fbpx

How to get data from Google Maps using Python

Google Maps API Python

Have you ever wonder how to take advantage of Google Maps massive data? Since Google made available its API, this task has never been so easy. In this post, I will show you how to easily get the API key (for Geocoding and Places API) and query the information from Python and thus, be able to analyze it there.

https://www.datacamp.com/

Get the API Key

  1. Visit the Google Cloud Platform Console.
  2. Click the project drop-down and select or create the project for which you want to add an API key.
  3. Click on Google Maps > APIs.
  4. Click on Places API > Enable.
  5. Click on Geocoding API > Enable.
  6. Click the menu button and select Credentials, and click Credentials in APIs & Services.
  7. On the Credentials page, click Create credentials > API key. The API key created dialog display your newly created API key.
  8. The new API key is listed on the Credentials page under API Keys.
Advertisements

Install the library googlemaps in python

  1. Install the library:
    1. pip install googlemaps
  2. Follow the next code and add your API Key on Activate Key:
# libraries
import googlemaps
from datetime import datetime
import pandas as pd
# API Key
gmaps = googlemaps.Client(key='Activate Key')

Since API uses the scheme “Pay-as-you-go pricing”, please ensure you understand the pricing structure. Also, please ensure to enable the billing of your project.

  1. Next, you can search for directions and places using coordinates with this function reverse_geocode. For verification purposes, let’s try this: Times Square (Manhattan, NY 10036, United States, {40.757989, -73.985524}).
  2. For knowing what should be specified as parameters, please visit the documentation of Geocoding API.
reverse_geocode_result = gmaps.reverse_geocode((40.757989,-73.985524))
Formated_Address = []
Latitude = []
Longitude = []
Place_ID = []
Types_ = []
for i in range(0,len(reverse_geocode_result)):
    Formated_Address.append(reverse_geocode_result[i]['formatted_address'])
    Latitude.append(reverse_geocode_result[i]['geometry']['location']['lat'])
    Longitude.append(reverse_geocode_result[i]['geometry']['location']['lng'])
    Place_ID.append(reverse_geocode_result[i]['place_id'])
    Types_.append(reverse_geocode_result[i]['types'])
results_Geo = pd.DataFrame(data={'Formated_Address':Formated_Address,
                                'Latitude':Latitude,
                                'Longitude':Longitude,
                                'Place_ID':Place_ID,
                                'Types_':Types_})
results_Geo.to_excel('datos_GEO_location.xlsx')
Advertisements

Results Geocode

AddressLatitudeLongitudePlace IDTypes
Times Square, New York, NY 10036, USA40.758-73.9856ChIJ74T0qVVYwokRgupPU9hTtp0[‘establishment’, ‘point_of_interest’, ‘transit_station’]
177 W 45th St, New York, NY 10036, USA40.75792-73.9852ChIJz3MIqFVYwokRDQGAtbRCz_Y[‘street_address’]
Bertelsmann Building, New York, NY 10036, USA40.75796-73.9847ChIJd_cVoVVYwokRq4t_7F117HU[‘premise’]
1539 Broadway, New York, NY 10036, USA40.75797-73.9856EiYxNTM5IEJyb2Fkd2F5LCBOZXcgWW9yaywgTlkgMTAwMzYsIFVTQSIbEhkKFAoSCYUFmK5VWMKJEftBkwRJbYrKEIMM[‘street_address’]
7th Ave, New York, NY 10036, USA40.75815-73.9854ChIJowwgqVVYwokR3JwLCfUBRlQ[‘route’]
Theater District, New York, NY, USA40.75901-73.9845ChIJgzD7uFVYwokRXCoEdvGu-aA[‘neighborhood’, ‘political’]
New York, NY 10036, USA40.76026-73.9933ChIJByP4k1NYwokR7WYV3pZo1fc[‘postal_code’]
Midtown Manhattan, New York, NY, USA40.75493-73.984ChIJqXwSpAFZwokR28_WgZDMzb4[‘neighborhood’, ‘political’]
Manhattan, New York, NY, USA40.78306-73.9712ChIJYeZuBI9YwokRjMDs_IEyCwo[‘political’, ‘sublocality’, ‘sublocality_level_1’]
New York County, New York, NY, USA40.78306-73.9712ChIJOwE7_GTtwokRFq0uOwLSE9g[‘administrative_area_level_2’, ‘political’]
New York, NY, USA40.71278-74.006ChIJOwg_06VPwokRYv534QaPC8g[‘locality’, ‘political’]
New York, USA43.29943-74.2179ChIJqaUj8fBLzEwRZ5UY3sHGz90[‘administrative_area_level_1’, ‘political’]
United States37.09024-95.7129ChIJCzYy5IS16lQRQrfeQ5K5Oxw[‘country’, ‘political’]
  1. With the code above, you can store the results of the query into a pandas dataframe to have them available for analysis.
  2. Now, you use the function places_nearby to look for places near to a specified coordinate.
  3. For knowing what should be specified as parameters, please visit the documentation of Places API.
places_nearby_example = gmaps.places_nearby(location = (40.757989, -73.985524), radius = 100, type=['aquarium',
'art_gallery','atm','bakery','bank','bar','beauty_salon','bicycle_store','book_store','bowling_alley','bus_station',
'cafe','campground','car_dealer','car_rental','car_repair','car_wash','casino','cemetery','church','city_hall',
'clothing_store','convenience_store','courthouse','dentist','department_store','doctor','electrician',
'electronics_store','embassy','fire_station','florist','funeral_home','furniture_store','gas_station','gym',
'hair_care','hardware_store','hindu_temple','home_goods_store','hospital','insurance_agency','jewelry_store',
'laundry','lawyer','library','liquor_store','local_government_office','locksmith','lodging','meal_delivery',
'meal_takeaway','mosque','movie_rental','movie_theater','moving_company','museum','night_club','painter',
'park','parking','pet_store','pharmacy','physiotherapist','plumber','police','post_office','real_estate_agency',
'restaurant','roofing_contractor','rv_park','school','shoe_store','shopping_mall','spa','stadium','storage',
'store','subway_station','supermarket','synagogue','taxi_stand','train_station','transit_station','travel_agency',
'veterinary_care','zoo'])
res = len(places_nearby_example['results'])
results = places_nearby_example['results']
lat_ = []
lng_ = []
name_ = []
place_id_ = []
types_ = []
vicinity_ = []
for rr_ in range(0,res):
    lat = results[rr_]['geometry']['location']['lat']
    lng = results[rr_]['geometry']['location']['lng'] 
    name = results[rr_]['name']
    place_id = results[rr_]['place_id']
    types = results[rr_]['types']
    vicinity = results[rr_]['vicinity']
    lat_.append(lat)
    lng_.append(lng)
    name_.append(name)
    place_id_.append(place_id)
    types_.append(types)
    vicinity_.append(vicinity)
results = pd.DataFrame(data={'lat':lat_,
                                'lng':lng_,
                                'name':name_,
                                'place_id':place_id_,
                                'types':types_,
                                'vicinity':vicinity_})
results.to_excel('datos_places_location.xlsx')
Advertisements

Results Places

LatitudeLongitudeNamePlace IDTypesVicinity
40.71278-74.006New YorkChIJOwg_06VPwokRYv534QaPC8g[‘locality’, ‘political’]New York
40.75797-73.9855Times SquareChIJmQJIxlVYwokRLgeuocVOGVU[‘tourist_attraction’, ‘point_of_interest’, ‘establishment’]Manhattan
40.75859-73.9858New York Marriott MarquisChIJiVXoAFVYwokREqPijh-d8xg[‘lodging’, ‘point_of_interest’, ‘establishment’]1535 Broadway, New York
40.75794-73.9851Planet HollywoodChIJf2_0qFVYwokRu7dmhsHUrpo[‘restaurant’, ‘food’, ‘point_of_interest’, ‘establishment’]1540 Broadway, New York
40.75797-73.9859Minskoff TheatreChIJB4cC_1RYwokRu6mRBD_lqO8[‘point_of_interest’, ‘establishment’]200 West 45th Street, New York
40.75824-73.985Disney StoreChIJf2_0qFVYwokRcbTtlS60Vqg[‘point_of_interest’, ‘clothing_store’, ‘store’, ‘establishment’]1540 Broadway, New York
40.75755-73.9861Oakley StoreChIJC4BM_FRYwokRT7tenPBxEUQ[‘shoe_store’, ‘point_of_interest’, ‘clothing_store’, ‘store’, ‘establishment’]1515 Broadway, New York
40.75837-73.985MAC CosmeticsChIJQSY1plVYwokRIiTnNMzktsE[‘point_of_interest’, ‘store’, ‘establishment’]1540 Broadway, New York
40.75792-73.9852Buca di Beppo Italian RestaurantChIJN3JuqFVYwokRXvoa9Q9wmnM[‘restaurant’, ‘food’, ‘point_of_interest’, ‘establishment’]1540 Broadway, New York
40.75788-73.9862MTVChIJAQES_lRYwokR0HBr86D5FRY[‘point_of_interest’, ‘establishment’]1515 Broadway, New York
40.75799-73.9853Sunglass HutChIJJaibplVYwokRi6fDp2MjUYg[‘shopping_mall’, ‘point_of_interest’, ‘store’, ‘establishment’]1540 Broadway, New York
40.75766-73.9863PlayStation TheaterChIJbX7w8FRYwokR7GPMrwmmgtE[‘point_of_interest’, ‘establishment’]1515 Broadway, New York
40.75788-73.9862IT2 Treasury Solutions Inc.ChIJbX7w8FRYwokRMlxCK0A18Zg[‘point_of_interest’, ‘establishment’]1515 Broadway, New York
40.75809-73.9861Shimon SandlerChIJbX7w8FRYwokRKx3XTT7wwoM[‘point_of_interest’, ‘establishment’]1515 Broadway #627, New York
40.75779-73.9862Design ShoppnyChIJSc3GAlVYwokRiDnoXdqZp10[‘point_of_interest’, ‘establishment’]1515 Broadway, New York
40.75779-73.9862TLD AssetsChIJqWJv-1RYwokRLBeoQUiHzcM[‘point_of_interest’, ‘establishment’]1515 Broadway, New York
40.75791-73.9864LX Coach Bus Charter CoChIJbX7w8FRYwokR6Y-uT_fik7A[‘point_of_interest’, ‘establishment’]1515 Broadway, New York
40.75779-73.9862Ciplex New YorkChIJqWJv-1RYwokRwwLzQzds5ck[‘point_of_interest’, ‘establishment’]1515 Broadway, New York
40.75751-73.9861ViacomChIJqWJv-1RYwokRpWCF8nL4bUE[‘point_of_interest’, ‘establishment’]1515 Broadway 53rd floor, New York
40.75493-73.984Midtown ManhattanChIJqXwSpAFZwokR28_WgZDMzb4[‘neighborhood’, ‘political’]Manhattan
Results (Incomplete) for Place Near Query
https://www.datacamp.com/

Potential Applications

Finally, I would like to highlight the main applications that this analysis could have in businesses:

  • Market Research on how well is a place for opening an establishment.
  • Scheduling and planning of selling route in case of physical visits.
  • Identify potential clients within an interesting area for a defined service or product.
Interesting for you:  Optimization in Data Science

References:

  1. https://developers.google.com/places/web-service/get-api-key
  2. https://developers.google.com/maps/billing/gmp-billing?hl=es#places-product

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: