Exemple #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
Exemple #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
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
Exemple #5
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'])
Exemple #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')
Exemple #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')
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!')
Exemple #9
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,})
Exemple #10
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})
Exemple #11
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})
Exemple #12
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()
Exemple #13
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,})
    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])


time = obj_json['current_condition']['hour']
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')
        print(address)

        if address.find("look under") >= 0:
            continue

        curpoi = sql.cursor()
    
        existing_data = cursor2.execute("SELECT * FROM BranchPOI WHERE id=?",
                                        [branch_id]).fetchone()

        if existing_data and existing_data["place_id"]:
            print("already found")
            continue

        places = nom.query(address);
        bank_place = None

        for place in places:
            if place["type"].find("bank") >= 0:
                print("found a bank")
            else:
                #print("not a bank")
                continue

            if place["display_name"].lower().find("Deutsche Bank".lower())>= 0:
                print("It's Deutsche Bank")
                bank_place = place
            else:
                print("not Deutsche Bank")
                continue
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
Exemple #18
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})
Exemple #19
0
    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])

time = obj_json['current_condition']['hour']
Exemple #20
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})
__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()