Featured
- Get link
- X
- Other Apps
Get Latitude and Longitude from Google Maps Geocoding API with Python urllib Library
On Google map, we can find a location with both latitude and longitude, or reversely, from an address, we can find out its latitude and longitude.
From Google Maps Geocoding API documentation, we need to get an API key first. This key should be kept secret. It is required when we do the requests from the API.
Also from the documentation, we can get a base url for any queries, this url is ended with a '?', we need to construct the second half of the query url to form a complete working url as the server's host address. Python's urllib.parse module has a great way to convert a dictionary into an encoded url - 'urlencode()' method, we only need to provide two keys to this dictionary parameter - 'address' and 'key' - and their corresponding values.
Once the url is correctly formatted, we can use urllib.request module to send requests to the url and receive reponses, the method is urlopen().
To correctly format the response, we should read() it like we read a file, then decode() it into string. For easier access to the keys inside the data such as 'lat' (for latitude) and 'lng' (for longitude), we use json.loads() to convert them to a dictionary.
To get necessary data from the dictionary, we only need to track down to the right keys in the dictionary.
Now, let's see how to code this.
'''Use Google Maps GeoCoding API to get a place's latitude and longitude as well as formatted address. With both latitude and longitude, we can put a marker on the map for that address''' import urllib.parse, urllib.request import json # retrieve the api key from a secret file with open('google_map.txt', 'r') as file: key = file.read().split()[2].strip() def get_lat_lng(address): # get base_url from google map api doc base_url = f'https://maps.googleapis.com/maps/api/geocode/json?' # use urllib library for converting dic into query string query_url = urllib.parse.urlencode({'address': address, 'key': key}) # To form the complete url url = base_url + query_url # send request to the url and get response with urllib.request.urlopen(url) as response: # read response (HTTPResponse) into bytes, then string, then dict (json) data = json.loads(response.read().decode()) # in case address provided is not real if data['status'] != 'OK' or 'status' not in data: data = None # To read the json file # print(json.dumps(data, indent=4)) # To check the request status # print(data['status']) # to get lat and lng if data != None: location= data['results'][0]['geometry']['location'] lat = location['lat'] lng = location['lng'] formatted_address = data['results'][0]['formatted_address'] return lat, lng, formatted_address else: print('try again') return print(get_lat_lng("sumiao juancheng"))
To run this program, we can choose to type in any city or address, I am using a small town in China, it correctly prints out the latitude, longitude and the formatted address with postal code. Very impressive for the accuracy.
To get the source code, go to github
- Get link
- X
- Other Apps
Popular Posts
Python SQLite3 Module Database - Many to Many Relationship Database Example
- Get link
- X
- Other Apps
CSS Staggered Animation - Show Different Elements Animations One After Another with CSS Only
- Get link
- X
- Other Apps