calculate distance between two points google maps javascript api

Keywords | calculate distance between two points google maps javascript api, calculate distance between two points in google maps, how to measure distance google maps

How to Measure Distance Google Maps

Let’s start with the formula of measure distance between two points. The distance formula is derived from the Pythagorean theorem. To find the distance between two points (x1,y1) and (x2,y2), all that you need to do is use the coordinates of these ordered pairs and apply the formula pictured below.

calculate distance between two points google maps calculate distance between two points google maps Calculate Distance Between Two Points Google Maps JavaScript distance between two points google maps api min

The above formula finds the length of a line that stretches between two points: Point 1 and Point 2 The linear distance is the square root of the square of the horizontal distance plus the square of the vertical distance between two points.

Calculate Distance Between two points Google Maps Javascript API

Since we’ll be using the Google Maps API to calculate the distance from two locations, first you’ll need to make sure you have an API Key. The following example will show you how to measure distance using google maps javascript API. Find the below source code to calculate distance between two points google maps: –

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Calculate distance between two latitude longitude points google maps api</title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBLMa7emvhGQMK0uYYrS-9aymoEhlX-4sU"></script>
    <script src="jquery-1.7.2.js" type="text/javascript"></script>
    <script type="text/javascript" src="utility.js"></script>
    <style type="text/css">
        html, body, #map-canvas {
            margin: 0;
            padding: 0;
            height: 350px;
            width: auto;
        }
    </style>
    <script type="text/javascript">
        var map;
        var infoHandler;
        var DistanceBearingPolyline;
        var isDistanceFlag = false;
        var DistBearingPolylineClickHdl = 0;
        var DistBearingMapClickHdl = 0;
        var InfoWindowCloseClickHdl = 0;

        function initialize() {
            var mapOptions = {
                zoom: 11,                                    // Set Zoom Level
                center: new google.maps.LatLng(28.667696, 77.224059),     // Set the Latitude and longitude of the location
                mapTypeId: google.maps.MapTypeId.ROADMAP    // Set Map Type Here ROADMAP, TERRAIN, SATELLITE
            };


            map = new google.maps.Map(document.getElementById('map-canvas'),      // Creating the map object to desplay
                mapOptions);

            /*Global mousemove event, developer has to manage the event while coding to use flags for different functionalities*/
            google.maps.event.addListener(map, 'mousemove', function (event) {
                // $('#divCoords').html(roundNumber(event.latLng.lat(), 5) + "," + roundNumber(event.latLng.lng(), 5));
                if (isDistanceFlag) {
                    if (DistanceBearingPolyline != null) {
                        var path = DistanceBearingPolyline.getPath();
                        var len = path.getLength();
                        $('#divLength').html("<span>Length: " + DistanceBearingPolyline.inKm() + " km</span>");
                        if (len == 1) {
                            path.push(event.latLng);
                        } else {
                            path.setAt(len - 1, event.latLng);
                        }
                    }
                }
            });
        }
    </script>
</head>
<body onload="initialize();">   
        <h1>Google maps distance from location to location</h1>
        <a href="#" onclick="MeasureDistance();" style="font-family: Verdana; font-size: 14px;">Click here to measure distance</a>
        <br />
        <br />

        <div id="divLength">
            <span style="font-family: Verdana; font-size: 14px; color: red"><b>Distance: 0 km</b></span>
        </div>
        <br />

        <div id="map-canvas">
        </div>    
</body>
</html>

Utility.js – Functions to calculate distance between two points google maps javascript api

// Calculate measure distance between points      
function MeasureDistance() {
    removeClickListnrs();
    $('#divLength').html("<span>Distance: 0 km</span>");
    if (DistanceBearingPolyline) {
        DistanceBearingPolyline.setMap(null);
        DistanceBearingPolyline = null;
        map.setOptions({ draggableCursor: '' });
    }
    else {
        map.setOptions({ draggableCursor: 'crosshair' });
        google.maps.event.addListenerOnce(map, "click", function (event) {
            addPolyline(event.latLng);
        });
    }
}

// To set default cursor pointer to the map
function DefaultCursorPointer() {
    map.setOptions({ draggableCursor: '' });

    removeDistanceLine();
    removeClickListnrs();
    measureReset();
}

// To remove click listener
function removeClickListnrs() {
    google.maps.event.removeListener(infoHandler);
}

// To add polyline to the map
function addPolyline(latlng) {
    if (!isDistanceFlag) {
        DistanceBearingPolyline = new google.maps.Polyline
            ({
                strokeColor: '#0000FF', //"#0000FF"=blue
                strokeOpacity: 1,
                strokeWeight: 2,
                path: [latlng],
                map: map
            });

        google.maps.event.addListener(DistanceBearingPolyline, 'click', adddistancePoint);
        google.maps.event.addListenerOnce(DistanceBearingPolyline, "dblclick", function (event) {
            addPolyline(event.latLng);
        });
        isDistanceFlag = true;
    }
    else {
        isDistanceFlag = false; var eDist = DistanceBearingPolyline.inKm();
        var eInfoWindowContent = "<b>Measurement Info</b><br><br><b>Distance (km):</b> " + eDist; //+ "<br><b>Bearing (deg) :</b> "+eBear;

        infoWindowPOly = new google.maps.InfoWindow({ content: eInfoWindowContent, position: latlng, size: new google.maps.Size(50, 50) });
        infoWindowPOly.open(map);

        InfoWindowCloseClickHdl = google.maps.event.addListener(infoWindowPOly, "closeclick", function (event) {
            ClearEvents_ComputeDistanceBearing();
        });
        map.setOptions({ draggableCursor: '' });

    }
}

// To clear events when close infowindow
function ClearEvents_ComputeDistanceBearing() {
    google.maps.event.removeListener(DistBearingPolylineClickHdl);
    google.maps.event.removeListener(DistBearingMapClickHdl);
    google.maps.event.removeListener(InfoWindowCloseClickHdl);
    map.setOptions({ draggableCursor: '' });
    if (DistanceBearingPolyline) {
        DistanceBearingPolyline.setMap(null);
        infoWindowPOly.close(map);
    }

    DistanceBearingPolyline = null;
    isDistanceFlag = false;

    DistBearingMapClickHdl = null;
    InfoWindowCloseClickHdl = null;
    DistBearingPolylineClickHdl = null;
}

// adding distance point to the map
function adddistancePoint(e) {
    var vertices = DistanceBearingPolyline.getPath();
    vertices.push(e.latLng);
    $('#divLength').html("<span>Distance: " + DistanceBearingPolyline.inKm() + " km</span>");
}
google.maps.Polyline.prototype.inKm = function (n) {
    var a = this.getPath(n), len = a.getLength(), dist = 0;
    for (var i = 0; i < len - 1; i++) {
        dist += a.getAt(i).kmTo(a.getAt(i + 1));
    }
    return roundNumber(dist, 2);
}

google.maps.LatLng.prototype.kmTo = function (a) {
    var e = Math, ra = e.PI / 180;
    var b = this.lat() * ra, c = a.lat() * ra, d = b - c;
    var g = this.lng() * ra - a.lng() * ra;
    var f = 2 * e.asin(e.sqrt(e.pow(e.sin(d / 2), 2) + e.cos(b) * e.cos(c) * e.pow(e.sin(g / 2), 2)));
    return f * 6378.137;
}

google.maps.LatLng.prototype.bearing = function (a) {
    var e = Math, ra = e.PI / 180; deg = 180 / e.PI;
    var x = a.lng() - this.lng();
    var y = a.lat() - this.lat();
    var f = 0;
    if (x >= 0 && y >= 0) {
        y = y * ra; x = x * ra;
        f = 90 - e.atan(y / x) * deg;
    } else if (x >= 0 && y <= 0) {
        y = y * ra; x = x * ra;
        f = 90 + e.abs(e.atan(y / x) * deg);
    } else if (x <= 0 && y <= 0) {
        y = y * ra; x = x * ra;
        f = 270 - e.atan(y / x) * deg;
    } else if (x <= 0 && y >= 0) {
        y = y * ra; x = x * ra;
        f = 270 + e.abs(e.atan(y / x) * deg);
    }
    return f;
}

// function to round an number
function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec) + '';
    var r = result.indexOf('.');
    if (r == -1) result += ".00";
    return result;
}

Download Code

What do you think?

I hope you liked this article on calculate distance between two points google maps. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

LEAVE A REPLY

Please enter your comment!
Please enter your name here