Ejemplo n.º 1
0
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
Ejemplo n.º 3
0
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) }
Ejemplo n.º 4
0
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")
Ejemplo n.º 5
0
def get_zip(loc):
    try:
        latitude = loc[0].get('data-latitude')
        longitude = loc[0].get('data-longitude')
        google_api = Geocoding('AIzaSyBkWTcFg-kawvHmt1MryKvMcpmsNmrGWPU')
        map_loc = google_api.reverse(float(latitude), float(longitude))
        items = map_loc[0]['address_components']
        result = [item['long_name'] for item in items if item['types'][0] == 'postal_code']
        code = 'USA-' + result[0]
        return code
    except IndexError:
        return None
Ejemplo n.º 6
0
    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'
Ejemplo n.º 7
0
 def test_json_like_geocode_call(self):
     gmaps_api = Geocoding(
         **{
             'sensor': True,
             'use_https': True,
             'api_key': u'{}'.format(settings.GMAPS_API_KEY)}
     )
     california = GmapsItem.objects.get(short_name="CA")
     california_response = california.get_response_json()
     geocode_response = gmaps_api.reverse(
         float(california.lat), float(california.lng),
         **{'language': 'en',
            'result_type': ['administrative_area_level_1']}
     )
     self.assertEqual(california_response, json.dumps(geocode_response[0]))
Ejemplo n.º 8
0
 def test_json_like_geocode_call(self):
     gmaps_api = Geocoding(
         **{
             'sensor': True,
             'use_https': True,
             'api_key': u'{}'.format(settings.GMAPS_API_KEY)
         })
     california = GmapsItem.objects.get(short_name="CA")
     california_response = california.get_response_json()
     geocode_response = gmaps_api.reverse(
         float(california.lat), float(california.lng), **{
             'language': 'en',
             'result_type': ['administrative_area_level_1']
         })
     self.assertEqual(california_response, json.dumps(geocode_response[0]))
Ejemplo n.º 9
0
def get_zip(loc):
    try:
        latitude = loc[0].get('data-latitude')
        longitude = loc[0].get('data-longitude')
        google_api = Geocoding('AIzaSyBkWTcFg-kawvHmt1MryKvMcpmsNmrGWPU')
        map_loc = google_api.reverse(float(latitude), float(longitude))
        items = map_loc[0]['address_components']
        result = [
            item['long_name'] for item in items
            if item['types'][0] == 'postal_code'
        ]
        code = 'USA-' + result[0]
        return code
    except IndexError:
        return None
Ejemplo n.º 10
0
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')
Ejemplo n.º 11
0
 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
Ejemplo n.º 12
0
# エキスパートPythonプログラミング 改訂2版 13章
# マルチスレッドその2
# ワーカースレッド内で発生した例外をメインスレッドに返す

import time
from gmaps import Geocoding
from threading import Thread, current_thread
from queue import Queue, Empty
from util import PLACES, get_config

api = Geocoding(api_key=get_config()["geocode_api_key"])


def fetch_place(place):
    geocoded = api.geocode(place)[0]
    return geocoded, current_thread().name


def present_result(geocoded, thread_name):
    print(
        f'{geocoded["formatted_address"]:>60s}, {geocoded["geometry"]["location"]["lat"]:6.2f}, {geocoded["geometry"]["location"]["lng"]:6.2f} [{thread_name}]'
    )


def worker(work_queue, results_queue):
    # 各々のスレッドは、work_queue から取り出して処理する
    # どの都市をどのスレッドが処理するかは、その時次第
    while not work_queue.empty():
        try:
            item = work_queue.get(block=False)
        except Empty:
Ejemplo n.º 13
0
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"]))
Ejemplo n.º 14
0
def getLocUsingGMaps(location):
    api = Geocoding()
    return api.geocode(location)
Ejemplo n.º 15
0
"""
Main backend file for SmartPark project.
Created by:
Yosef Leibman
Abhishek Kapoor
Sultan Sidhu
for TD Bank Elevate Hackathon, 22 September 2018.
"""
from gmaps import Geocoding
from json import JSONDecoder
import json

instance = Geocoding(api_key="<your api key>")  # todo: read api key from a txt file.
file = open("/Users/sultansidhu/Desktop/DataFiles/greenPParking2015.json")
stuff = file.read()
jsonstuff = json.loads(stuff)
# for x in jsonstuff['carparks']:
#     print(x, end="\n\n\n\n\n")


class ParkingClass:

    def __init__(self, location: tuple, address: str, rate_per_half_hour: float, capacity: int):
        """
        Creates a new Parking object
        """
        self.location = location
        self.address = address
        self.rate_per_hour = rate_per_half_hour
        self.capacity = capacity
        self.proximity_rating = 0
Ejemplo n.º 16
0
#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'])
Ejemplo n.º 17
0
# -*- coding: utf-8 -*-
import pytest
from gmaps import errors

from gmaps import Geocoding
from .testutils import retry

geocoding = Geocoding(sensor=False)


@retry
def test_geocode():
    results = geocoding.geocode(u"Wrocław, Hubska")
    assert results
    assert len(results) > 0


@retry
def test_geocode_override_sensor():
    results = geocoding.geocode(u"Wrocław, Hubska", sensor=True)
    assert results
    assert len(results) > 0


@retry
def test_geocode_components_filters():
    """Test if querying with same route but different component filtering
    returns different locations"""
    # both these cities has this street
    results1 = geocoding.geocode(u"Łubinowa",
                                 components={"locality": "Wrocław"})
Ejemplo n.º 18
0
from multiprocessing import Pool

from gmaps import Geocoding

api = Geocoding()


PLACES = (
    'Reykjavik', 'Vien', 'Zadar', 'Venice',
    'Wrocław', 'Bolognia', 'Berlin', 'Słubice',
    'New York', 'Dehli',
)

POOL_SIZE = 4


def fetch_place(place):
    return api.geocode(place)[0]


def present_result(geocoded):
    print("{:>25s}, {:6.2f}, {:6.2f}".format(
        geocoded['formatted_address'],
        geocoded['geometry']['location']['lat'],
        geocoded['geometry']['location']['lng'],
    ))


def main():
    with Pool(POOL_SIZE) as pool:
        results = pool.map(fetch_place, PLACES)
Ejemplo n.º 19
0
ALLOWED_TYPES = settings.GMAPS_PLACES_ALLOWED_TYPES
URL_TYPES = settings.GMAPS_PLACES_URL_TYPES
GMAPS_DEFAULT_CLIENT_PARAMS = {
    'sensor': False,
    'use_https': True,
    'api_key': settings.GMAPS_API_KEY,
}
GMAPS_DEFAULT_GEOCODE_PARAMS = {
    'language': settings.GMAPS_LANGUAGE_CODE,
    # 'region': settings.GMAPS_REGION, TODO
}
GMAPS_DEFAULT_REVERSE_PARAMS = {
    'language': settings.GMAPS_LANGUAGE_CODE,
}
gmaps_api = Geocoding(**GMAPS_DEFAULT_CLIENT_PARAMS)


class gmaps_attempt(object):
    def __init__(self, gmaps_call):
        self.gmaps_call = gmaps_call

    def __call__(self, *args, **kwargs):
        attempts = 0
        success = False
        while success is not True and attempts < 3:
            attempts += 1
            try:
                result = self.gmaps_call(*args, **kwargs)
            except (NoResults, RequestDenied, InvalidRequest) as e:
                raise e
Ejemplo n.º 20
0
@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' )



from gmaps import Geocoding
api = Geocoding(api_key='AIzaSyBGJgF7gltKbGbyEdio03s5vmYoIc6Uww8')
geofind = api.geocode(input('Enter location: '))
geofind[0]
print(geofind[0]['geometry']['location'])
Ejemplo n.º 22
0
def route_planing(request, id, ide):

	def new_last_point(event, point, lat, lng):
		waypoint_event = Waypoint_event()
		waypoint_event.point = point
		waypoint_event.name = point
		waypoint_event.point_lat = lat
		waypoint_event.point_lng = lng
		waypoint_event.user = request.user
		event_end_point = event.end_point()
		waypoint_event.order = event_end_point.order
		waypoint_event.number = event_end_point.number
		waypoint_event.event = event
		waypoint_event.save()
		event_end_point.order += 1
		event_end_point.number += 1
		event_end_point.save()

	event = Events.objects.filter(id = id, ide = ide)[0]

	form1a = Events3aForm(instance = event)
	form2a = Events4aForm(instance = event)
	form3a = Events5aForm(instance = event)
	form1b = Events3bForm(instance = event)
	form2b = Events4bForm(instance = event)
	form3b = Events5bForm(instance = event)

	if request.method == "POST":

		if 'save_route' in request.POST:
			form1a = Events3aForm(request.POST, instance = event)
			form2a = Events4aForm(request.POST, instance = event)
			form3a = Events5aForm(request.POST, instance = event)
			form1b = Events3bForm(request.POST, instance = event)
			form2b = Events4bForm(request.POST, instance = event)
			form3b = Events5bForm(request.POST, instance = event)
			if form1a.is_valid() and form2a.is_valid() and form3a.is_valid() and form1b.is_valid() and form2b.is_valid() and form3b.is_valid():
				form1a.save()
				form2a.save()
				form3a.save()
				form1b.save()
				form2b.save()
				form3b.save()
			return HttpResponseRedirect( reverse('route_details', args=(event.id, event.ide)) )

		if 'new_point_form' in request.POST:
			new_last_point(Events.objects.filter(id = id, ide = ide)[0], request.POST.get('point'), request.POST.get('point_lat'), request.POST.get('point_lng'))
			return HttpResponse(json.dumps({"data": "true"}),content_type="application/json")

		if 'new_point_click' in request.POST:
			event = Events.objects.filter(id = id, ide = ide)[0]
			api = Geocoding()
			nombre = ''
			for direccion in api.reverse( float(request.POST.get('lat')), float(request.POST.get('lng')))[0]['address_components']:
				entra = True
				nombre += direccion['long_name']
				nombre += ', '
			if entra:
				nombre = nombre[:-2]
			new_last_point(Events.objects.filter(id = id, ide = ide)[0], nombre, request.POST.get('lat'), request.POST.get('lng'))
			return HttpResponse(json.dumps({"data": "true"}),content_type="application/json")
		
		if 'del_waypoint' in request.POST:
			event = Events.objects.filter(id = id, ide = ide)[0]
			Waypoint_event.objects.filter(id=request.POST.get('del_waypoint'))[0].delete()
			waypoints = Waypoint_event.objects.filter(event=event).order_by('order')
			order = 1
			number = 1
			for obj in waypoints:
				obj.order = order
				obj.number = number
				obj.save()
				order += 1
				number += 1
			return HttpResponse(json.dumps({"data": "true"}),content_type="application/json")

		if 'order' in request.POST:
			data  = json.loads(request.POST.get('order'))
			order = 1
			number = 1
			for obj in data:
				waypoint = Waypoint_event.objects.filter(id=obj)[0]
				waypoint.order = order
				waypoint.number = number
				waypoint.save()
				order += 1
				number += 1
			return HttpResponse(json.dumps({"data": "true"}),content_type="application/json")
		
	event = Events.objects.filter(id = id, ide = ide)[0]
	waypoints = Waypoint_event.objects.filter(event=event).order_by('order')
	
	return render(request, 'app/route_planing.html',locals())
Ejemplo n.º 23
0
def __get_loc_using_gmaps(location):
    api = Geocoding(api_key=current_app.config['GOOGLE_GEO_CODE_API_KEY'])
    return api.geocode(location)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr  1 16:58:12 2018

@author: josephuses
"""

#!/usr/bin/env python
import pandas as pd
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 = []
Ejemplo n.º 25
0
def getLocUsingGoogleMap(location):
    api = Geocoding()
    return api.geocode(location)
Ejemplo n.º 26
0
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)
Ejemplo n.º 27
0
from gmaps import Geocoding
from gmaps import Directions
import gmaps
import pprint
import re

direct = Directions()
geo = Geocoding()

TAG_RE = re.compile(r'<[^>]+>')
startLoc = '2121 S. El Camino Real, San Mateo CA'
endLoc = '820 E El Camino Real, Mountain View, CA'
DEFAULT = 'Hollingsworth Drive, Mountain View CA'
token = '\n'


def remove_tags(text):
    return TAG_RE.sub('', text)


# supported modes include driving, walking, bicycling, transit
def get_directions(start, end, transport="driving"):
    try:
        direct = Directions()
        response = direct.directions(start, end, mode=transport)
    except gmaps.errors.GmapException as ex:
        response = '1'
    except:
        response = '2'
    return response
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'])
Ejemplo n.º 30
0
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"]))