google-maps-api-3map-directions

google maps directionsService giving wrong results


I am trying to get distance in miles and estimated time with googles directionsService. It sort of works but I know the results its giving me are incorrect. The distance and time are too short? I need results in driving mode. A sample of the code is :

HTML

<input id="s_lat" value="52.441334" />
<input id="s_lng" value="-1.654737" />
<input id="d_lat" value="52.450439" />
<input id="d_lng" value="-1.729660" />

JS

var n_start = s_lat + ',' + s_lng;
var n_end = d_lat + ',' + d_lng;

function getdistance() {
    var directionsService = new google.maps.DirectionsService();

    var request = {
        origin      : n_start,
        destination : n_end,
        travelMode  : google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        durationInTraffic: true
    };

    directionsService.route(request, function(response, status) {
        if ( status == google.maps.DirectionsStatus.OK ) {

            alert (response.routes[0].legs[0].duration.value);
            alert (response.routes[0].legs[0].distance.value);
        }
        else {
            // oops, there's no route between these two locations

        }
    });

}

Solution

  • The result I get with the posted code is NOT_FOUND, I don't get a distance. A comma separated string is not a google.maps.LatLng or a google.maps.LatLngLiteral, it is treated as an address and geocoded before returning the results.

    This:

    var n_start = s_lat + ',' + s_lng;
    var n_end = d_lat + ',' + d_lng;
    

    Should be (google.maps.LatLngLiteral):

    var n_start = {lat: parseFloat(s_lat.value), lng: parseFloat(s_lng.value)}; 
    var n_end = {lat: parseFloat(d_lat.value), lng: parseFloat(d_lng.value)};
    

    Or (google.maps.LatLng):

    var n_start = new google.maps.LatLng(s_lat.value,s_lng.value);
    var n_end = new google.maps.LatLng(d_lat.value,d_lng.value);
    

    Proof of concept fiddle

    enter image description here

    Code snippet:

    function initMap() {
      var n_start = new google.maps.LatLng(s_lat.value,s_lng.value);
      var n_end = new google.maps.LatLng(d_lat.value,d_lng.value);
     
    
      function getdistance() {
        var directionsService = new google.maps.DirectionsService();
    
        var request = {
          origin: n_start,
          destination: n_end,
          travelMode: google.maps.TravelMode.DRIVING,
          unitSystem: google.maps.UnitSystem.METRIC,
          durationInTraffic: true
        };
        console.log(JSON.stringify(request));
        directionsService.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
    
            console.log("duration=" + response.routes[0].legs[0].duration.value + " seconds");
            console.log("distance=" + response.routes[0].legs[0].distance.value + " meters");
            document.getElementById('result').innerHTML = "distance=" + (response.routes[0].legs[0].distance.value / 1000).toFixed(2) + " km<br>duration=" + (response.routes[0].legs[0].duration.value / 60).toFixed(2) + " minutes";
            new google.maps.DirectionsRenderer({
              map: new google.maps.Map(document.getElementById('map')),
              directions: response
            })
          } else {
            window.alert('Directions request failed due to ' + status);
    
          }
        });
    
      }
      getdistance();
    }
    #map {
      height: 100%;
    }
    
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <input id="s_lat" value="52.441334" />
    <input id="s_lng" value="-1.654737" />
    <input id="d_lat" value="52.450439" />
    <input id="d_lng" value="-1.729660" /><br>
    <div id="result"></div>
    <div id="map"></div>
    <!-- Replace the value of the key parameter with your own API key. -->
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>