Search code examples
ionic-frameworkgeolocationionic4ionic-nativedirections

Calculate distance using geolocation in ionic 4


I already can get my map and the route between two points, i would like to calculate de distance in km between that points

the code to trace the route

displayDirection(_origin, destin) {
    var ref = this;
    console.log('DIRECTION');
    var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();

    directionsDisplay.setMap(ref.map)


    directionsService.route({
      origin: _origin,
      destination: destin,
      travelMode: 'DRIVING'
    }, (response, status) => {
      console.log("Response: " + response + " Status: " + status);

      if (status === 'OK') {
        directionsDisplay.setDirections(response);
      } else {
        console.log("Can't set directions due to " + response);
      }
    });
  }

can someone help me?


Solution

  • If you take the response that you receive, there will be an Array of Routes that It will show under the object

    response.routes
    

    In your request object, the array will have one or many route objects in it. The route object will have an array of legs breaking down the journey to smaller pieces. Simply Iterate the Legs to find the total distance. You can use the following method to find it for a route.

    findRouteDistance(route) {
    
        var total_distance = 0;
        var route_legs = route.legs;
    
        for(var i=0; i < route_legs.length; i++) {
             total_distance += route_legs[i].distance.value;
        }
    
        return total_distance;
    }
    

    If you have only 1 route object simply call

    findRouteDistance(response.routes[0])
    

    Or iterate over the response.routes object if you have many.