Introduction 

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.  

 

Background 

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

 map.png 

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 good understanding of how the Google Maps Javascript API works. Although, there was no article I found which pulls series of co-ordinates from a database or datatable and plots a continous path on the run. I have explained in steps how to do the same as below: 

Step - 1  Create a Default.aspx page with following content.

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

<!DOCTYPE html>
<html>
<head>
<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>
<link 
href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" 
rel="stylesheet" type="text/css" />

<!--Google API Javascript Reference-->
<script type="text/javascript" 
src="http://maps.google.com/maps/api/js?sensor=false"></script> 

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

 

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" src="http://maps.google.com/maps/api/js?sensor=false"></script>   

 

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 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)
    {
        try
        {
            String Locations = "";
            String sJScript = "";
            int i = 0;
            foreach (DataRow r in tblPoints.Rows)
            {
                // bypass empty rows 
                if (r["latitude"].ToString().Trim().Length == 0)
                    continue;

                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
                });";
                i++;
            }

            // 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);
                                 poly.setMap(map);

                                 var path = poly.getPath();

                                 " + Locations + @"

                             }
                </script>";
            return sJScript;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

In above code, we will be genrating the necessory 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;
            dt.Rows.Add(row);

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

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

            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. 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.

 

History

GPSLib v1.1 -

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"