Exemplo n.º 1
0
def query(query_string):
    nom = Nominatim()
    results = nom.query(query_string) if query != '' else None

    if results is not None and len(results) >= 1:
        return results
    else:
        return None
Exemplo n.º 2
0
def query(query_string):
    nom = Nominatim()
    results = nom.query(query_string) if query != '' else None

    if results is not None and len(results) >= 1:
        return results
    else:
        return None
Exemplo n.º 3
0
def locate_places():
	nom = Nominatim()
	for team in db.teams.find():
		if 'coords' not in team:
			results = nom.query('{} {} {}'.format(team['town'], team['state'], team['country']))
			place = results[0]
			team['coords'] = [float(place['lon']), float(place['lat'])]
			db.teams.save(team)
			click.echo(team['coords'])
def get_coords(location):
    nom = Nominatim()
    try:
        data = nom.query(location)
        entity = data[0]
        result = [entity['lat'], entity['lon']]
    except:
        result = False
    return result
def get_coords(location):
    nom = Nominatim()
    try:
        data = nom.query(location)
        entity = data[0]
        result = [entity['lat'], entity['lon']]
    except:
        result = False
    return result
Exemplo n.º 6
0
def nominatim_weather_daily(location, token_id, cnt):
    """
     Downloads weather forecast for location for number of days wanted.

     :param location: location to search forecast for.
     :type location: str.
     :param token_id: user's token for website.
     :type token_id: str.
     :param cnt: number of days for downloading forecst, 14 by default.
     :type cnt: int
     :returns: None. Prints weather data.
     """

    if cnt > 16 or cnt < 1:
        raise ValueError("Weather forecast may be provided for up to 16 days")
    if type(location) == str:
        nom = Nominatim()
        coordinates = nom.query(location)
        output = ''

        if coordinates:
            lat = coordinates[0]['lat']
            lon = coordinates[0]['lon']

            url = 'http://api.openweathermap.org/data/2.5/find'
            token = token_id
            querystring = {'lat': lat, 'lon': lon, 'cnt': cnt, 'appid': token}
            response = requests.request('GET', url, params=querystring)
            data = response.json()
            if data == {
                    'cod':
                    401,
                    'message':
                    'Invalid API key. '
                    'Please see http://openweathermap.org/faq#error401 '
                    'for more info.'
            }:
                raise NameError('You have inputted invalid token id!')
            else:
                if location != data['list'][0]['name']:
                    output += 'Weather for {} in {}\n'.format(
                        location, data['list'][0]['name'])
                else:
                    output += 'Weather in {} for {} days\n'.format(
                        location, data['count'])
                for i in range(cnt):
                    output += 'Weather for day {}: {}\n'.format(
                        i + 1, data['list'][i]['weather'][0]['description'])
                    for j in data['list'][i]['main'].items():
                        output += (formating(j) + '\n')
            return output
        else:
            raise NameError('no such location found!')
    else:
        raise TypeError('"location" should be of type str')
Exemplo n.º 7
0
def nominatim_weather(location, token_id):
    """
    Downloads current weather and 3 hour forecast for location.

    :param location: location to search forecast for.
    :type location: str.
    :param token_id: user's token for website.
    :type token_id: str.
    :returns: None. Prints weather data.
    """
    if type(location) == str:
        nom = Nominatim()
        coordinates = nom.query(location)
        if coordinates:
            lat = coordinates[0]['lat']
            lon = coordinates[0]['lon']

            url = 'http://api.openweathermap.org/data/2.5/weather'
            token = token_id
            querystring = {'lat': lat, 'lon': lon, 'appid': token}
            response = requests.request('GET', url, params=querystring)
            data = response.json()
            if data == {
                    'cod':
                    401,
                    'message':
                    'Invalid API key. '
                    'Please see http://openweathermap.org/faq#error401 '
                    'for more info.'
            }:
                raise NameError('You have inputted invalid token id!')
            else:
                print('weather in {}: {}'.format(
                    location, data['weather'][0]['description']))
                for i in data['main'].items():
                    print('{}: {}'.format(i[0], i[1]))

                url_2 = 'http://api.openweathermap.org/data/2.5/forecast'
                response_2 = requests.request('GET', url_2, params=querystring)
                data_2 = response_2.json()
                days = 5
                j = 39
                while j < len(data_2['list']):
                    print('weather forecast for {} days in {}: {}'.format(
                        days, location,
                        data_2['list'][j]['weather'][0]['description']))
                    for i in data_2['list'][j]['main'].items():
                        print('{}: {}'.format(i[0], i[1]))
                    j += 1
        else:
            raise NameError('no such location found!')
    else:
        raise TypeError('"location" should be of type str')
Exemplo n.º 8
0
    def add_provider(self, provider):
        for geocoder in self.geocoders:
            type = provider.type
            if type == 'user':
                type = 'cartociudad'
            if geocoder.has_key(type):
                geocoder[type].append(provider)
                return

        geocoder = {}

        if provider.type == 'new_cartociudad':
            geocoder[provider.type] = CartoCiudad2(provider)
            self.geocoders.append(geocoder)

        if provider.type == 'nominatim':
            geocoder[provider.type] = Nominatim(provider)
            self.geocoders.append(geocoder)

        if provider.type == 'googlemaps':
            geocoder[provider.type] = GoogleMaps(provider)
            self.geocoders.append(geocoder)

        if provider.type == 'cartociudad' or provider.type == 'user':
            geocoder['cartociudad'] = Cartociudad(provider, provider.type)
            self.geocoders.append(geocoder)
Exemplo n.º 9
0
 def testReverseExtratags(self):
     with self.assertRaises(InvalidParameterException):
         Nominatim(
             **{
                 "operation": self.reverse,
                 "latitude": self.latitude,
                 "longitude": self.longitude,
                 "extratags": True
             })
Exemplo n.º 10
0
def main():
    # creates api object
    api = Nominatim()
    # list to hold location
    zipCode = input("Enter a US zip code: ")
    # location = json.dumps(api.query(zipCode), indent=2)
    query = api.query(zipCode)
    isinvalid = True
    if query:
        for loc in query:
            loc = dict(loc)
            # Verify it is a 'postcode' and in 'United States'
            if (loc.get('type') == 'postcode'
                ) and 'United States' in loc.get('display_name'):
                location = list(loc.get('display_name').split(',')[0:3])
                # prints in readable format
                print(
                    f'The zip code, {zipCode}, is located at: {location[0]},{location[1]},{location[2]}'
                )
                isinvalid = False
                break

    if isinvalid:
        print(f'Zip code, {zipCode}, is invalid!')
Exemplo n.º 11
0
 def guess_the_projection(points, state=None, spatial_reference_query=None, city=None, conversion=None):
     epsgs_hits = []
     if spatial_reference_query is None:
         spatial_reference_query = state
     epsgs = SpatialReference.epsg_search(spatial_reference_query)
     y_min, y_max, x_min, x_max = Nominatim.nominatim_get_bounding_box_of(state=state, city=city)
     for epsg in epsgs:
         epsg_hit = 0
         for p in points:
             try:
                 x, y = SpatialReference.convert_spatial_reference(p[0], p[1], epsg[0], 4326, conversion=conversion)
             except:
                 print "Could not find EPSG:'%s'" % epsg[0]
                 break
             # print x, x_min, x_max
             if y_min < y < y_max and x_min < x < x_max:
                 epsg_hit += 1
         epsgs_hits.append((epsg[0], epsg_hit))
     epsgs_hits.sort(key=lambda x: x[1], reverse=True)
     return epsgs_hits
Exemplo n.º 12
0
def insertDataImage(request):

    if request.method == 'POST': # If the form has been submitted...
        stationform = StationForm(request.user.get_username(),request.POST, request.FILES) # A form bound to the POST data
        nominatimform = NominatimForm(request.POST) # A form bound to the POST data
        form = ImageForm(request.POST, request.FILES) # A form bound to the POST data

        if stationform.is_valid(): # All validation rules pass

            slug=stationform.cleaned_data['station_slug']
            if slug:
                station=StationMetadata.objects.get(ident__username=request.user.username,slug=slug)
                #stationlat=station.lat
                #stationlon=station.lon
                POST=request.POST.copy()
                POST['geom']= str(Point(station.lon,station.lat))
                stationform = StationForm(request.user.get_username(),POST, request.FILES) # A form bound to the new data
                form = ImageForm(POST, request.FILES) # A form bound to the new data
                return render(request, 'insertdata/form.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform})
        else:
            stationform = StationForm(request.user.get_username())
            return render(request, 'insertdata/form.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform,"invalid":True})

        if nominatimform.is_valid(): # All validation rules pass

            address=nominatimform.cleaned_data['address']
            if address:
                nom = Nominatim(base_url="http://nominatim.openstreetmap.org",referer= get_current_site(request))
                result=nom.query(address,limit=1,countrycodes="IT")
                if len(result) >= 1:
                    lat= result[0]["lat"]
                    lon= result[0]["lon"]
                    address= result[0]["display_name"]
                    POST=request.POST.copy()
                    POST['geom']= str(Point(float(lon),float(lat)))
                    POST['address']= address
                    stationform = StationForm(request.user.get_username(),POST, request.FILES) # A form bound to the new data
                    nominatimform = NominatimForm(POST) # A form bound to the new data
                    form = ImageForm(POST, request.FILES) # A form bound to the new data
                return render(request, 'insertdata/form.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform})
        else:
            nominatimform = NominatimForm()
            return render(request, 'insertdata/form.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform,"invalid":True})

        if form.is_valid(): # All validation rules pass

            if True:
                from rmap import exifutils
                comment=form.cleaned_data['comment']
                geom=form.cleaned_data['geom']
                image=request.FILES['image']
                dt=datetime.utcnow().replace(microsecond=0)
                lon=geom['coordinates'][0]
                lat=geom['coordinates'][1]
                image=image.read()

                body=exifutils.setgeoimage(image,lat,lon,imagedescription=request.user.username,usercomment=comment)

            else:
                import pexif
                img = pexif.JpegFile.fromString(handle_uploaded_file(image).encode("utf8"))
                exif = img.get_exif()
                if exif:
                    primary = exif.get_primary()
                    if not exif is None or not primary is None:

                        primary.ImageDescription = str(request.user.username)
                        #primary.ExtendedEXIF.UserComment = "UNICODE"+chr(0x00)+str(comment)
                        primary.ExtendedEXIF.UserComment = chr(0x55)+chr(0x4E)+chr(0x49)+chr(0x43)+chr(0x4F)+chr(0x44)+chr(0x45)+chr(0x00)+str(comment)
                        img.set_geo(lat,lon)
                        
                        #        try:
                        #            print primary.DateTime
                        #        except:
                        #            print "DateTime not present"

                        primary.DateTime=datetime.utcnow().strftime("%Y:%m:%d %H:%M:%S")
                        #        print primary.DateTime
                        body=img.writeString()


            #grimages=GeorefencedImage.objects.filter(ident__username=ident)
            #grimages=GeorefencedImage.objects.filter(id=1)


            #f = NamedTemporaryFile(delete=False)
            #image = File(f)
            #image.write(body)
            #f.close()
            #os.unlink(f.name)

            if True:
                #inserimento diretto in DB

                geoimage=GeorefencedImage(active=True,geom = geom,comment=comment,ident=request.user,
                                      date=dt, category = CATEGORY_CHOICES[1])

                geoimage.image.save('geoimage.jpg',ContentFile(body))

                geoimage.save()

            else:
                # invio ad AMQP

                #quale utente usare per AMQP; ho l'utente ma non la password
                #bisognerebbe abilitare tutti gli admin a pubblicare immagini e qui usare amqpuser

                #user=request.user.username,
                user=rmap.settings.amqpuser
                password=rmap.settings.amqppassword

                rmap.rmap_core.send2amqp(body=body,
                                         user=user,
                                         password=password,
                                         host="localhost",
                                         exchange="photo",routing_key="photo")

            #return HttpResponseRedirect(reverse('geoimage-ident-id', args=[request.user.username,geoimage.pk]))
            return HttpResponseRedirect(reverse('geoimage-ident', args=[request.user.username]))

        else:

            form = ImageForm() # An unbound form
            return render(request, 'insertdata/form.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform,"invalid":True})

    else:
            stationform = StationForm(request.user.get_username()) # An unbound form
            nominatimform = NominatimForm() # An unbound form
            form = ImageForm() # An unbound form
            return render(request, 'insertdata/form.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform})
Exemplo n.º 13
0
def addressToLatLong(addr):
    nom = Nominatim()
    result = nom.query(addr)
    if len(result) >= 1:
        return float(result[0]['lat']), float(result[0]['lon'])
    return None, None
Exemplo n.º 14
0
def insertNewStation(request):

    if request.method == 'POST': # If the form has been submitted...

        nominatimform = NominatimForm(request.POST) # A form bound to the POST data
        newstationform = NewStationForm(request.POST) # A form bound to the POST data

        if nominatimform.is_valid(): # All validation rules pass

            address=nominatimform.cleaned_data['address']
            if address:
                nom = Nominatim(base_url="http://nominatim.openstreetmap.org",referer=get_current_site(request))
                result=nom.query(address,limit=1,countrycodes="IT")
                if len(result) >= 1:
                    lat= result[0]["lat"]
                    lon= result[0]["lon"]
                    address= result[0]["display_name"]
                    request.POST['geom']= str(Point(float(lon),float(lat)))
                    request.POST['address']= address
                return render(request, 'insertdata/newstationform.html',{'nominatimform':nominatimform,'newstationform':newstationform})
        else:
            nominatimform = NominatimForm()
            return render(request, 'insertdata/newstationform.html',{'nominatimform':nominatimform,'newstationform':newstationform,"invalid":True})


        if newstationform.is_valid(): # All validation rules pass
            
            geom=newstationform.cleaned_data['geom']
            lon=geom['coordinates'][0]
            lat=geom['coordinates'][1]
            ident=request.user.username

            name=newstationform.cleaned_data['name']

            if name:
                try:
                    print "new station:", name,ident,lon,lat

                    mystation=StationMetadata(slug=slugify(name),name=name)
                    user=User.objects.get(username=ident)
                    mystation.ident=user
                    mystation.lat=lat
                    mystation.lon=lon
                    mystation.active=True

                    mystation.save()

                except:
                    return render(request, 'insertdata/newstationform.html',{'nominatimform':nominatimform,'newstationform':newstationform,"error":True})

            return render(request, 'insertdata/newstationform.html',{'nominatimform':nominatimform,'newstationform':newstationform})

        else:

            print "invalid form"
            form = NewStationForm() # An unbound form
            return render(request, 'insertdata/newstationform.html',{'nominatimform':nominatimform,'newstationform':newstationform,"invalid":True})

    else:
        nominatimform = NominatimForm() # An unbound form
        newstationform = NewStationForm() # An unbound form
        return render(request, 'insertdata/newstationform.html',{'nominatimform':nominatimform,'newstationform':newstationform,})
Exemplo n.º 15
0
else:
    print "Error on format. Only 'json' and 'csv' are alowed. Program stop"
    sys.exit()
    
output_path = ""

if args['path'] == "./":
    output_path = args['path'] + args['location'].lower().replace(" ", "_") + "." + args['format']
else:
    output_path = args['path']

################################################
#                   WEATHER
################################################

my_city = Nominatim()
city_detail = my_city.query(args['location'])[0] ## Take the best city match name

print "Weather forecast for : " + city_detail['display_name']

my_url = "http://www.prevision-meteo.ch/services/json/lat=" + city_detail['lat'] + "lng=" + city_detail['lon']

obj_string = urllib2.urlopen(my_url).read()
obj_json = json.loads(obj_string)

date =  obj_json['current_condition']['date']
year = int(obj_json['current_condition']['date'][6:])
month = int(obj_json['current_condition']['date'][3:5])
day = int(obj_json['current_condition']['date'][0:2])

Exemplo n.º 16
0
__author__ = 'wickes1'

from nominatim import Nominatim

nom = Nominatim()

result = nom.query("1904 Oliver Dr, Champaign, IL")

result


def foo(fuzzy):
    """pass it something fuzzy and it'll return five of that"""
    return fuzzy * 5


print foo()
Exemplo n.º 17
0
 def testReverseMissingLongitude(self):
     with self.assertRaises(MissingParameterException):
         Nominatim(**{"operation": self.reverse, "latitude": self.latitude})
Exemplo n.º 18
0
from .models import *
from django.contrib.gis.geos import Point
from django.contrib.gis.measure import Distance
from geopy.distance import distance as geopy_distance
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.gis.measure import D
from django.http import HttpResponse
from django import template
from nominatim import Nominatim
from geopy.geocoders import Nominatim as geonom
import random
import os
import re
from base64 import b64decode
from django.core.files.base import ContentFile
nom = Nominatim()


def handle_uploaded_file(f, category_name):
    category_name = category_name.replace(' ', '-')
    fname = '{}_{}'.format(random.randint(0, 100), str(f))
    directory = 'media/supermarket_crawlers/{}/images'.format(category_name)
    dest = '{}/{}'.format(directory, fname)
    os.system('mkdir -p {}'.format(os.path.join(settings.MEDIA_ROOT,
                                                directory)))
    with open(os.path.join(settings.MEDIA_ROOT, dest), 'wb+') as g:
        g.write(f.read())

    return dest

Exemplo n.º 19
0
 def testWrongOperation(self):
     with self.assertRaises(InvalidParameterException):
         Nominatim(**{"operation": "unknown", "address": self.address})
Exemplo n.º 20
0
def insertDataImage(request):

    if request.method == 'POST': # If the form has been submitted...
        stationform = StationForm(request.user.get_username(),request.POST, request.FILES) # A form bound to the POST data
        nominatimform = NominatimForm(request.POST) # A form bound to the POST data
        form = ImageForm(request.POST, request.FILES) # A form bound to the POST data

        if stationform.is_valid(): # All validation rules pass

            slug=stationform.cleaned_data['station_slug']
            if slug:
                station=StationMetadata.objects.get(ident__username=request.user.username,slug=slug)
                #stationlat=station.lat
                #stationlon=station.lon
                request.POST['geom']= str(Point(station.lon,station.lat))
                return render(request, 'insertdata/form.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform})
        else:
            stationform = StationForm(request.user.get_username())
            return render(request, 'insertdata/form.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform,"invalid":True})

        if nominatimform.is_valid(): # All validation rules pass

            address=nominatimform.cleaned_data['address']
            if address:
                nom = Nominatim(base_url="http://nominatim.openstreetmap.org")
                result=nom.query(address,limit=1,countrycodes="IT")
                if len(result) >= 1:
                    lat= result[0]["lat"]
                    lon= result[0]["lon"]
                    address= result[0]["display_name"]
                    request.POST['geom']= str(Point(float(lon),float(lat)))
                    request.POST['address']= address
                return render(request, 'insertdata/form.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform})
        else:
            nominatimform = NominatimForm()
            return render(request, 'insertdata/form.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform,"invalid":True})

        if form.is_valid(): # All validation rules pass

            if True:
                from rmap import exifutils
                comment=form.cleaned_data['comment']
                geom=form.cleaned_data['geom']
                image=request.FILES['image']
                dt=datetime.utcnow().replace(microsecond=0)
                lon=geom['coordinates'][0]
                lat=geom['coordinates'][1]
                image=image.read()

                body=exifutils.setgeoimage(image,lat,lon,imagedescription=request.user.username,usercomment=comment)

            else:
                import pexif
                img = pexif.JpegFile.fromString(handle_uploaded_file(image).encode("utf8"))
                exif = img.get_exif()
                if exif:
                    primary = exif.get_primary()
                    if not exif is None or not primary is None:

                        primary.ImageDescription = str(request.user.username)
                        #primary.ExtendedEXIF.UserComment = "UNICODE"+chr(0x00)+str(comment)
                        primary.ExtendedEXIF.UserComment = chr(0x55)+chr(0x4E)+chr(0x49)+chr(0x43)+chr(0x4F)+chr(0x44)+chr(0x45)+chr(0x00)+str(comment)
                        img.set_geo(lat,lon)
                        
                        #        try:
                        #            print primary.DateTime
                        #        except:
                        #            print "DateTime not present"

                        primary.DateTime=datetime.utcnow().strftime("%Y:%m:%d %H:%M:%S")
                        #        print primary.DateTime
                        body=img.writeString()


            #grimages=GeorefencedImage.objects.filter(ident__username=ident)
            #grimages=GeorefencedImage.objects.filter(id=1)


            #f = NamedTemporaryFile(delete=False)
            #image = File(f)
            #image.write(body)
            #f.close()
            #os.unlink(f.name)

            if True:
                #inserimento diretto in DB

                geoimage=GeorefencedImage(active=True,geom = geom,comment=comment,ident=request.user,
                                      date=dt, category = CATEGORY_CHOICES[1])

                geoimage.image.save('geoimage.jpg',ContentFile(body))

                geoimage.save()

            else:
                # invio ad AMQP

                #quale utente usare per AMQP; ho l'utente ma non la password
                #bisognerebbe abilitare tutti gli admin a pubblicare immagini e qui usare amqpuser

                #user=request.user.username,
                user=rmap.settings.amqpuser
                password=rmap.settings.amqppassword

                import rmap.rmap_core
                rmap.rmap_core.send2amqp(body=body,
                                         user=user,
                                         password=password,
                                         host="localhost",
                                         exchange="photo",routing_key="photo")

            #return HttpResponseRedirect(reverse('geoimage-ident-id', args=[request.user.username,geoimage.pk]))
            return HttpResponseRedirect(reverse('geoimage-ident', args=[request.user.username]))

        else:

            form = ImageForm() # An unbound form
            return render(request, 'insertdata/form.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform,"invalid":True})

    else:
            stationform = StationForm(request.user.get_username()) # An unbound form
            nominatimform = NominatimForm() # An unbound form
            form = ImageForm() # An unbound form
            return render(request, 'insertdata/form.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform})
from time import sleep
import sys
from pprint import pformat

sys.path.insert(0,"./python-nominatim")
from nominatim import Nominatim

sql = sqlite3.connect("deutschebank.sqlite3")
sql.row_factory = sqlite3.Row
cursor = sql.cursor()

sql.execute("CREATE TABLE IF NOT EXISTS BranchPOI(id TEXT, place_id TEXT,"
            "data TEXT)")


nom = Nominatim()


branches = cursor.execute("SELECT id FROM BranchInfo GROUP BY id")

for branch_id_row in branches:
    branch_id = branch_id_row[0]

    cursor2 = sql.cursor()
    
    attributes = cursor2.execute("SELECT * FROM BranchInfo WHERE id=?",
                                 [branch_id])

    branch = {}

    for attribute in cursor2:
from nominatim import Nominatim, NominatimReverse
import json
import csv
import pandas as pd

nom = Nominatim()

with open('neighborhood.csv', 'wb') as neighborhoodFile: #stores neighborhoods as new csv file
    df = pd.read_csv('sample_coords.csv') #parses in these coordinates for geocoding
    # lat = df.ix[:,14]
    # lon = df.ix[:,13]
    for i in range(0, len(df)):
        lat = df.ix[i,1]
        lon = df.ix[i,0]
        coords = str(lon) + ", " + str(lat)
        result = nom.query(coords) #start geocode query for each entry
        neighborhoodDetails = result[0]['display_name'] #obtain first query elements
        neighborhoodList = neighborhoodDetails.split(",") #convert unicode to list elements separated by ","
        neighborhood = neighborhoodList[2]
        if coords != "nan, nan":
            output = neighborhood
            neighborhoodFile.write(output)
            neighborhoodFile.write('\n')
            print i
        else:
            output = " "
            neighborhoodFile.write(output)
            neighborhoodFile.write('\n')
Exemplo n.º 23
0
def insertDataManualData(request):

    if request.method == 'POST': # If the form has been submitted...

        #stationlat=None
        #stationlon=None

        stationform = StationForm(request.user.get_username(),request.POST) # A form bound to the POST data
        nominatimform = NominatimForm(request.POST) # A form bound to the POST data
        form = ManualForm(request.POST) # A form bound to the POST data

        if stationform.is_valid(): # All validation rules pass

            slug=stationform.cleaned_data['station_slug']
            if slug:
                station=StationMetadata.objects.get(ident__username=request.user.username,slug=slug)
                #stationlat=station.lat
                #stationlon=station.lon
                POST=request.POST.copy()
                POST['geom']= str(Point(station.lon,station.lat))
                POST['coordinate_slug']= slug
                stationform = StationForm(request.user.get_username(),POST) # A form bound to the new data
                form = ManualForm(POST) # A form bound to the new data
                return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform})
        else:
            stationform = StationForm(request.user.get_username())
            return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform,"invalid":True})

        if nominatimform.is_valid(): # All validation rules pass

            address=nominatimform.cleaned_data['address']
            if address:
                nom = Nominatim(base_url="http://nominatim.openstreetmap.org",referer=get_current_site(request))
                result=nom.query(address,limit=1,countrycodes="IT")
                if result is not None:
                    if len(result) >= 1:
                        lat= result[0]["lat"]
                        lon= result[0]["lon"]
                        address= result[0]["display_name"]
                        POST=request.POST.copy()
                        POST['geom']= str(Point(float(lon),float(lat)))
                        POST['address']= address
                        nominatimform = NominatimForm(POST) # A form bound to the new data
                        stationform = StationForm(request.user.get_username(),POST) # A form bound to the new data
                        form = ManualForm(POST) # A form bound to the new data
                return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform})
        else:
            nominatimform = NominatimForm()
            return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform,"invalid":True})

        if form.is_valid(): # All validation rules pass
            
            geom=form.cleaned_data['geom']
            lon=geom['coordinates'][0]
            lat=geom['coordinates'][1]
            dt=datetime.utcnow().replace(microsecond=0)
            ident=request.user.username

            #if (not stationlat is None):
            #    if (stationlat != lat):
            #        stationform = StationForm(request.user.get_username())
            #        return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,"invalid":True})
            #if (not stationlon is None):
            #    if (stationlon != lon):
            #        stationform = StationForm(request.user.get_username())
            #        return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,"invalid":True})

            datavar={}
            value=form.cleaned_data['presentweather']
            if (value != ""):
                datavar["B20003"]={"t": dt,"v": str(value)}

            value=form.cleaned_data['snow_height']
            if (not value is None):
                value=int(value*10)
                datavar["B13013"]={"t": dt,"v": str(value)}

            value=form.cleaned_data['visibility']
            if (not value is None):
                value=int(value/10)
                datavar["B20001"]={"t": dt,"v": str(value)}

            print "datavar:",datavar
            if (len(datavar)>0):
                try:

                    user=rmap.settings.mqttuser
                    password=rmap.settings.mqttpassword
                    prefix=rmap.settings.topicreport

                    slug=form.cleaned_data['coordinate_slug']
                    if (slug):
                        network="fixed"
                    else:
                        network="mobile"

                    print "<",slug,">","prefix:",prefix

                    mqtt=rmapmqtt(ident=ident,lon=lon,lat=lat,network=network,host="localhost",port=1883,prefix=prefix,maintprefix=prefix,username=user,password=password)
                    mqtt.data(timerange="254,0,0",level="1,-,-,-",datavar=datavar)
                    mqtt.disconnect()

                    form = ManualForm() # An unbound form
                except:
                    return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform,"error":True})

            return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform})

        else:

            print "invalid form"
            form = ManualForm() # An unbound form
            return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform,"invalid":True})

    else:
        stationform = StationForm(request.user.get_username()) # An unbound form
        nominatimform = NominatimForm() # An unbound form
        form = ManualForm() # An unbound form
        return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform})
Exemplo n.º 24
0
 def testNoOperation(self):
     with self.assertRaises(MissingParameterException):
         Nominatim(**{"address": self.address})
Exemplo n.º 25
0
def insertNewStation(request):

    if request.method == 'POST': # If the form has been submitted...

        nominatimform = NominatimForm(request.POST) # A form bound to the POST data
        newstationform = NewStationForm(request.POST) # A form bound to the POST data

        if nominatimform.is_valid(): # All validation rules pass

            address=nominatimform.cleaned_data['address']
            if address:
                nom = Nominatim(base_url="http://nominatim.openstreetmap.org",referer=get_current_site(request))
                result=nom.query(address,limit=1,countrycodes="IT")
                if len(result) >= 1:
                    lat= result[0]["lat"]
                    lon= result[0]["lon"]
                    address= result[0]["display_name"]
                    POST=request.POST.copy()
                    POST['geom']= str(Point(float(lon),float(lat)))
                    POST['address']= address
                    newstationform = NewStationForm(POST) # A form bound to the new data
                    nominatimform = NominatimForm(POST) # A form bound to the new data

                return render(request, 'insertdata/newstationform.html',{'nominatimform':nominatimform,'newstationform':newstationform})
        else:
            nominatimform = NominatimForm()
            return render(request, 'insertdata/newstationform.html',{'nominatimform':nominatimform,'newstationform':newstationform,"invalid":True})


        if newstationform.is_valid(): # All validation rules pass
            
            geom=newstationform.cleaned_data['geom']
            lon=geom['coordinates'][0]
            lat=geom['coordinates'][1]
            ident=request.user.username
            name=newstationform.cleaned_data['name']
            slug=slugify(name)
            board_slug="default"
            template=newstationform.cleaned_data['template']
            
            if name:
                try:
                    try:
                        print "del station:", ident,slug,ident
                        mystation=StationMetadata.objects.get(slug__exact=slug,ident__username=ident)
                        mystation.delete()
                    except Exception as e:
                        print e
                    
                    print "new station:", name,ident,lon,lat

                    mystation=StationMetadata(slug=slug,name=name)
                    user=User.objects.get(username=ident)
                    mystation.ident=user
                    mystation.lat=rmap.rmap_core.truncate(lat,5)
                    mystation.lon=rmap.rmap_core.truncate(lon,5)
                    mystation.active=True

                    mystation.clean()
                    mystation.save()

                    rmap.rmap_core.addboard(station_slug=slug,username=ident,board_slug=board_slug,activate=True
                                 ,serialactivate=False
                                 ,mqttactivate=True, mqttserver="rmap.cc", mqttusername=ident, mqttpassword="******", mqttsamplerate=30
                                 ,bluetoothactivate=False, bluetoothname="HC-05"
                                ,amqpactivate=False, amqpusername="******", amqppassword="******", amqpserver="rmap.cc", queue="rmap", exchange="rmap"
                                 ,tcpipactivate=False, tcpipname="master", tcpipntpserver="ntpserver"
                    )
                    
                    rmap.rmap_core.addsensors_by_template(
                        station_slug=slug
                        ,username=ident
                        ,board_slug=board_slug
                        ,template=template)
                    
                except Exception as e:
                    print e
                    return render(request, 'insertdata/newstationform.html',{'nominatimform':nominatimform,'newstationform':newstationform,"error":True})

            return render(request, 'insertdata/newstationform.html',{'nominatimform':nominatimform,'newstationform':newstationform,"station":mystation})

        else:

            print "invalid form"
            form = NewStationForm() # An unbound form
            return render(request, 'insertdata/newstationform.html',{'nominatimform':nominatimform,'newstationform':newstationform,"invalid":True})

    else:
        nominatimform = NominatimForm() # An unbound form
        newstationform = NewStationForm() # An unbound form
        return render(request, 'insertdata/newstationform.html',{'nominatimform':nominatimform,'newstationform':newstationform,})
Exemplo n.º 26
0
 def testNoParameters(self):
     with self.assertRaises(MissingParameterException):
         Nominatim(**{})
Exemplo n.º 27
0
    print "Error on format. Only 'json' and 'csv' are alowed. Program stop"
    sys.exit()

output_path = ""

if args['path'] == "./":
    output_path = args['path'] + args['location'].lower().replace(
        " ", "_") + "." + args['format']
else:
    output_path = args['path']

################################################
#                   WEATHER
################################################

my_city = Nominatim()
city_detail = my_city.query(
    args['location'])[0]  ## Take the best city match name

print "Weather forecast for : " + city_detail['display_name']

my_url = "http://www.prevision-meteo.ch/services/json/lat=" + city_detail[
    'lat'] + "lng=" + city_detail['lon']

obj_string = urllib2.urlopen(my_url).read()
obj_json = json.loads(obj_string)

date = obj_json['current_condition']['date']
year = int(obj_json['current_condition']['date'][6:])
month = int(obj_json['current_condition']['date'][3:5])
day = int(obj_json['current_condition']['date'][0:2])
Exemplo n.º 28
0
 def testGeocodeMissingAddress(self):
     with self.assertRaises(MissingParameterException):
         Nominatim(**{"operation": self.geocode})
Exemplo n.º 29
0
def insertDataManualData(request):

    if request.method == 'POST': # If the form has been submitted...

        #stationlat=None
        #stationlon=None

        stationform = StationForm(request.user.get_username(),request.POST) # A form bound to the POST data
        nominatimform = NominatimForm(request.POST) # A form bound to the POST data
        form = ManualForm(request.POST) # A form bound to the POST data

        if stationform.is_valid(): # All validation rules pass

            slug=stationform.cleaned_data['station_slug']
            if slug:
                station=StationMetadata.objects.get(ident__username=request.user.username,slug=slug)
                #stationlat=station.lat
                #stationlon=station.lon
                request.POST['geom']= str(Point(station.lon,station.lat))
                request.POST['coordinate_slug']= slug
                return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform})
        else:
            stationform = StationForm(request.user.get_username())
            return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform,"invalid":True})

        if nominatimform.is_valid(): # All validation rules pass

            address=nominatimform.cleaned_data['address']
            if address:
                nom = Nominatim(base_url="http://nominatim.openstreetmap.org")
                result=nom.query(address,limit=1,countrycodes="IT")
                if len(result) >= 1:
                    lat= result[0]["lat"]
                    lon= result[0]["lon"]
                    address= result[0]["display_name"]
                    request.POST['geom']= str(Point(float(lon),float(lat)))
                    request.POST['address']= address
                return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform})
        else:
            nominatimform = NominatimForm()
            return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform,"invalid":True})

        if form.is_valid(): # All validation rules pass
            
            geom=form.cleaned_data['geom']
            lon=geom['coordinates'][0]
            lat=geom['coordinates'][1]
            dt=datetime.utcnow().replace(microsecond=0)
            ident=request.user.username

            #if (not stationlat is None):
            #    if (stationlat != lat):
            #        stationform = StationForm(request.user.get_username())
            #        return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,"invalid":True})
            #if (not stationlon is None):
            #    if (stationlon != lon):
            #        stationform = StationForm(request.user.get_username())
            #        return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,"invalid":True})

            datavar={}
            value=form.cleaned_data['presentweather']
            if (value != ""):
                datavar["B20003"]={"t": dt,"v": str(value)}

            value=form.cleaned_data['snow_height']
            if (not value is None):
                value=float(value*10.)
                datavar["B13013"]={"t": dt,"v": str(value)}

            value=form.cleaned_data['visibility']
            if (not value is None):
                value=float(value/10.)
                datavar["B20001"]={"t": dt,"v": str(value)}

            print datavar
            if (len(datavar)>0):
                try:

                    user=rmap.settings.mqttuser
                    password=rmap.settings.mqttpassword

                    slug=form.cleaned_data['coordinate_slug']
                    if (slug):
                        prefix="rmap"
                    else:
                        prefix="mobile"

                    print "<",slug,">","prefix:",prefix

                    mqtt=rmapmqtt(ident=ident,lon=lon,lat=lat,network="rmap",host="localhost",port=1883,prefix=prefix,maintprefix=prefix,username=user,password=password)
                    mqtt.data(timerange="254,0,0",level="1,-,-,-",datavar=datavar)
                    mqtt.disconnect()

                    form = ManualForm() # An unbound form
                except:
                    return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform,"error":True})

            return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform})

        else:

            print "invalid form"
            form = ManualForm() # An unbound form
            return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform,"invalid":True})

    else:
        stationform = StationForm(request.user.get_username()) # An unbound form
        nominatimform = NominatimForm() # An unbound form
        form = ManualForm() # An unbound form
        return render(request, 'insertdata/manualdataform.html',{'form': form,'stationform':stationform,'nominatimform':nominatimform})
Exemplo n.º 30
0
__author__ = 'wickes1'


from nominatim import Nominatim

nom = Nominatim()

result = nom.query("1904 Oliver Dr, Champaign, IL")

result

def foo(fuzzy):
    """pass it something fuzzy and it'll return five of that"""
    return fuzzy * 5

print foo()