Google's Distance Matrix Service & Using Zip Codes
I'm working on an estimate rate calculator. You enter in two zip codes and multiply a distance by a rate. e.g., 100 miles by 25 cents I'm using the Distance Matrix Service API by Google to get the distance.
You can use a URL like https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=44039&destinations=75081&key=your_api_key and it will return
You can use a URL like https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=44039&destinations=75081&key=your_api_key and it will return
{ "destination_addresses" : [ "Richardson, TX 75081, USA" ], "origin_addresses" : [ "North Ridgeville, OH 44039, USA" ], "rows" : [ { "elements" : [ { "distance" : { "text" : "1,162 mi", "value" : 1870791 }, "duration" : { "text" : "17 hours 13 mins", "value" : 62001 }, "status" : "OK" } ] } ], "status" : "OK" }
You can take the distance and do your math. A problem I was running into was when I used the zip code 16508. https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=44039&destinations=16508&key=your_api_hey The address for that was missing
{ "destination_addresses" : [ "" ], "origin_addresses" : [ "North Ridgeville, OH 44039, USA" ], "rows" : [ { "elements" : [ { "status" : "NOT_FOUND" } ] } ], "status" : "OK" }
Well, that doesn't work. In doing some testing, I mashed in a four digit zip code and got results back. I noticed the four-digit zip had a complete address. How can I ensure I look for zip codes? I dug deeper into the documentation since searching the web didn't turn up anything. I saw a mention about place_id, and you can use origins=place_id:ChIJ3S-JXmauEmsRUcIaWtf4MzE. I thought "Can I use zip?" https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=zip:16508&destinations=zip:44039&key=your_api_key
{ "destination_addresses" : [ "Erie, PA 16508, USA" ], "origin_addresses" : [ "North Ridgeville, OH 44039, USA" ], "rows" : [ { "elements" : [ { "distance" : { "text" : "122 mi", "value" : 196682 }, "duration" : { "text" : "1 hour 58 mins", "value" : 7077 }, "status" : "OK" } ] } ], "status" : "OK" }
It works. Now I can get distances to Erie, PA.
I hope this helps.
I hope this helps.