Draw interactive polyline path from source to destination in Google Maps v3

random

Draw interactive polyline path from source to destination in Google Maps v3

C# - Draw a route between two markers in Google Maps API


In my previous posts I explained How to create google maps Latlng object from latitude and longitude string, How to Geocode an Address or Zip Code using Google Maps API v3, How to calculate angle of line between two points in JavaScript? and many more. 

In this article I will show how to make polylines based on routing on google maps and plot route between two points using javascript.

 Make polylines based on routing on Google Maps, javascript - Drawing routes on google maps,javascript - google maps plot route between two points,javascript - Draw line in google map follow the route

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 id="Head1" runat="server">
    <title>How to draw a route between two markers in Google Maps API? </title>
    <script src="jquery-1.7.2.js" type="text/javascript"></script>

    <style type="text/css">
        html, body, #map-canvas
        {
            margin: 0;
            padding: 0;
            height: 500px;
            width: auto;
        }
    </style>
    <%--Google Maps API--%>
    <style type="text/css">
        .labels
        {
            color: white;
            background-color: #4CC417;
            font-family: "Lucida Grande" , "Arial" , sans-serif;
            font-size: 10px;
            text-align: center;
            width: 10px;
            white-space: nowrap;
        }
    </style>

    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>

    <script type="text/javascript">
            // Loading google map on web page
            var map;var MarkerArray =[]; 
            var icon='';
           
            // creating a map on web page
            function initialize() {
              var mapOptions = {
                zoom: 12,                                    // Set Zoom Level
                center: new google.maps.LatLng(19.114029,72.873688 ),     // 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);                       
            }                    
           
            // adding markers on map
            function AddMarker(lat, lng)
            {  
                var latlng=CreateLatLngObject(lat, lng);
                var marker = new google.maps.Marker({
                
                position: latlng,
                map: map,
                icon: icon               
              });  
              MarkerArray.push(marker);
            }  
           
             // Create Lat/Lon object
            function CreateLatLngObject(Latitude, Longitude) {
            var latlng = new google.maps.LatLng(parseFloat(Latitude), parseFloat(Longitude));
            return latlng;
            }
             
           // Fetching latitude and longitude from the database using asp.net handler
           function GetData() {
                    var respons = $.ajax({
                    url: "Handler.ashx?Analysis=getInfo",
                    type: "post",
                    async: false,
                    data: {},
                    success: function (data) {
                    },
                    error: function () {
                        alert("failure");
                    }
                }).done(function (resp) {
                    if (resp != '') {
                   
                        var jresp = $.parseJSON(resp);                       
                        DrawLocationOnMap(jresp);                       
                    }
                    else
                    {
                        alert('No data found.');
                    }
                });
            }
                      
              // Drawing location through latitude & longitude
              var arrCoordinates = [];var lPath='';

              function DrawLocationOnMap(jresp)
              {
                    arrCoordinates = new Array();
                   
                    for (var i = 0; i < jresp.data.columns.length; i++) {
                        var ClmnVal = jresp.data.rows[i];
                        if(i==0)
                        {   
                            icon='http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=A|4CC417|000000';
                            AddMarker(ClmnVal.split(',')[0], ClmnVal.split(',')[1]);
                           
                        }
                        else if(i==jresp.data.columns.length-1)
                        {
                            icon='http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=B|4CC417|000000';
                            AddMarker(ClmnVal.split(',')[0], ClmnVal.split(',')[1]);                           
                        }
                        arrCoordinates.push(new google.maps.LatLng(ClmnVal.split(',')[0], ClmnVal.split(',')[1]));
                    }
                   
                        lPath = new google.maps.Polyline({
                        path: arrCoordinates,
                        strokeColor: '#4CC417',
                        strokeOpacity: 1.0,
                        strokeWeight: 5
                    });
                   
                    lPath.setMap(map);  return arrCoordinates;          
           }
          
           // Removing line path from the map
           function RemoveLocationOnMap() {
                   if (arrCoordinates) {
                    arrCoordinates.length = 0;
                    lPath.setMap(null)
                    RemoveMarkersFromArray();
                }
                    arrCoordinates = [];                   
            }     
           
            // Removing markers from the map
            function RemoveMarkersFromArray() {         
                if (MarkerArray) {
                    for (var i = 0; i < MarkerArray.length; i++) {
                        MarkerArray[i].setMap(null);
                    }
                }         
            MarkerArray = new Array();
        }
    </script>

</head>
<body onload="initialize();">
    <form id="form1" runat="server">
    <p>
        Draw interactive polyline path from source to destination in Google Maps v3</p>  
    <a href="#" style="text-decoration: none;" onclick="GetData();">Draw Route Path</a>&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="#" style="text-decoration: none;" onclick="RemoveLocationOnMap();">Clear Map</a>
    <br />
    <br />
    <div id="map-canvas">
    </div>
    </form>
</body>
</html>

Handler.ashx


<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Data;
using System.Text;

public class Handler : IHttpHandler, System.Web.SessionState.IRequiresSessionState{
   
    public void ProcessRequest (HttpContext context) {
        if (context.Request.QueryString.Count > 0)
        {
            if (context.Request.QueryString["Analysis"].Trim().Equals("getInfo"))
            {
                getLayerinfo(context);
            }
        }
    }

    private void getLayerinfo(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        string featureInfo = getFeatureinfo(context);
        context.Response.Write(featureInfo);
        context.Response.End();
    }

    private string getFeatureinfo(HttpContext context)
    {
        string featurefetail =string.Empty;
       
        DataTable dt = new DataTable();
        dt.Columns.Add("Latitude", typeof(string));
        dt.Columns.Add("Longitude", typeof(string));

        //
        // Here we add DataRows.
        //
        dt.Rows.Add("19.090022", "72.9039");
        dt.Rows.Add("19.126356", "72.889481");
        dt.Rows.Add("19.128951", "72.867508");
        dt.Rows.Add("19.130248", "72.849655");
        dt.Rows.Add("19.162033", "72.847595");

        if (dt.Rows.Count > 0)
        {
            featurefetail = "{\"status\":true,\"data\":{";
            string colarr = "", rowArr = "";

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string colName = dt.Columns[0].ColumnName + "," + dt.Rows[i][1].ToString() + "";
                string rowVal = dt.Rows[i][0].ToString() + "," + dt.Rows[i][1].ToString()+"";
               
                if (rowVal != "")
                {
                    colarr += (colarr == "") ? "\"" + colName + "\"" : ",\"" + colName + "\"";
                    rowArr += (rowArr == "") ? "\"" + rowVal + "\"" : ",\"" + rowVal + "\"";
                }
            }

            colarr = "\"columns\":[" + colarr + "]";
            rowArr = ",\"rows\":[" + rowArr + "]";

            featurefetail += colarr + rowArr + "}}";
        }
        else
        {
            featurefetail = "{\"status\":false,\"data\":\"\"}";
        }
        return featurefetail;
    }
   
    public bool IsReusable {
        get {
            return false;
        }
    }

}
Download the source code click here ..
Please leave your comments, suggestions and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading .. :)

Draw interactive polyline path from source to destination in Google Maps v3 Reviewed by Ravi Kumar on 2:40 PM Rating: 5

No comments:

All Rights Reserved by Etechpulse © 2012 - 2017

Contact Form

Name

Email *

Message *

Powered by Blogger.