Rate Calculator
By john@johnivanoff.com
I'm working on an estimated rate calculator. You enter two ZIP codes and multiply the distance by a rate. For example, 100 miles at 25 cents. I'm using Google's Distance Matrix API 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
{
"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. While testing, I entered 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 of place_id, and you can use origins=place_id:ChIJ3S-JXmauEmsRUcIaWtf4MzE. I thought, "Can I use a ZIP code?" 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.