Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Calculate geographic coordinates of places using google geocoding API in Python?
To get the geographic coordinates (longitude and latitude) of any place, we can use the Google Maps Geocoding API. This API converts addresses into geographic coordinates and provides detailed location information.
Requirements
To get the coordinates of a place, you need a Google Geocoding API key. You can get it from the official Google documentation:
https://developers.google.com/maps/documentation/geocoding/get-api-key
Apart from the API key, we need the following Python modules ?
- requests module (to fetch the coordinates from API)
- json module (for JSON data conversion)
Basic Implementation
Here's a complete program to get geographic coordinates using Google Geocoding API ?
# Import required libraries import requests import json # Enter the place name place = "New York" # Replace with your Google Maps API key apiKey = 'YOUR_API_KEY' # Google geocoding API URL url = 'https://maps.googleapis.com/maps/api/geocode/json?' # Make API request response = requests.get(url + 'address=' + place + '&key=' + apiKey) # Get JSON format result data = response.json() # Print the complete response print(data)
Extracting Coordinates
The complete response contains a lot of information. To extract just the latitude and longitude coordinates ?
import requests
import json
def get_coordinates(place_name, api_key):
url = 'https://maps.googleapis.com/maps/api/geocode/json?'
response = requests.get(url + 'address=' + place_name + '&key=' + api_key)
data = response.json()
if data['status'] == 'OK':
location = data['results'][0]['geometry']['location']
latitude = location['lat']
longitude = location['lng']
formatted_address = data['results'][0]['formatted_address']
return {
'latitude': latitude,
'longitude': longitude,
'address': formatted_address
}
else:
return None
# Example usage
place = "Tokyo, Japan"
api_key = 'YOUR_API_KEY'
coordinates = get_coordinates(place, api_key)
if coordinates:
print(f"Place: {coordinates['address']}")
print(f"Latitude: {coordinates['latitude']}")
print(f"Longitude: {coordinates['longitude']}")
else:
print("Location not found")
Handling Multiple Places
You can also get coordinates for multiple places at once ?
import requests
import json
def get_multiple_coordinates(places, api_key):
results = []
url = 'https://maps.googleapis.com/maps/api/geocode/json?'
for place in places:
response = requests.get(url + 'address=' + place + '&key=' + api_key)
data = response.json()
if data['status'] == 'OK':
location = data['results'][0]['geometry']['location']
results.append({
'place': place,
'latitude': location['lat'],
'longitude': location['lng'],
'formatted_address': data['results'][0]['formatted_address']
})
else:
results.append({
'place': place,
'error': 'Location not found'
})
return results
# Example usage
cities = ["London", "Paris", "Mumbai", "Sydney"]
api_key = 'YOUR_API_KEY'
coordinates_list = get_multiple_coordinates(cities, api_key)
for coord in coordinates_list:
if 'error' in coord:
print(f"{coord['place']}: {coord['error']}")
else:
print(f"{coord['place']}: Lat {coord['latitude']}, Lng {coord['longitude']}")
Key Points
- Always check the API response status before extracting coordinates
- The API returns the most relevant result first in the results array
- Handle potential errors like invalid API keys or location not found
- The formatted_address provides a standardized address format
- Consider API usage limits and costs for production applications
Conclusion
Google Geocoding API provides an easy way to convert place names into geographic coordinates. Always validate the API response status and handle errors appropriately for robust applications.
