1

I am using react js and I am getting coordinates from user input. Now I want to calculate the total distance in miles between those coordinates. e.g 51.5035914, -0.1193578 51.5031346, -0.1193844 51.5038217, -0.1282733

So the distance from point a to b + point b to c.

PS. In above example I added only 3 points but it can be 30 or more

1 Answers1

0

If you want to get the distance and time duration to travel between your coordinates, you can use Google Maps Platform API's Distance Matrix API.

To do this, you can get the distance/duration between point A and point B in one Distance Matrix request first and store it in a variable. Then get the distance/duration between point B and point C in another request and add it in the same variable too.

Here is a snippet of a code that shows the Distance Matrix request:

    var service = new google.maps.DistanceMatrixService;
    var orig = this.state.input;
    var dest = this.state.destination;

    service.getDistanceMatrix({
          origins: [orig],
          destinations: [dest],
          travelMode: 'DRIVING',
          unitSystem: google.maps.UnitSystem.METRIC,
          avoidHighways: false,
          avoidTolls: false
        }, (response, status) => {
          if (status !== 'OK') { 
            alert('Error was: ' + status);
          } else {
            var origins = response.originAddresses;
            var destinations = response.destinationAddresses;

            //Loop through the elements row to get the value of duration and distance
            for (var i = 0; i < origins.length; i++) {
              var results = response.rows[i].elements;
              for (var j = 0; j < results.length; j++) {
              var element = results[j];
              var distanceString = element.distance.text;
              var durationString = element.duration.text;

              //add new value to the previousValue 
              this.setState ({
                distance: this.state.distance + parseInt(distanceString, 10)
                });
              console.log(this.state.distance);
              this.setState ({
                duration: this.state.duration + parseInt(durationString, 10)
                });
                console.log(this.state.duration);
               }
             }
          }
          });

Hope this helps!

Pagemag
  • 2,779
  • 1
  • 7
  • 17