4

I am having trouble starting with this new feature that I have to implement on an application that I am working on. So the application works like this; A user inputs a point on the map by pressing a button and gets a latlng for source. Another modal opens and then they have to do the same for destination. What I want to do is to calculate the distance between two points and show a route on the map. I have been trying to find tutorials on this but have had no luck. Anyone knows how to do this or have any working example repo that I can have a look at it? Would be of great help. Thanks!

BleachedAxe
  • 393
  • 2
  • 5
  • 20
  • With the google maps api you can get the distance between two points as simple as passing the 2 locations. – pinedax Apr 07 '17 at 23:47
  • Two locations are passed as latlng objects? What is the name of the api? – BleachedAxe Apr 07 '17 at 23:53
  • this is an example: https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=40.6655101,-73.89188969999998&destinations=40.6905615%2C-73.9976592. The full documentation is here: https://developers.google.com/maps/documentation/distance-matrix/intro – pinedax Apr 07 '17 at 23:59

1 Answers1

6

Have you seen this:

https://stackoverflow.com/a/27943/52160

 function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
    var R = 6371; // Radius of the earth in km
    var dLat = deg2rad(lat2-lat1);  // deg2rad below
    var dLon = deg2rad(lon2-lon1); 
    var a =
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
        Math.sin(dLon/2) * Math.sin(dLon/2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
        var d = R * c; // Distance in km
        return d;
    }

    function deg2rad(deg) {
      return deg * (Math.PI/180)
    }
  }
Swapnil Kadam
  • 4,075
  • 5
  • 29
  • 35
Jay Ordway
  • 1,708
  • 2
  • 11
  • 33