Click here to Skip to main content
14,243,950 members

Plot Path using Google Maps JavaScript API

Rate this:
4.67 (8 votes)
Please Sign up or sign in to vote.
4.67 (8 votes)
31 Mar 2011CPOL
This article describes how to plot path on Google map using array of latitude & longitude points.


I was looking for some code which pulls Google co-ordinates (latitude & longitude) from database and plot the respective path on my Google map. So I studied the Google Maps JavaScript API and implemented a function which reads the GPS co-ordinates from a ASP.NET Data Table and plots the path on page_load event.


You may refer to this article for basic information about each function in Google maps JavaScript API.


Using the Code

I was able to plot the path between just two co-ordinates easily, using one of Google JavaScript API function. There are many articles on CodeProject which gave me a good understanding of how the Google Maps JavaScript API works. However, there was no article I found which pulls series of co-ordinates from a database or datatable and plots a continuous path on the run. I have explained in steps how to do the same as below:

Step - 1

Create a Default.aspx page with the following content:

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

Inherits="_Default" %>

<!DOCTYPE html>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Plot Path Demo Using Google Maps JavaScript API v3</title>


rel="stylesheet" type="text/css" />

<!--Google API Javascript Reference-->
<script type="text/javascript" 


<!--Literal Control for runtime javascript-->
<asp:Literal ID="js" runat="server"></asp:Literal>
<body onload="initialize()">
  <form id="form1" runat="server">
            <!--Canvas for showing the google map-->
           <div id="map_canvas" style="width: 100%; height: 100%;"></div>

Let me explain in brief how the Google Maps JavaScript API works in here. First, we add Google API JavaScript Reference in head tag:

<script type="text/javascript" 

Then, you place a block level element like div on the page, where you want the map to be shown:

<div id="map_canvas" style="width: 100%; height: 100%;"></div>

Next, add a JavaScript function on onload event of html body tag as below:

<body onload="initialize()"> 

Step - 2

Create a class GPSLib.cs Under App_Code directory & create the following function. I have declared the function and respective class (GPSLib) as static so it can be accessed directly without creating any object.

public static String PlotGPSPoints(DataTable tblPoints)
            String Locations = "";
            String sJScript = "";
            int i = 0;
            foreach (DataRow r in tblPoints.Rows)
                // bypass empty rows 
                if (r["latitude"].ToString().Trim().Length == 0)

                string Latitude = r["latitude"].ToString();
                string Longitude = r["longitude"].ToString();

                // create a line of JavaScript for marker on map for this record 
                Locations += Environment.NewLine + @"
                path.push(new google.maps.LatLng(" + Latitude + ", " + Longitude + @"));

                var marker" + i.ToString() + @" = new google.maps.Marker({
                    position: new google.maps.LatLng
			(" + Latitude + ", " + Longitude + @"),
                    title: '#' + path.getLength(),
                    map: map

            // construct the final script
            sJScript = @"<script type="text/javascript">

                             var poly;
                             var map;

                             function initialize() {
                                 var cmloc = new google.maps.LatLng
					(33.779005, -118.178985);
                                 var myOptions = {
                                     zoom: 11,
                                     center: cmloc,
                                     mapTypeId: google.maps.MapTypeId.ROADMAP

                                 map = new google.maps.Map
				(document.getElementById('map_canvas'), myOptions);

                                 var polyOptions = {
                                     strokeColor: 'blue',
                                     strokeOpacity: 0.5,
                                     strokeWeight: 3
                                 poly = new google.maps.Polyline(polyOptions);

                                 var path = poly.getPath();

                                 " + Locations + @"
            return sJScript;
        catch (Exception ex)
            throw ex;

In the above code, we will be generating the necessary JavaScript code needed to create the map along with the plotting. The above function PlotGPSPoints() will return a string object with respective JavaScript code. You may find more information regarding how this script works here.

I am reading the values(latitude, longitude) from datatable row by row in a for loop and creating a 'Locations' string, which is nothing but JavaScript code. This code will be embedded in initialize() function.

Step - 3

Adding code to the page_load event of Default.aspx Page to display the plotted path using the function PlotGPSPoints(). I have manually created a DataTable with 2 columns Latitude & Longitude and added 3 rows and passed it to draw the path as below:

if (!IsPostBack)
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("Latitude"));
            dt.Columns.Add(new DataColumn("Longitude"));

            DataRow row = dt.NewRow();
            row["Latitude"] = 33.779005;
            row["Longitude"] = -118.178985;

            row = dt.NewRow();
            row["Latitude"] = 33.879005;
            row["Longitude"] = -118.098985;

            row = dt.NewRow();
            row["Latitude"] = 33.979005;
            row["Longitude"] = -118.218985;

            js.Text = GPSLib.PlotGPSPoints(dt); ;

You may extract your co-ordinates from the database into a datatable with 2 columns latitude & longitude and pass it to GPSLib.PlotGPSPoints() function as parameter. The rest will be automatically taken care of.

Points of Interest

If you are inside a web application and trying to add a new class in App_Code folder, it will not be accessible until you set the value of Build Action property to 'Compile' instead of 'Content'. To do the same, select the class and hit F4 to view its properties.


  • GPSLib v1.1


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Technical Lead
India India
No Biography provided

Comments and Discussions

GeneralHow to show Name,Titile on Icon indicator when click whether hover Pin
naren 819861414-Feb-19 22:23
membernaren 819861414-Feb-19 22:23 
PraiseThanks a lot ,I am very grateful to you. Pin
naren 819861414-Feb-19 17:53
membernaren 819861414-Feb-19 17:53 
QuestionMap not display Pin
Member 1195845121-Nov-15 2:18
memberMember 1195845121-Nov-15 2:18 
QuestionNot showing map Pin
Member 1132591821-Dec-14 0:38
memberMember 1132591821-Dec-14 0:38 
QuestionCreating Long Distance Path Pin
Member 111362697-Oct-14 10:58
memberMember 111362697-Oct-14 10:58 
QuestionWant to use this in web platform Pin
Member 1084617026-May-14 23:38
memberMember 1084617026-May-14 23:38 
AnswerRe: Want to use this in web platform Pin
indianDEV27-May-14 0:08
memberindianDEV27-May-14 0:08 
GeneralRe: Want to use this in web platform Pin
Member 1084617027-May-14 0:18
memberMember 1084617027-May-14 0:18 
QuestionHow to draw a route between two markers in Google Maps API? Pin
Ravi.Kumar02117-Jan-14 7:44
professionalRavi.Kumar02117-Jan-14 7:44 
QuestionCan you pls do it in MVC3 Pin
memberRAMESHVELAYUDHAN18-Apr-13 1:27 
Questionset panTo auto-zoom on marker's click? Pin
Member 98158386-Feb-13 18:52
memberMember 98158386-Feb-13 18:52 
SuggestionResolve maps does not show up Pin
John Tang17-Jan-13 22:51
memberJohn Tang17-Jan-13 22:51 
GeneralRe: Resolve maps does not show up Pin
memberRAMESHVELAYUDHAN9-Apr-13 2:53 
GeneralRe: Resolve maps does not show up Pin
santrotech14-Feb-15 20:20
membersantrotech14-Feb-15 20:20 
GeneralRe: Resolve maps does not show up Pin
naren 819861414-Feb-19 17:54
membernaren 819861414-Feb-19 17:54 
Questioni aspect from you Pin
twinkle 283-Oct-12 23:36
membertwinkle 283-Oct-12 23:36 
AnswerRe: i aspect from you Pin
ManiRat24-Jun-15 22:45
memberManiRat24-Jun-15 22:45 
NewsResolved the Map Display Issue Pin
indianDEV2-Oct-12 20:34
memberindianDEV2-Oct-12 20:34 
Questionmap does not work Pin
twinkle 2827-Sep-12 21:58
membertwinkle 2827-Sep-12 21:58 
AnswerRe: map does not work Pin
indianDEV27-Sep-12 22:05
memberindianDEV27-Sep-12 22:05 
QuestionLatitude And Longitude How can set on code on map basis Pin
Muhammad Paryal16-Dec-11 2:18
memberMuhammad Paryal16-Dec-11 2:18 
AnswerRe: Latitude And Longitude How can set on code on map basis Pin
indianDEV16-Dec-11 8:30
memberindianDEV16-Dec-11 8:30 
Questionmap doesnt show Pin
Member 81305622-Aug-11 4:29
memberMember 81305622-Aug-11 4:29 
AnswerRe: map doesnt show Pin
indianDEV16-Dec-11 8:33
memberindianDEV16-Dec-11 8:33 
GeneralRe: map doesnt show Pin
Member 183650510-May-12 20:01
memberMember 183650510-May-12 20:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 31 Mar 2011


24 bookmarked