Search code examples
javascriptzipcodegoogle-distancematrix-api

Google Distance Matrix API can't find a specific zip code


I am trying to get the distance between zip codes on the client side in JavaScript. The Distance Matrix service has been working great except for one specific zip code: 68434. When I tried performing the request using an ajax request instead it worked but was restricted on browsers with CORS. I am also only restricted to client side calls so no trying for a server side call.

Code:

var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
// Build request for driving distance from zip code 1 to zip code 2
{
    origins: ["87108"],
    destinations: ["68434"],
    travelMode: 'DRIVING'
}, 
// Parse the response message to get the distance
function(response, status) {
    console.log(response);
    //Print any errors to the screen
    if (status !== 'OK') {
        console.log('Error was: '+status);
    }
    else {
        if (response.rows[0].elements[0].status === "OK") {
            console.log("Success");
        }
        else
            console.log("Fail");
    }
});

Is there a safer way to be making these requests or some configuration I may possibly be messing up?


Solution

  • Found a work around. Zip codes alone are considered ambiguous addresses and are therefore less reliable. Using full city, state, and zip code in the address string resolved the issue for this specific input and I haven't run into any issues with any of the other addresses tested. Found the best practices for these APIs and their reliability here: https://developers.google.com/maps/documentation/geocoding/best-practices