
Last week I was working on couple of Google APIs to get the latitude/ longitude for a city and also find the driving distance between two points given the latitude/ longitude for the two locations. These can be easily achieved by using couple of different google APIs. For getting the latitude/ longitude or a formatted address from an address we can use the geocoding API.
The other API that I want to present is the distancematrix API from Google. We will use this for calculating the driving distance between two given locations. Previously we have seen how to calculate as the crow flies miles in a separate blog. Here we had introduced the haversine and Vincenty formula to calculate distance between two points on a sphere. However roads are never straight.
Fun Fact: Why are roads never build straight and curves added? We would imagine that straight roads would save cost and time, but we still see a lot of unnecessary curves on the road. These were added because it was found that drivers tend to get bored driving on straight roads and fell asleep. The curves gives then a break from monotony. Roads are also curved to adjust to the curves of earth. Sometimes it becomes easier to switch road directions than to force a way through earth surface.
Both the APIs are GET calls, so it is easy to just call them from JavaScript. However, I needed to call it from backend service using Java. For convenience in this blog, I have added calls from Python to make it simpler.
Geocode APIs
Geocode API takes in address and key as the input parameters.
https://maps.googleapis.com/maps/api/geocode/json?address=<address>&key=<google_key>
Here I have given the output format as JSON as that is now a pretty standard format. I will just have a simple python program to make this call. For this program I am not using any external libraries, so you should be able to run it using a pristine python install.
import json from urllib.parse import quote from urllib.request import urlopen, Request from urllib.error import HTTPError class GoogleMapTest: API_KEY = "<API_KEY>" LATLON_URL = "https://maps.googleapis.com/maps/api/geocode/json?address=" def getLatLonFromAddress(self, addr): fnl_url = self.LATLON_URL + quote(addr, "utf-8") + "&key=" + self.API_KEY http_request = Request(fnl_url, headers={"Accept": "application/json"}) print(http_request) try: with urlopen(http_request) as response: print(response.status) resp = response.read().decode() print(resp) latLonObj = json.loads(resp) print(latLonObj["results"][0]["geometry"]["location"]["lat"]) print(latLonObj["results"][0]["geometry"]["location"]["lng"]) except HTTPError as e: print(e.status) print(e.reason) print(e.headers.get_content_type())
I am using urllib here directly instead of using requests, this helps in eliminating any library dependencies. Here what we are doing is to create a request string and posting it to google. For my request with address 1211 Avenue of the Americas, Manhattan, NY, following three fields were of interest to me,
"formatted_address": "1211 6th Ave, New York, NY 10036, USA", "geometry": { "location": { "lat": 40.7584969, "lng": -73.9821147 }
So following two fields will give me the approx lat/ lon for the location
print(latLonObj["results"][0]["geometry"]["location"]["lat"]) print(latLonObj["results"][0]["geometry"]["location"]["lng"]) ---- 40.7584969 -73.9821147 ----
There are other features that this API provides, One example would be setting a bounding box and getting a geocode location within it.
Distance Matrix API
Distance Matrix API is used for getting driving distance, drive time etc. between two points. The main API takes the form of following,
https://maps.googleapis.com/maps/api/distancematrix/json?origins=<list_of_origins>&destinations=<list_of_destinations>&key=<google_key>
Origins and Destinations can take full physical address, place ID or latitude/ longitude combination. Since I already had the latitude/ longitude of the places I just snapped them in the API. There are a few optional parameters that this API can also take.
Parameter Name | Meaning |
---|---|
arrival_time/ departure_time | Desired Arrival/ Departure time in seconds from midnight of January 1, 1970 UTC |
avoid | tolls, highways, ferries, indoor |
mode | driving, biking, bicycling, transit |
traffic_model | best_guess, pessimistic, optimistic |
transit_mode | bus, subway, train, tram, rail |
I am giving below the python code for getting driving distance using this API.
def calculateDriveDistance(self, src, dest): fnl_url = self.DISTNC_URL + "origins=" + src[0] +"," + src[1] + "&destinations=" + dest[0] + "," + dest[1] + "&key=" + self.API_KEY http_request = Request(fnl_url, headers={"Accept": "application/json"}) print(http_request) try: with urlopen(http_request) as response: print(response.status) print(response.read().decode()) except HTTPError as e: print(e.status) print(e.reason) print(e.headers.get_content_type()) # Plainsboro, NJ -> Manhattan, NY # mt.calculateDriveDistance(["40.3570497", "-74.615308"], ["40.776676", "-73.971321"])
This API returns an array of data based on what you have called it with. You can use elements[n].distance to get the total distance and elements[0].duration to get the total duration for the drive.
This output can also contain the fare for a public transport.
Conclusion
That was a very quick look at couple of logistics APIs that google provides. Please note that the second API dos not give the step by step driving direction, just the drive time. Ciao for now!