Home > Google Map, GPS Tracking System > GPS Tracking Monitoring Application with Google Map

GPS Tracking Monitoring Application with Google Map

In the previous article we have discussed the global architecture of the GPS Tracking system which consists of the Tracking Device and Monitoring Application. In this article we will discuss about the GPS Tracking Application Monitoring.

Introduction

The monitoring application will display a Marker on the map view provided by Google Map. This Marker represents the last position of the GPS Tracking Device. Marker coordinate data is taken from a table on a database which contains last GPS position data and is constantly updated by the GPS Tracking Device so that the information obtained is always the up to date position.

The monitoring application consists of several parts that can be described as follows.

Arsitektur Aplikasi Pemantau

Section Description
File viewer.php File viewer.php This is the main file of the monitoring application. This file consists of the Google Map Object. There is a definition of the timer that will call the lastpos.xml.php file periodically. On each periodic time, the display on the Google Map Marker Object will be updated with the latest position data in the database
File lastpos.xml.php File lastpos.xml.php This file is used to read data from the database and generate output data in the form of XML to be used by a Google Map to display the Object Marker on a certain position.
Google Map Object Google Map Object Google Map object that is used for displaying a map on a coordinate position and a zoom level.

Next let us study in detail the functional part of each Monitoring Application.

User Interface Design

Here is a display of user interface design for the monitoring application that we are going to build.

clip_image002[4]

The user interface is very simple, consisting only of the Google Map object, the list box that contains the code of the moving objects that will be observed, and one button to zoom the map that will move the position of Google Map with a center point, that is the coordinates of the selected objects selected in the list box. Besides that, we will also see the information box that contains the detail information about the selected moving objects such as code, coordinates, time, and so forth.

Google Map Object initialization

Note the program source code below, which is a fragment of the file viewer.php.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Sistem Pemantau GPS Tracking</title>
<script src="http://maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;key=abcde" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
   var map = null;
   var timeOut=null;
   var markers=[];
   var htmls=[];
   function load()
   {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(-6.8790, 107.63520), 12);
        map.enableScrollWheelZoom();
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        refreshMarkers();}
  }
//]]>
</script>
</head>
<body onload="load()" onunload="GUnload()"><div id="map" style="width: 400px; height: 400px">Loading</div>
</body>
</html>

On the line 10-13 variable initialization is done:

  1. map : the Google Map object variables
  2. timeOut: timer variable
  3. markers : an array that holds all the Marker on the map
  4. htmls : an array that holds all the HTML data for the information box of all existing Marker on the map

On the line 15-28 defined load () function, which is first called when the HTML document is downloaded by the user. The following is done here:

  1. at line 19: make a Google Map object and store it in the variable map
  2. at line 20: make the map object reacts to a button on the mouse wheel, that is if the button on the mouse wheel will cause the map to play in the zoom in and out. This is done by calling enableScrollWheelZoom() method
  3. at line 21: added a map of the area control can be used to replace, men-in and zoom out the map. This is done by calling addControl () method with the parameter object GSmallMapControl.
  4. On line 22: added a control area that can be used to select the type of map if the road map, satellite images, or both. This is done by calling addControl() method with the parameter object GMapTypeControl.
  5. at line 23: we make a determination of the center map setCenter() method and select the type of map of the combined map and satellite map of the road (hybrid) with the method setMapType().
  6. after the initialization is done, we call the function refreshMarkers() to display the Marker which is the correct representation of the moving objects that we want to monitor.

Displaying Marker from database

This is done by two functions: refreshMarkers() and createMarker(). Note the source code below, which also is part of the file viewer.php.

function refreshMarkers()
{
   clearTimeout(timeOut);
   GDownloadUrl("lastpos.xml.php", function(data, responseCode) {
    var fetch=0;
    window.status= responseCode + ‘:’ + fetch++;
    if(responseCode != 200) {return;}
    for (var i=0; i<markers.length; i++){
      map.removeOverlay(markers[i]);}
    var xml = GXml.parse(data);
    var xmarkers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < xmarkers.length; i++) {
       var label = xmarkers[i].getAttribute("label");
       var point = new  GLatLng(parseFloat(xmarkers[i].getAttribute("lat")), parseFloat(xmarkers[i].getAttribute("lon")));

       map.addOverlay(createMarker(point, i, label) );
}});
timeOut=setTimeout("refreshMarkers()",5000);
}

The above source code displays refreshMarkers() function that will be called by the load() function as noted before.

The first thing that will be done each time the function is called is to turn off the timer if it’s already defined on timeOut variable. Look at line 3.

Next on line 5 the function GDownloadUrl() is called. The invoked URL is the lastpos.xml.php file that is the file which will output a data in the form of XML that contains coordinates information for the markers which represents the moving object to be observed. This is a simple example of the lastpos.xml.php:

<?
mysql_connect("localhost","root","");
mysql_select_db("dijexi_gps");
$sql="select * from lastpos order by id";
$res=mysql_query($sql) or die(mysql_error());
echo ‘<?xml version="1.0" encoding="UTF-8"?>’;
echo "<markers>\n";
while($row=mysql_fetch_array($res))
{
 $unit_id =$row[‘unit_id’];
 $latitude =$row[‘lat’];
 $longitude  =$row[‘lon’];
 echo ‘<marker lat="’.$latitude.‘" lon="’.$longitude.‘" label="’.$unit_id.‘" /> ‘;
}
echo "</markers>\n";
?>

After downloading the data, this function will execute a function defined at it’s second parameter by giving it’s input parameter as the data obtained from the download and the responseCode (from the server).

This function the handle the data downloaded as shown from the line 6. First, it will show an information on the status bar about the response code to make it easy for debugging, especially if the download process from the URL was failed, which is the responseCode was not 200.

If the download was failed, the program is simply exits and wait for the next timer event, as seen on the line 7-10.

At line 12-15 we destroy all existing markers stored on the array variable markers. This is done by invoking removeOverlays() method of the map object for the markers with index i, where i begins from 0 until the size of the array element ot markers, the markers.length.

At line 17 we do the parsing of the XML data resulted from the download into a variable of type XML data called xml, which is done by parse() mehtod of the Gxml object.

After successfully parsed, the data in the object variable xml can be read to get any data element on it. For example at line 18, we read the element named “marker”, which is done by invoking getElementsByTagName(”marker”) method of the documentElement object contained in the xml object. The data element of the XML is then stored on JavaScript array variable called xmarkers.

After successfully read the element then we can do a looping through all xmarkers array elements to get the attributes of the XML. This is done at line 19 – 25, which are setting up a variable i that begins from 0 until the size of array xmarkers, that is xmarkers.length.

At every loop, we read the attribute “label” that exists on every XML element data. We do this by calling getAttribute(”label”) method on xmarkers object with index i. This Attribute is then stored on variable called “label”.

Next, at line 21-23 we also get the “lat” and “lon” attribute from every XML element data . But this time, the attribute is to be converted from string into float with the parseFloat() function, and is used as a parameter for creating a new object with type of GLatLng() and stored on a variable “point”.

At line 24, the “point” variable is used as a parameter for createMarker() function which is to be explained later. The Function createMarker() results a data with GMarker type which can be used to display a marker on the Google Map by calling addOverlay() method.

At line 28 we can see:

TimeOut = setTimeout("refreshMarkers()",5000);

This is a JavaScript command that define a timer which will execute the function refreshMarkers() every period of time, i.e 5000 ms.

The command itself is executed inside the body of refreshMarkers() function that will cause an infinite loop of timer events.

Next, this is the complete definition of createMarker() function which will be used to create a new object with type of GMarker and a parameter.

function createMarker(point, index, label)
{
var marker = new GMarker(point );
var html= "<pre>"+label+"</pre>";
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
markers[index]=marker;
htmls[index]=html;
return marker;
}

The createMarker() function will be called by refreshMarkers() function as described before. This function can then be modified to result an object marker with a custom icon and not a standard icon from Google Map.

At line 1 is the definition of createMarker() function that have point parameter that represents the coordinate information on where the marker will be plotted on the map, an index that represents the index of the marker, and a label that will be displayed on the information box for that marker.

At line 2 we create a variable marker of type GMarker() object at the coordinate defined by point variable.

At line 3 we define a variable html that contains “<pre>” and the label variable taken from the function parameter and end it with “</pre>”.

At line 4 we register a new event with the help of Gevent.addListener for the marker object on “click” event. What will be done when the object marker receive a mouse click is to invoke the function that contains the command marker.openInfoWindowHtml(). This will result: when the marker is clicked then an information box will appear with the marker information on it.

At line 5-6 we store the new marker on the JavaScript array markers[] and the labels for the informatin box on the JavaScript array htmls[]. Both variable will be used when the user interface need to select one of the markers exists on the Google Map.

At line 13 the function returns the result which is the object marker with type of GMarker recently created before.

List of Objects monitored

As on the specification, we need a list box that lists the moving objects to be monitored. We can choose one object from the list and click Zoom To to display the object on the map by moving Google Map to the object’s coordinate.

Below is the source code to creating the list box which read the data from lastpos table.

<div id="controller" style="position:absolute; left:400px; top:10px">
<form> <select name="unit_id" multiple>  <?
    mysql_connect("localhost","root","");
mysql_select_db("dijexi_gps");
 $sql="select concat(unit_id,’|',lat,’|',lon), unit_id from lastpos order by id asc";
$rs = mysql_query($sql) or die(mysql_error());
while ($row=mysql_fetch_row($rs))
 {
echo "<option value =’" . $row[0] . "’>" . $row[1];
}
?>
</select>
<p>
<input type="button" value="Zoom To" onClick="zoomTo(this.form.unit_id.selectedIndex ,this.form.unit_id.value)">
</form>
</div>

Note on the PHP code to read the data and display them into a list box. At line 5 we define an SQL command to be sent to MySQL to result a data that consists of 2 fields:

  1. the one that contained the concatenation of field unit_id, lat, and lon separated by pipe character “|”, which in here we use MySQL function CONCAT(). This field will be used as an identification of the item to be selected from list box as the “value” for that list box
  2. field unit_id, to be used as the label for the list box

At line 7-11 there are a PHP commands to generated all query result from the SQL command to create a HTML syntax to display a list box as specified.

At line 15-17 there are HTML syntax to display a “Zoom To” button that will execute JavaScript zoomTo() function when clicked, with a parameter index of the item chosen from the list box, and the value of that item. The value of that item is the concatenation of unit_id, lat, and lon separated by pipe character “|”.

Below is the zoomTo() function needed above:

function myclick(i)
{
markers[i].openInfoWindowHtml(htmls[i]);
}

function zoomTo(index, unit_id){
if(unit_id=="") {
alert(‘Please select Unit ID’);
 return ;
}
var temp = new Array();
temp = unit_id.split(‘|’);
var p=new GLatLng(parseFloat(temp[1]), parseFloat(temp[2]));
 map.setCenter(p,13);
myclick(index);
}

Note at line 5, we define the zoomTo() function. The function is to be called when the “Zoom To” button is clicked that will make Google Map to have a center point to be the same as the coordinate of the object selected from the list box and the do the zoom at a certain level.

At line 7-10 we do the checking of whether the parameter variable unit_id is not empty, which means that whether a user has chosen one of the item from the list box before. If not, then just exits from the function.

At line 12-13 we define an array variable temp to store the data from the separation of the variable unit_id with pipe character “|”. The results are the temp variable which has 3 element: unit_id, latitude, and longitude.

At line 14, we create an object variable p of type GLatLng() with parameter temp[1] and temp[2] which are lat and lon defined and converted info float by parseFloat() function before.

At line 15 we set the center point for Google Map to be the coordinate of the p variable which is the same as the cooirdinate of the item chosen at zoom level 13. The result is the map will move and show the marker right at the center.

At line 18 we call the function myClick() with the parameter index which is the variable of the zoomTo() parameter. This is the index of the list box item chosen by user.

Function myClick() is used to show the information box of a marker by calling openInfoWindowHtml() method of the marker. If we remember at the createMarker() function, we have assigned array variable markers[] and htmls[] with marker objects and the label for each markers.

On this myClick() function, that array is used again using the index taken from the list box index. One thing to be noted is that the index of the array markers[] and htmls[] must refer to the same index with the one at the list box, which in this case when we define the SQL command to read the data from lastpos tabel before.

The Completed File viewer.php

Below is the source code of the file viewer.php as described above.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "<A href=’http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"‘ jQuery1246946979000="3">http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"</A>>
<html xmlns="<A href=’
http://www.w3.org/1999/xhtml"’ jQuery1246946979000="4">http://www.w3.org/1999/xhtml"</A>>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Sistem Pemantau GPS Tracking</title>
<script src="http://maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;key=abce" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var timeOut=null;
var markers=[];
var htmls=[];

function load() {
if (GBrowserIsCompatible())
{
 map = new GMap2(document.getElementById("map"));
 map.setCenter(new GLatLng(-6.8790, 107.63520), 12);
map.enableScrollWheelZoom();
 map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
 refreshMarkers();
     }
}

function refreshMarkers(){
clearTimeout(timeOut);
GDownloadUrl("data.xml", function(data, responseCode) {
var fetch=0;
 window.status= responseCode + ':' + fetch++;
 if(responseCode != 200)
{
return;
 }
 for (var i=0; i<markers.length; i++)
 {
map.removeOverlay(markers[i]);
}
var xml = GXml.parse(data);
 var xmarkers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < xmarkers.length; i++)
{
var label = xmarkers[i].getAttribute("label");
var point = new GLatLng(
parseFloat(xmarkers[i].getAttribute("lat")),
parseFloat(xmarkers[i].getAttribute("lon")));
 map.addOverlay(createMarker(point, i, label) );
}
 });
timeOut=setTimeout("refreshMarkers()",5000);
}

function createMarker(point, index, label) {
var icon = new GIcon();
var marker = new GMarker(point );
var html= "<pre>"+label+"</pre>";
 GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
markers[index]=marker;
 htmls[index]=html;
return marker;
}

function myclick(i) {
markers[i].openInfoWindowHtml(htmls[i]);
}

function zoomTo(index, unit_id){
if(unit_id=="") {
alert('Please select Unit ID');
return ;
}
 var temp = new Array();
temp = unit_id.split('|');
var p=new GLatLng(parseFloat(temp[1]), parseFloat(temp[2]));
map.setCenter(p,13);
myclick(index);
}
//]]>
</script>
</head>
<body onload="load()" onunload="GUnload()">
<div id="map" style="width: 400px; height: 400px">Loading</div>
<div id="controller" style="position:absolute; left:400px; top:10px">
<form>
<select name="unit_id" multiple>
<?
mysql_connect("localhost","root","");
mysql_select_db("dijexi_gps");
 $sql="select concat(unit_id,’|',lat,’|',lon),unit_id from lastpos order by id asc";
$rs = mysql_query($sql) or die(mysql_error());
while ($row=mysql_fetch_row($rs))
{
echo "<option value =’" . $row[0] . "’>" . $row[1];
}
?>
 </select>
<p>
<input type="button" value="Zoom To" onClick="zoomTo(this.form.unit_id.selectedIndex ,this.form.unit_id.value)">
</form>
</div>
</body>
</html>

Preview of the Application

Below is the preview of the GPS Tracking Monitoring Application:

Aplikasi Pemantau GPS Tracking

On the next article we will discuss the J2ME application to be run on the Nokia N95 hand phone so that it can send it’s GPS position data to our GPS tracking server.

Related Article:

Akhmad Daniel Sembiring

vITraining.com – Qualified IT Products, Outsourcing, and Services

Ligarwangi.com – Linux, E-book, Coffee, Gift, etc

  • Share/Bookmark
  1. devi
    November 3rd, 2009 at 13:48 | #1

    wah pak bapak emang jago.. skarang tracknya dah otomatis jalan markernya, tapi markernya muncul semuanya… pake map.clearoverlays malah hilang semuanya, maunya saya titik terakhir lah marker muncul gak muncul semuanya, ada saran pak ?

  2. May 10th, 2010 at 14:35 | #3

    Waw… artikelnya mantap thank’s saya dapat masukan lagi…smoga sukses

  3. May 23rd, 2010 at 21:36 | #4

    Thank you so much for your great article.
    But I need more help, when marker is move to outside map .
    the map is not move with maker so I can not see marker.

    Regards
    Chuan

  4. May 23rd, 2010 at 22:45 | #5

    Thank you so much .
    Now I can resolve my job by add this line to refreshMarkers function

    function refreshMarkers(){
    clearTimeout(timeOut);
    GDownloadUrl(“data.xml.php”, function(data, responseCode) {
    var fetch=0;
    window.status= responseCode + ‘:’ + fetch++;
    if(responseCode != 200)
    {
    return;
    }
    for (var i=0; i<markers.length; i++)
    {
    map.removeOverlay(markers[i]);
    }
    var xml = GXml.parse(data);
    var xmarkers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < xmarkers.length; i++)
    {
    var label = xmarkers[i].getAttribute("label");

    var point = new GLatLng(
    parseFloat(xmarkers[i].getAttribute("lat")),
    parseFloat(xmarkers[i].getAttribute("lon")));
    map.setCenter(point); //<<============================ add this line to make map follow our marker
    map.addOverlay(createMarker(point, i, label) );

    }
    });
    timeOut=setTimeout("refreshMarkers()",5000);
    }

  5. fanny
    August 5th, 2011 at 16:04 | #6

    wah pak kok pk bhs inggris? jd lebih rumit:) tp gpp trims
    apa ini juga membutuhkan alat gps/ponsel biasa/ponsel dg gps? tks

  1. No trackbacks yet.
This site uses a Hackadelic PlugIn, Hackadelic SEO Table Of Contents 1.6.0.