def index(request): consumer_key = "YAvBBJnUpgMOWIkBbzjjsCy1q" consumer_secret = "xPcvMjYjSicdIIcC57E9M8X51sarSiSi3syNjNZpNHn9wbz9gd" access_token = "841688184467705856-Sm1KiDoZomcOHgsXvJWj9ifXsHR5nc9" access_token_secret = "IhAGMDIfLn5eWvhUQVFvhqnYZ48q6c9VGZH735a43F3AZ" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) word = request.GET.get("word", None) public_tweets = api.search(str(word), retry_count=3, count=50) api1 = Geocoding() lat1 = dict(api1.geocode("new york")[0])['geometry']['location']['lat'] lng1 = dict(api1.geocode("new york")[0])['geometry']['location']['lng'] map_osm = folium.Map(location=[lat1, lng1], zoom_start=3) for tweet in public_tweets: analysis = textblob.TextBlob(tweet.text) a = tweet.user.location try: if a == '' or len(a) >= 12 or len(a) <= 3 or textblob.TextBlob( a).detect_language() != 'en' or a == 'interwebs': lat = random.uniform(30, 60) lng = random.uniform(-135, -75) else: lat = dict(api1.geocode(a)[0])['geometry']['location']['lat'] lng = dict(api1.geocode(a)[0])['geometry']['location']['lng'] if analysis.sentiment[0] > 0: folium.Marker([lat, lng], popup=str(analysis.sentiment) + "location:" + str(a) + "latitude:" + str(round(lat, 2)) + "longitude:" + str(round(lng, 2)), icon=folium.Icon(color='green')).add_to(map_osm) elif analysis.sentiment[0] == 0: folium.Marker([lat, lng], popup=str(analysis.sentiment) + "location:" + str(a) + "latitude:" + str(round(lat, 2)) + "longitude:" + str(round(lng, 2)), icon=folium.Icon(color='blue')).add_to(map_osm) elif analysis.sentiment[0] < 0: folium.Marker([lat, lng], popup=str(analysis.sentiment) + "location:" + str(a) + "latitude:" + str(round(lat, 2)) + "longitude:" + str(round(lng, 2)), icon=folium.Icon(color='red')).add_to(map_osm) except: pass map_osm.save('blog2/templates/blog2/osm.html') return render(request, "blog2/osm.html")
def look_uber(self, source, destination, cab_type, intent): api = Geocoding() try: source_loc = api.geocode(source) source_lat_long = source_loc[0]['geometry']['location'] start_lat = source_lat_long['lat'] start_lng = source_lat_long['lng'] except: return 'Enter Valid Source.\n' try: destination_loc = api.geocode(destination) destination_lat_long = destination_loc[0]['geometry']['location'] end_lat = destination_lat_long['lat'] end_lng = destination_lat_long['lng'] except: return 'Enter Valid destination.\n' try: response = client.get_price_estimates(start_latitude=start_lat, start_longitude=start_lng, end_latitude=end_lat, end_longitude=end_lng, seat_count=2) estimate = response.json for cab_types in estimate['prices']: if cab_types['localized_display_name'].lower( ) == cab_type.lower(): if (intent == 'book'): out = 'Booking ' + ( cab_type) + ' with averege fare ' + ( cab_types['estimate'] ) + '. Your journy will be ' + str( cab_types['distance'] ) + ' KM long and will take ' + str( cab_types['duration'] / 60) + ' minutes. ' return out + self.cab_details() else: out = str(cab_type) + ' with averege fare ' + ( cab_types['estimate'] ) + 'is available. Distance will be ' + str( cab_types['distance'] ) + ' KM and it will take ' + str( cab_types['duration'] / 60) + ' minutes.' print(out) return str(out) except uber_error.ClientError as e: return 'Distance between two points exceeds 100 miles'
def geocode(address, api_key=None): api_key = getattr(settings, 'WORKON_GOOGLE_API_KEY', api_key) if api_key and api_key.strip() == "": api_key = None api = Geocoding(api_key=api_key) if address.strip() != '': original_address = address.strip() try: latlng = latlngreg.search(original_address) if latlng: results = api.reverse(float(latlng.group(1)), float(latlng.group(2))) else: results = api.geocode(original_address) if len(results): results[0]['lng'] = results[0].get('geometry', {}).get('location', {}).get('lng', None) results[0]['lat'] = results[0].get('geometry', {}).get('location', {}).get('lat', None) return results[0] except NoResults, e: return { 'error': 'NoResults', 'message': str(e.message) } except GmapException, e: return { 'error': 'GmapException', 'message': str(e.message) }
def tw_expert_location_geocoding(self, tw_user_location): """ Using data from the <tw_location> field in <monexp_db> database, and python-gmaps Package as wrapper for Google Maps Geocoding API (as part of Google Maps API), get the latitude and longitude of the expert's location Arguments: tw_user_location {str} -- The value of the <tw_user_location> field of the User object in Twitter Returns: [float] -- latitude of the expert's location or None, if the latitude was not determined [float] -- longitude of the expert's location or None, if the longitude was not determined """ try: gmaps_request = Geocoding(api_key='<your-api_key>') gmaps_result = gmaps_request.geocode(tw_user_location) expert_location_lat = gmaps_result[0]['geometry']['location'][ 'lat'] expert_location_lng = gmaps_result[0]['geometry']['location'][ 'lng'] except: expert_location_lat = None expert_location_lng = None return expert_location_lat, expert_location_lng
def geocode(address, api_key=None): api_key = getattr(settings, 'WORKON_GOOGLE_API_KEY', api_key) if api_key and api_key.strip() == "": api_key = None api = Geocoding(api_key=api_key) if address.strip() != '': original_address = address.strip() try: latlng = latlngreg.search(original_address) if latlng: results = api.reverse(float(latlng.group(1)), float(latlng.group(2))) else: results = api.geocode(original_address) if len(results): results[0]['lng'] = results[0].get('geometry', {}).get( 'location', {}).get('lng', None) results[0]['lat'] = results[0].get('geometry', {}).get( 'location', {}).get('lat', None) return results[0] except NoResults, e: return {'error': 'NoResults', 'message': str(e.message)} except GmapException, e: return {'error': 'GmapException', 'message': str(e.message)}
def look_uber(source,destination=None): api = Geocoding() try: source_loc = api.geocode(source) source_lat_long = source_loc[0]['geometry']['location'] start_lat=source_lat_long['lat'] start_lng=source_lat_long['lng'] except: print('Enter Valid Source.\n') print('Please let me know if you want to know anything more') return('null') if destination : try: destination_loc = api.geocode(destination) destination_lat_long = destination_loc[0]['geometry']['location'] end_lat=destination_lat_long['lat'] end_lng=destination_lat_long['lng'] except: print('Enter Valid destination.\n') print('Please let me know if you want to know anything more') return('null') else: end_lat=12.9173312 # latitude of Central Silk Board end_lng=77.6212483 # longitude of Central Silk Board try: response = client.get_price_estimates( start_latitude=start_lat, start_longitude=start_lng, end_latitude=end_lat, end_longitude=end_lng, seat_count=2 ) estimate = response.json cab_details_df= uber_cab_details(estimate) cab_details_df.fillna(0, axis=1, inplace=True) #print('Following are the cabs availability\n') #print(cab_details_df) return cab_details_df except uber_error.ClientError as e: print('Distance between two points exceeds 100 kms\n') print('Please let me know if you want to know anything more') return('null')
def geo(self, search): """ Get a dict_location from gmaps. :param search: :return: dict_location """ try: gmaps = Geocoding(api_key=MAP_API_KEY) geocode_result = gmaps.geocode(search, language='fr')[0] dict_location = {} for libelle, item in geocode_result.items(): if libelle == 'formatted_address': dict_location['adresse'] = item elif libelle == 'geometry': dict_location['latitude'] = item['location']['lat'] dict_location['longitude'] = item['location']['lng'] return dict_location except: return False
def getLocUsingGMaps(location): api = Geocoding() return api.geocode(location)
@route('/todo') def todo_list(): conn = sqlite3.connect('sessions.db') c = conn.cursor() c.execute("SELECT id, dt, data FROM DATA") result = c.fetchall() c.close() output = template('templates/maketable', rows = result) return output @route('/map') def todo_list(): conn = sqlite3.connect('sessions.db') c = conn.cursor() c.execute("SELECT id, dt, data FROM DATA") result = c.fetchall() c.close() output = template('templates/maps', rows = result) return output api = Geocoding() api.geocode("somwhere") print(api.reverse(51.123, 21.123)) print(api.base) run(port = 8989, host = '192.168.0.156' )
def __get_loc_using_gmaps(location): api = Geocoding(api_key=current_app.config['GOOGLE_GEO_CODE_API_KEY']) return api.geocode(location)
#use python_gmaps module #Many online providers such as Google & Bing have geocoding services #Here is a code to get a Lat & Lng from Google import argparse from gmaps import Geocoding #create api_key using => https://developers.google.com/maps/documentation/geocoding/start #api = Geocoding(api_key='Your API_KEY') api = Geocoding(api_key='AIzaSyBGJgF7gltKbGbyEdio03s5vmYoIc6Uww8') #create parser parser = argparse.ArgumentParser() #add argument parser.add_argument("string", help="The coordinatate of the location to be find", type=str) args = parser.parse_args() #find entered loctaion using api geocode geofind = api.geocode(args.string) geofind[0] print(geofind[0]['geometry']['location'])
def getLocUsingGoogleMap(location): api = Geocoding() return api.geocode(location)
from gmaps import Geocoding from gmaps import errors import sys geo = Geocoding(api_key="AIzaSyCAU19MydrGYH5TulC8jFS9EYv8EiYLegY") address = "".join(sys.argv[1:]) place = geo.geocode(address)[0] print(place["place_id"] + "\t" + str(place["geometry"]["location"]["lat"]) + "\t" + str(place["geometry"]["location"]["lng"]))
def test_client_with_key(): geocoding = Geocoding(api_key="invalid_key", use_https=True) with pytest.raises(errors.RequestDenied) as excinfo: geocoding.geocode("Some address") assert "API key is invalid" in str(excinfo)
from gmaps import Geocoding api = Geocoding(api_key='AIzaSyBGJgF7gltKbGbyEdio03s5vmYoIc6Uww8') geofind = api.geocode(input('Enter location: ')) geofind[0] print(geofind[0]['geometry']['location'])
def __process_extracted_data(results, restaurant, state, extractedDataFile, namesAllowed): """ This function processes the extracted data using pandas and stores the location density in a csv file :param: results - list of dictionary of restaurant location data :type: list :param: restaurant - name of the restaurant; eg. Pizza Hut :type: str :param: state - name of the state; eg. CA :type: str :param: extractedDataFile - path of the file where the extracted data will be stored :type: str :param: namesAllowed - names of the restaurant to qualify as valid results; eg. ['Pizza Hut', 'Pizza Hut Express'] :type: list :returns: None """ #assert statements assert(isinstance(results, list)) assert(isinstance(restaurant, str)) assert(isinstance(state, str)) assert(isinstance(extractedDataFile, str)) assert(isinstance(namesAllowed, list)) df = pd.DataFrame(results) #remove restaurants with other name than the restaurant's name df = df[df.Name.isin(namesAllowed)] #check if the location is within the state #get cities name in a list citiesFile = f"{FOLDER}/{state}_cities.txt" cities = [] f = open(citiesFile, "r") for line in f.readlines(): cities.append(line.strip().lower()) f.close() geocodeApi = Geocoding(api_key=API_KEY) for location in set(df['Location']): isLocationValid = False if(not __has_numbers(location) and location.lower() not in cities): isLocationValid = False elif(not __has_numbers(location) and location.lower() in cities): isLocationValid = True else: try: response = geocodeApi.geocode(location + ', ' + state) for address in response[0]['address_components']: if(address['types'][0] == 'locality'): df.replace(location, address['long_name']) location = address['long_name'] elif(address['types'][0] == 'administrative_area_level_1'): isStateValid = address['short_name'] == state elif(address['types'][0] == 'country'): isCountryValid = address['short_name'] == 'US' isLocationValid = isStateValid and isCountryValid except: isLocationValid = False if(not isLocationValid): df = df[df.Location != location] #remove duplicate location using dataframes df.drop_duplicates(subset=None, keep='last', inplace=True) with open(extractedDataFile, 'a', newline="") as csv_file: writer = csv.writer(csv_file) writer.writerow([restaurant, state, str(len(df))])
#use python_gmaps module #Many online providers such as Google & Bing have geocoding services #Here is a code to get a Lat & Lng from Google import sys from gmaps import Geocoding #create api_key using => https://developers.google.com/maps/documentation/geocoding/start #api = Geocoding(api_key='Your API_KEY') api = Geocoding(api_key='AIzaSyBGJgF7gltKbGbyEdio03s5vmYoIc6Uww8') #find entered loctaion using api geocode geofind = api.geocode(sys.argv[1]) geofind[0] print(geofind[0]['geometry']['location'])
from gmaps import Geocoding # Use your own api key by registering at https://console.cloud.google.com/apis/credentials?project=starlit-woods-175707 api = Geocoding(api_key = 'Your api key') # import the data data = pd.read_csv("data.csv") # make a list of the addresses in data['address'] # change the index as desired # remember that you are only limited to 2500 queries in a day address = data['address'][:1000].tolist() # initialize the location list location = [] # Download the geocodes for each school address for place in address: try: location.append(api.geocode(place)) except Exception as e: location.append("No Result") # Initialize the lat (latitude) and long (longitude) lists lat = [] long = [] # Get the number of schools in the list n_address = len(address) # loop through the addresses and store the lat and long values # a value of 0 means that there is no match from the query for i in list(range(n_address)): if type(location[i]) is list: lat.append(location[i][0]['geometry']['location']['lat']) long.append(location[i][0]['geometry']['location']['lng']) else: