Sercan Ozdemir
Sercan Ozdemir

Reputation: 4692

Google Maps Distance Matrix API Rounding JS API v3

i have a problem like i mentioned at title. Please look at images at bottom first. 130 METERS

In this image you can easily see it's 130 meters but if i use Distance Matrix API it's showing 0.1 KM,

180 METERS

And here it's 180 Meters but it's showing 0.2 KM in distance matrix API. It's both google how can it be different..

And here's my code to get distance :

 var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
      {
          origins: startArray, //LatLng Array
          destinations: finishArray, //LatLng Array
          travelMode: google.maps.TravelMode.DRIVING,
          unitSystem: google.maps.UnitSystem.METRIC,
          avoidHighways: false,
          avoidTolls: false
      }, callback);

function callback(response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
        alert('Error was: ' + status);
    } else {
        var origins = response.originAddresses;
        var destinations = response.destinationAddresses;

        for (var i = 0; i < origins.length; i++) {
            var results = response.rows[i].elements;
                console.log(results[i].distance.text);
                document.getElementById('ctl00_MainContent_hidSpeed').value += results[i].distance.text+"&";
        }
}
}

Any help would be appreciated

Upvotes: 1

Views: 3470

Answers (2)

Hubvill
Hubvill

Reputation: 504

Figure I'd post this in case it may help someone in the future. If you'd like to show either km or m:

var distance = results[i].distance.value
if (distance < 1000){
    distance = results[i].distance.value + ' m';                    
} else {
    distance = results[i].distance.text;
}

Upvotes: 0

nekaab
nekaab

Reputation: 442

Just use the results[i].distance.value instead of the text.

See https://developers.google.com/maps/documentation/javascript/distancematrix#distance_matrix_responses for an example, in text, it's rounded, but the value displays the distance accurately in meters.

Upvotes: 2

Related Questions