Calculate distance between current location and and a different location using Google Maps API V3

10,205

Simplified script using libraries=geometry

function getLocation() {
  navigator.geolocation.getCurrentPosition(
            function(position) {
                var latLngA = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
                var latLngB = new google.maps.LatLng(40.778721618334295, -73.96648406982422);
                var distance = google.maps.geometry.spherical.computeDistanceBetween(latLngA, latLngB);
                alert(distance);//In metres
            },
            function() {
                alert("geolocation not supported!!");
            }
    );
}
Share:
10,205

Related videos on Youtube

Admin
Author by

Admin

Updated on July 11, 2022

Comments

  • Admin
    Admin almost 2 years

    I'm trying to calculate the distance between my location and a different location, but all I get is NaN. I'm pretty sure I placed the code in the wrong place in the script. Can somebody help me figuring this issue?

    <!DOCTYPE html>
    <html>
    <head>
        <script src="http://maps.google.com/maps/api/js?sensor=false&v=3&libraries=geometry"></script>
    </head>
    <body>
        <p id="demo"></p>
        <button onclick="getLocation()" id="demo">get current location</button>
        <button onclick="console.log(distance)">get ditance from current location to other location</button>
    
        <script>
            var lat;
            var longt;
            var latLngA = new google.maps.LatLng(lat, longt);
            var latLngB = new google.maps.LatLng(40.778721618334295, -73.96648406982422);
            var distance = google.maps.geometry.spherical.computeDistanceBetween(latLngA, latLngB);
    
            var x=document.getElementById("demo");
    
            function getLocation(){
                if (navigator.geolocation){
                    navigator.geolocation.getCurrentPosition(showPosition);
                }
                else{
                    x.innerHTML="Geolocation is not supported by this browser.";}
                }
    
            function showPosition(position){
                lat = position.coords.latitude;
                longt = position.coords.longitude;
                x.innerHTML="Latitude: " + lat + "<br>Longitude: " + longt; 
            }
        </script>
    </body>
    </html>
    
  • Admin
    Admin about 11 years
    It works perfectly! One question though: is the function(position) must be declared as function(position)? Is that the syntax of the API?
  • kzfabi
    kzfabi almost 11 years
    Just to clarify some points. A) distance is in meters. B) google.maps.geometry library is not loaded by default so you have to add "&libraries=geometry" to the URL when you load Google Maps API. See docs for more info.