Example #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
Example #2
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 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
Example #5
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})
Example #6
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})
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])

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:
Example #9
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
__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()