How to measure distance between two points on Google Maps InfoWindow? - JavaScript

random

How to measure distance between two points on Google Maps InfoWindow? - JavaScript

Measure and calculate distance on Google Maps


In this post I will explain about to measure and calculate distance between two or more points on Google Maps. Find the sample code below:



Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to measure distance between two points on Google Maps InfoWindow?</title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>

    <script src="jquery-1.7.2.js" type="text/javascript"></script>

    <script src="MeasureDistance.js" type="text/javascript"></script>

    <style type="text/css">
        html, body, #map-canvas
        {
            margin: 0;
            padding: 0;
            height: 550px;
            width: auto;
        }
    </style>
    <%--Google Maps API--%>

    <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: 9,                                    // 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();">
    <form id="form1" runat="server">
    <a href="#" onclick="MeasureDistance();">Click here to measure distance</a>
    <br />
    <br />
    <div id="divLength">
        <span>Distance: 0 km</span>
    </div>
    <br />
    <div id="map-canvas">
    </div>
    </form>
</body>
</html>

MeasureDistance.js


// 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 Source Code Click here .. 

How to measure distance between two points on Google Maps InfoWindow? - JavaScript Reviewed by Ravi Kumar on 6:43 PM Rating: 5

3 comments:

  1. Hi, I would like to download this code, but the link doesn't seem to work. Could you please update the link

    ReplyDelete
    Replies
    1. Hello! It's updated, you can download the source code.

      Delete

All Rights Reserved by Etechpulse © 2012 - 2017

Contact Form

Name

Email *

Message *

Powered by Blogger.