def get_ll(postal_code):
  if postal_code == None: return None
  geolocator = Nominatim()
  location = geolocator.geocode(postal_code)   # it seems that cannot write abbreviation here
  if location == None: return None
  al = str(location.latitude) + ', ' + str(location.longitude)
  return al
Esempio n. 2
0
def set_description(sender, instance, created=False, **kwargs):
    if created:
        try:
            geolocator = Nominatim()
            lat = instance.location.latitude
            lon = instance.location.longitude
            print('.....{}, {}........'.format(lat, lon))
            loc = geolocator.reverse([lat, lon])
            address = loc.address
            print(address)
            instance.description = address
            instance.save()
        except:
            try:
                geolocator = Nominatim()
                lat = instance.location.latitude
                lon = instance.location.longitude
                print('..........{}, {}........'.format(lat, lon))
                loc = geolocator.reverse([lat, lon])
                address = loc.address
                print(address)
                instance.description = address
                instance.save()
            except:
                print('......didnt work.......')
                instance.description = 'Location created on {}'.format(instance.date_added)
                instance.save()
                pass
Esempio n. 3
0
def tags():
    url = request.args["url"] 
    clarifai_api = ClarifaiApi()  # assumes environment variables are set.
    result = clarifai_api.tag_image_urls(url)
    results = result['results'][0]["result"]["tag"]["classes"]#[:3]

    client = foursquare.Foursquare(client_id='JEK02X44TGMNJSE0VC1UBEB4FRNNW3UMFQ4IQOPI4BAR2GXA', \
                                    client_secret='A2Z50VTUHHXEUYJBHCQKB1LXTNVVBYBQR4SDASVTXTWUMWXS') #foursquare shit

    address = request.args["address"] #address is currently a string
    geolocator = Nominatim()
    location = geolocator.geocode(address)
    newLocation = str(location.latitude) + str(", ") + str(location.longitude)
    
    
    # foursquare_dictionary = client.venues.explore(params={'ll': '40.7, -74', 'v': '20160402', 'query': results[0] + ',' + results[1] + ',' + results[2]})

    foursquare_dictionary = client.venues.explore(params={'ll': newLocation, 'v': '20160402', 'query': results[0] + ',' + results[1] + ',' + results[2]})

    #first place to eat
    # status1 = foursquare_dictionary['groups'][0]['items'][0]['venue']['hours']['status']
    address1 = foursquare_dictionary['groups'][0]['items'][0]['venue']['location']['formattedAddress']
    name = foursquare_dictionary['groups'][0]['items'][0]['venue']['name']

    #second place to eat
    address2 = foursquare_dictionary['groups'][0]['items'][1]['venue']['location']['formattedAddress']
   # status2 = foursquare_dictionary['groups'][0]['items'][1]['venue']['hours']['status']
    name1 = foursquare_dictionary['groups'][0]['items'][1]['venue']['name']

    return render_template('tags.html',\
                           newAddress1 = newAddress(address1), name = name,\
                           newAddress2 = newAddress(address2), name1 = name1,\
                           newLocation = newLocation)
def make_LatLonDict(tweet_lat_lon_dict, tweet_location_unique):

    geolocator = Nominatim()

    # Turn the user defined location place name into a geographic (lat,lon) location

    for i, placeName in enumerate(tweet_location_unique):
        if placeName not in tweet_lat_lon_dict:
            try:
                placeGeo  = geolocator.geocode(placeName)
            except Exception as E:
                print("exception happened", type(E), E)

            if i % 20 == 0:
                print(i)
            if placeGeo is not None:
                tweet_lat_lon_dict[placeName] = (placeGeo.latitude, placeGeo.longitude)
            else:
                tweet_lat_lon_dict[placeName] = (None, None)


    # How many location place names were not able to be turned into (lat,lon) locations?
    # Which names were they?
    print("The total (lat,lon) dictionary is %d items long." %(len(tweet_lat_lon_dict)))

    bad_place_names = [k for k,v in tweet_lat_lon_dict.items() if v == (None,None)]

    print("Of these, %d were unable to be converted into (lat,lon) coordinates. These were specifically the following locations: \n" %(len(bad_place_names)))
    print("\n".join(bad_place_names))

    # Write out the dictionary of place names and corresponding latitutes & longitudes to a JSON file
    with open('../data/Twitter_Zika_PlaceName_Geo_info.json', 'w') as twitterGeo_JSONFile:
        json.dump(tweet_lat_lon_dict, twitterGeo_JSONFile, indent=2)
def geo_tweets():

    geolocator = Nominatim()
    count =1
    tweets_list = db1.view('sentiment-analysis/get_tweet_ids')
    for doc in  db.view('sentiment-analysis/get_alltweets'):
        tw=doc.value
        if  (not_exist(tw['id'])== "true"):
    	    loc_point= tw['geo']
	    #print loc_point
	    try:
                location = geolocator.geocode(loc_point['coordinates'])
	        #print type(location)
	        try:
   	            print count ,location.address
                    modified_place={'geo_address': location.address}
                    place_update = {'place-mod': modified_place}
	            new_tw = tw.copy()
                    new_tw.update(place_update)
                    new_tw.update({'_id': tw['id_str']})
                    try:
                        db1.save(new_tw)
                    except:
                        print ("Tweet " + tw['id_str'] + " already exists !!!! " )
	        except:
                    print ("Returned Location is Empty !!!! " )
            except GeocoderTimedOut as e:
	        print("Error: geocode faied on input %s with message ")
		print loc_point['coordinates']
	else:
    	    print count, 'ALREADY EXIST!!'
        count =count+1
Esempio n. 6
0
def geocode_w(txt):
    time.sleep(16+scipy.randn(1))
    geoloc = Nominatim()
    print(txt)
    cded = geoloc.geocode(txt)
    geoloc = 0 
    return cded
Esempio n. 7
0
    def current_temp_will(self, message=None, location=None):
        """what's the temperature (in _______): I know how to tell you the temperature!"""
        geolocator = Nominatim()
        if location is None:
            forecast = forecastio.load_forecast(FORECAST_API_KEY, LINCOLN_LAT, LINCOLN_LNG, units="us")
            currently = forecast.currently()
            temp = currently.temperature
            feels_like = currently.apparentTemperature
            combined = "It's currently %sF and feels like %sF here in Lincoln, NE" % (temp, feels_like)

            self.save("local_temp", combined)

            if message:
                return self.say(combined, message=message)
        else:
            geolocation = geolocator.geocode(location)
            lat = geolocation.latitude
            lng = geolocation.longitude

            forecast = forecastio.load_forecast(FORECAST_API_KEY, lat, lng, units="us")
            currently = forecast.currently()
            temp = currently.temperature
            feels_like = currently.apparentTemperature
            full_address = geolocation.address
            combined = "It's currently %s degrees and feels like %s degrees in %s" % (temp, feels_like, full_address)

            self.save(full_address + "_temp", combined)

            if message:
                self.say(combined, message=message)
Esempio n. 8
0
def get_nearest(user_location, address_list, maps_api_key=None):
    ''' This function returns the nearest address to the
        user location. It compares the user location with an
        existing list of addresses.

        Args:
            user_location (string): can be either the zip code or address.
            maps_api_key (string): optional google maps api key.
            address_list (tuple): list of addresses

        Returns:
            string: the nearest address to the user_location or false if the address list is not a tuple
    '''
    if isinstance(address_list, tuple):
        if len(address_list) > 1:
            if maps_api_key:
                geolocator = GoogleV3(maps_api_key, timeout=10)
            else:
                geolocator = Nominatim(timeout=10)
            user_location = geolocator.geocode(user_location)
            user_latlon = (user_location.latitude, user_location.longitude)
            geo_locations = [geolocator.geocode(address) for address in address_list]
            distance_dict = {vincenty((address.latitude, address.longitude),
                              user_latlon).miles: address for address in geo_locations if address is not None}
            min_distance = min(distance_dict.items(), key=lambda k: k[0])
            return min_distance[1].address
        raise Exception('Tuple must be contain more than one address')
    raise TypeError('Second parameter must be a tuple')
Esempio n. 9
0
def example1():
    '''Simple Geocoding
    '''
    from geopy.geocoders import Nominatim # Nominatim 替换成你要用到的引擎
    engine = Nominatim()
    loc = engine.geocode('1400 S Joyce St Arlington, VA 22202')
    print loc.address
Esempio n. 10
0
	def getGeo(self, lon, lat):
		if self.geocoderCache:
			try:
				nodeObj = self.db.get(GeoAssign,{'lat' : lat, 'lon' : lon})
				nodeObj['cached'] = True
				return nodeObj
			except GeoAssign.DoesNotExist:
				pass
		if self.printStatus:
			print('lon: '+str(lon)+', lat: '+str(lat)+' not in cache - start lookup at Nominatim-API')
		geolocator = Nominatim()
		location = geolocator.reverse([lat, lon], timeout=20)
		if 'address' in location.raw:
			location = location.raw['address']
			nodeObj = GeoAssign({
				'lat' : lat,
				'lon' : lon,
				'payload' : location
				})
			self.db.save(nodeObj)
			self.db.commit()
			nodeObj['cached'] = False
			return nodeObj
		else:
			# got no results (i.e. coordinates are incorrect)
			return None
Esempio n. 11
0
	def getTweets(self):
		auth = tweepy.OAuthHandler(self.consumer_key, self.consumer_secret)
		auth.set_access_token(self.access_token, self.access_token_secret)

		api = tweepy.API(auth)

		geolocator = Nominatim()
		location = geolocator.geocode(self.zip_code)

		geo_code = str(location.latitude) + "," + str(location.longitude) + "," + self.radius + "mi"
		public_local_tweets = api.search(lang = "en",geocode=geo_code, count=100)

		print public_local_tweets
		count = len(public_local_tweets)
		twitter_data = ""
		twitter_time = ""
		for each in range(0, count-1):
			twitter_data += public_local_tweets[each].text + " , " + "\n"

		self.status = True
		twitter_data_file = open("twitter_data.txt", "r+")
		twitter_data = twitter_data.encode('utf-8').strip()
		twitter_data_file.write(twitter_data)

		return self.status
Esempio n. 12
0
def claim_map(request, claim_id):
    claim = Claims.objects.get(pk=claim_id)
    address = claim.address
    try:
        geolocator = Nominatim()
        location = geolocator.geocode(address.encode('utf-8') + ", Умань, Україна")
        lat = location.latitude
        str_lat = str(lat)
        min_lat = str(lat - 0.0008)
        max_lat = str(lat + 0.0008)
        lon = location.longitude
        str_lon = str(lon)
        min_lon = str(lon - 0.00117)
        max_lon = str(lon + 0.00117)
    except:
        results = Geocoder.geocode(address.encode('utf-8') + ", Умань, Україна")
        lat = results[0].coordinates[0]
        str_lat = str(lat)
        min_lat = str(lat - 0.0008)
        max_lat = str(lat + 0.0008)
        lon = results[0].coordinates[1]
        str_lon = str(lon)
        min_lon = str(lon - 0.00117)
        max_lon = str(lon + 0.00117)
    return render(request, 'maps.html', locals())
Esempio n. 13
0
def get_address(location):
    geolocator = Nominatim()    
    latitude, longitude = location
    address = ""
    if latitude is not None:
        address = geolocator.reverse(latitude, longitude).address
    return address
def getCoordinatesForAllData(sourceUrl,patternUrl):

    data = EventsPortal.getAllEventsData(sourceUrl,patternUrl)


    for docs in data:
        latitudeField = docs['latitude']

        if latitudeField == None:

            geocity = docs['locationCity']

            geolocator = Nominatim()
            locatorCity = geocity

            location = geolocator.geocode(locatorCity)

            latitude = location.latitude

            longitude = location.longitude

            docs['latitudetest'] = latitude

            docs['longitudetest'] = longitude

        else:
            pass

    return  data
    def parse(self,text,place="NYC"):
        dict_addr,addr_type = self.preprocess(text)
        google_key = pickle.load(open("google_api_key.pickle","r"))
        g_coder = GoogleV3(google_key)
        if addr_type == 'complete':
            combined_addr = []
            keys = ["AddressNumber","StreetName","StreetNamePostType","PlaceName","StateName","ZipCode"]
            for key in keys:
                try:
                    combined_addr += [dict_addr[key]]
                except KeyError:
                    continue
                addr = " ".join(combined_addr) 
            n_coder = Nominatim()
            addr = self.pre_formatter(addr,dict_addr)
            lat_long = n_coder.geocode(addr)
            if lat_long: #means the request succeeded
                return lat_long
            else:
                lat_long = g_coder.geocode(addr)
                return lat_long
            #If None, means no address was recovered.
        if addr_type == 'cross streets':
            #handle case where dict_addr is more than 2 nouns long
	    cross_addr = " and ".join(dict_addr) + place 
            try:
                lat_long = g_coder.geocode(cross_addr)
                return lat_long
            except geopy.geocoders.googlev3.GeocoderQueryError:
                return None
Esempio n. 16
0
def CalculateDistance(place,city_list,Path_to_Take,Distance,length):
	geolocator = Nominatim();
	main_location = geolocator.geocode(place, exactly_one=True, timeout=None);
	main_coordinates = (main_location.latitude,main_location.longitude);
	list_toSort = [];
	for x in city_list:
		place_location = geolocator.geocode(x, exactly_one=True, timeout=None);
		place_coordinates = (place_location.latitude,place_location.longitude);
		print place_coordinates;
		result = vincenty(main_coordinates,place_coordinates).miles
		print result;
		list_toSort.append({'Name':x,'Distance':result});
	newlist = sorted(list_toSort, key=lambda k: k['Distance']) 
	Path_to_Take.append(newlist[1]);
	Distance += newlist[1]['Distance']
	city_list.remove(city_list[0]);
	if len(Path_to_Take) < length:
		CalculateDistance(newlist[1]['Name'],city_list,Path_to_Take,Distance,length);
	if len(Path_to_Take) == length:
		main_location = geolocator.geocode(Path_to_Take[0]['Name'], exactly_one=True, timeout=None);
		main_coordinates = (main_location.latitude,main_location.longitude);
		place_location = geolocator.geocode(Path_to_Take[length-1]['Name'], exactly_one=True, timeout=None);
		place_coordinates = (place_location.latitude,place_location.longitude);
		result = vincenty(main_coordinates,place_coordinates).miles
		Path_to_Take.append({'Name':Path_to_Take[0]['Name'],'Distance':result});
Esempio n. 17
0
def convertgeo(city):
    geolocator = Nominatim()
    location = geolocator.geocode(city)
    if location:
        return location.latitude, location.longitude
    else:
        return None
Esempio n. 18
0
def getCoordinates(l):
    geolocator = Nominatim()
    location = geolocator.geocode(l, timeout=20)
    
    coord = "{latitude: %s , longitude: %s }" %(location.latitude,location.longitude)
    print coord
    return coord
Esempio n. 19
0
def login():
    login_name = request.json['email']
    service = request.json['service']
    password = request.json['password']
    location = request.json['location']

    geolocator = Nominatim()
    location = geolocator.geocode(location)
    if not location:
        location = geolocator.geocode("Düsseldorf, Germany")
    latitude = location.latitude
    longitude = location.longitude

    try:
        logged_in = pokeapi.login(service, login_name, password,
                                  lat=latitude, lng=longitude, app_simulation=True)
    except AuthException as e:
        return jsonify({'status': 'error',
                        'message': e.__str__()})

    time.sleep(1)
    if not logged_in:
        return jsonify({'status': 'error',
                        'message': 'Failed to login. If the Pokemon GO Servers are online, your credentials may be wrong.'})
    else:
        return jsonify({'status': 'ok'})
Esempio n. 20
0
def get_gps(address):
    geolocator = Nominatim()
    try:
        location = geolocator.geocode(address, timeout=5)
    except:
        return None
    return location
def getTrackCountryOfOrigin(billboard_df_final):
    geolocator = Nominatim()
    track_state_of_origin = []
    track_country_of_origin = []
    for index_artist, row in billboard_df_final.iterrows():
        if (not pd.isnull(row['latitude'])) & (not pd.isnull(row['longitude'])):
            try:
                location = geolocator.reverse(str(row['latitude']) +',' + str(row['longitude']), language='en')
                state = location.raw['address']['state']
                if state == "Puerto Rico":
                    country = "Puerto Rico"
                else:
                    country = location.raw['address']['country']
                    if country == "The Netherlands":
                        country = "Netherlands"
            except:
                print row["Artist(s)"]
                country = "" 
                state = ""
        else:
            country = ""
            state = ""
        
        track_country_of_origin.append(country)
        if country == "United States of America":
            track_state_of_origin.append(state)
        else:
            track_state_of_origin.append("")

    return [track_country_of_origin, track_state_of_origin]
Esempio n. 22
0
def get_adr(gps):
    geolocator = Nominatim()
    try:
        location = geolocator.reverse(gps, timeout=5)
    except:
        return None
    return location.address
    def get(self, height, weight, city, state):
        # combined = pd.read_csv("wonderfullyamazingdata.csv", encoding='ISO-8859-1')
        combined = pd.read_csv("newamazingdata.csv", encoding='ISO-8859-1')
        location =  str(city) + ' ' + str(state)
        geolocator = Nominatim()
        place = geolocator.geocode(location[0])
        latitude = place.latitude
        longitude = place.longitude


        users = [float(height), float(weight), latitude, longitude ]
        players = combined[["height", "weight", "latitude", "longitude"]]

        result = []
        for index in range(0,len(players)):

            result.append(1-distance.cosine(users, players.iloc[index]))

        result = sorted(range(len(result)), key=lambda i: result[i])[-5:]   
        result.reverse()

        ids = []
        for index in result:
            ids.append( combined.ID.iloc[index] )


        ids = str(ids)


        with open('reply.json', 'w') as outfile:
            json_stuff = json.dumps(ids)
            json.dump(json_stuff, outfile)

        return json_stuff
Esempio n. 24
0
def address_2_lonlat_hack_dev(x):
    """
    in case frequent request would make script get block
    here is a mini hack : make script sleep until the API is able to response 
    then do the run again 
    """
    print (x)
    time.sleep(1)  # let's see if sleep 1 per epoch is OK for limitation 
    # --------- API  1) GOOGLE MAP API 
    results= get_google_results(x)
    print ('google API results :' , results)
    if [results['latitude'], results['longitude']] != [None,None]:
        return [results['latitude'], results['longitude']] 
     # --------- API  2) GEOPY API 
    else:
        try:
            geolocator = Nominatim()
            location = geolocator.geocode(x, timeout=3)
            print(location.latitude, location.longitude)
            return [location.latitude, location.longitude]
        except Exception as e:
            print (e)
            if str(e) == '[Errno 61] Connection refused':
                print ('meet API request limit, try again...')
                print ('sleep 1 min  ...')
                time.sleep(60)
                address_2_lonlat_hack_dev(x)
            else:
                print ('fail to convert address to lon & lat ') 
            return [None,None]
Esempio n. 25
0
 def find_coordinates(self):
     """Get and set longitude and Latitude
     
     Scrape individual posting page, if no
     coordinates are found, cascade precision
     (try location, try user_location, or set
     to zero).  Returns an array, first 
     latitude and then longitude.
     """
     self.coordinates = []
     geolocator = Nominatim()
     follow_this = self.url
     follow_page = requests.get(follow_this)
     follow_soup = BeautifulSoup(follow_page.text, "html.parser")
     location = follow_soup.find("div", class_="viewposting")
     if location is not None: # Get from Page
         lat = location['data-latitude']
         lon = location['data-longitude']
     else:
         try: # Get from posted location
             lat = geolocator.geocode(self.location).latitude
             lon = geolocator.geocode(self.location).longitude
         except:
             try: # Get from user locatoin
                 lat = geolocator.geocode(self.user_location).latitude
                 lon = geolocator.geocode(self.user_location).longitude
             except:
                 lat = 0 #38.9047 # This is DC
                 lon = 0 #-77.0164
     self.coordinates.append(lat)
     self.coordinates.append(lon)
Esempio n. 26
0
def geolocator():
        table_string = ""
        listAddress=[]
        geolocator = Nominatim()
        locationsList=['Banke','Makwanpur','Lalitpur']
        for i in locationsList:
            table_string += "<tr>" + \
                          "<td>" + \
                              "".join(i) + \
                          "</td>" + \
                        "</tr>\n"
    
            sys.stdout.write( table_string )
          
            location = geolocator.geocode(i)
            #here we pass the values of latitude and longitudes in a javascript function 
            "<html><td>"
            "<tr>"
            "< a href="" onclick=javascript:loadMap({{location.latitude , location.longitude}});>{{location}}</a>"
            "</tr>"
            "</td>"
            "</html>"
            a=print(location.latitude, location.longitude)
            listAddress.append(a)
        return listAddress
Esempio n. 27
0
def set_location(set_type=None):
    user = User.query.filter_by(id=g.user.id).first()

    if request.method == 'POST':
        input_location = request.form['address']
        geolocator = Nominatim()
        try:
            location = geolocator.geocode(input_location)
            user.loc_input = input_location
            user.loc_latitude = location.latitude
            user.loc_longitude = location.longitude
            db.session.commit()
        except:
            location = None
        return render_template(
            'set_location.html', 
            location=location, 
            type=set_type
        )

    if set_type:
        loc_input = user.loc_input
    else:
        loc_input = None
    return render_template(
        'set_location.html', 
        type=set_type, 
        current_loc=loc_input
    )
    def handle(self, *args, **options):
        geolocator = Nominatim()

        for i in filter(lambda x: x.location.strip(), Event.objects.filter(location__isnull=False)):
            if LocationCache.objects.filter(string=i.location).exists():
                location = LocationCache.objects.get(string=i.location)
            else:
                time.sleep(5)
                try:
                    location = geolocator.geocode(i.location)
                except GeocoderTimedOut:
                    location = None

                if location is None and re.search("\(.*\)", i.location):
                    time.sleep(5)
                    try:
                        location = geolocator.geocode(re.search("(\(.+\))", i.location).group()[1:-1])
                    except GeocoderTimedOut:
                        location = None

                location = LocationCache.objects.create(
                    string=i.location,
                    lat=location.latitude if location else None,
                    lon=location.longitude if location else None,
                )

                if (location.lat, location.lon) == (None, None):
                    continue

            i.lon = location.lon
            i.lat = location.lat
            i.save()
Esempio n. 29
0
def api_v1_canvas(request):
    if request.method == 'POST':
        try:
            geolocator = Nominatim()
            location = None
            access_token = request.POST.get('access_token')
            # print "access_token:" + access_token
            text_location = request.POST.get('text_location')
            gps_location = request.POST.get('gps_location').decode('utf8') 

            if text_location:
                geo = geolocator.geocode(text_location)
                if hasattr(geo, 'latitude') and hasattr(geo, 'longitude'):
                    # print geo.latitude
                    # print geo.longitude
                    location = str(geo.latitude) + "," + str(geo.longitude)
                else:
                    pass
            else:
                location = str(gps_location)
                # print "location: " + location
                pass
            filename = parse_places_api(location, access_token)
        except Exception,e:
            print e
        return HttpResponse(json.dumps({'success':True,'filename':filename}), content_type="application/javascript; charset=utf-8") 
Esempio n. 30
0
    def getLatLon(codigo_pais, latitud, longitud, localizacion):
        result = ""
        # From twitter
        if latitud != "" and longitud !="":
            # OK
            result = [latitud, longitud, "T"]
        else:
            # Nominatim request
            geolocator = Nominatim()
            if(localizacion != ""):
                # Nominatim
                latlong_loc = geolocator.geocode(localizacion, timeout=60)
                if (latlong_loc != None) and (latlong_loc != ""):
                    result = [latlong_loc.latitude, latlong_loc.longitude ,"L"]
                else:
                    # Nominatim
                    latlong_cod = geolocator.geocode(codigo_pais, timeout=60)
                    if (latlong_cod != None) and (latlong_cod != ""):
                        result = [latlong_cod.latitude, latlong_cod.longitude ,"LM"]
            elif(codigo_pais != ""):
                # Nominatim
                latlong_cod = geolocator.geocode(codigo_pais, timeout=60)
                if (latlong_cod != None) and (latlong_cod != ""):
                    result = [latlong_cod.latitude, latlong_cod.longitude ,"C"]

        return result