Tracking your route on Google Maps with a non-GPS enabled mobile phone

google-map-small Cycle tourists nowadays can track (record) their route on Google Maps using a GPS-enabled mobile phone. Here's an example on John Talbot's 2009 end-to-end tour in which tracking data was automatically uploaded every 5 minutes whilst he was moving. However, to do a whole day's logging with the phone switched on is battery-intensive and may require external battery packs and somewhere to re-charge at the end of each day.

There's an alternative way that doesn't need a fancy phone left switched on all day. It does require the phone to be switched on from time to time, plus a GPS device to display your position, but it has the advantage that you can go for up to a couple of weeks without having to re-charge the phone, and your friends and relatives will at least be able to see where in the world you are.

Basic requirements

(1) An ordinary non-GPS enabled mobile phone.
(2) A simple GPS device to display your location co-ordinates.
(3) A Google Maps key.
(4) A web hosting account with a MySQL database.

The rest involves writing a few scripts and uploading them to your web space.

Storing Google Map marker co-ordinates

First, create a table ready to receive the co-ordinates you will enter from your mobile phone, and name it 'markers' in your MySQL database, using:

CREATE TABLE `markers` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`lat` FLOAT(10,6) NOT NULL,
`lng` FLOAT(10,6) NOT NULL,
`datetime` DATETIME NOT NULL
) ENGINE = MYISAM;

Outputting Google Map marker co-ordinates

Next, create the following .php file, name it output-xml.php, and upload it to your web space. The file will be used to output any latitude and longitude markers stored in the database to an XML file like this one »

<?php

  // Connect to database
  require("path/to/your_connection_script.php");

  function parseToXML($htmlStr) {
    $xmlStr=str_replace('<','&lt;',$htmlStr);
    $xmlStr=str_replace('>','&gt;',$xmlStr);
    $xmlStr=str_replace('"','&quot;',$xmlStr);
    $xmlStr=str_replace("'",'&#39;',$xmlStr);
    $xmlStr=str_replace("&",'&amp;',$xmlStr);
    return $xmlStr;
  } 

  // Select all the rows in the markers table
  $query = "SELECT lat, lng, DATE_FORMAT(datetime,
  '%W %M %D, %Y %T') AS datetime FROM markers WHERE 1";
  $result = mysql_query($query);
  if (!$result) {
    die('Invalid query: ' . mysql_error());
  }

header("Content-type: text/xml");

  // Start XML file, echo parent node
  echo "<markers>\n";

  // Iterate through the rows, printing XML nodes for each
  while ($row = @mysql_fetch_assoc($result)){
    // ADD TO XML DOCUMENT NODE
    echo '<marker ';
    echo 'lat="' . $row['lat'] . '" ';
    echo 'lng="' . $row['lng'] . '" ';
    echo 'datetime="' . $row['datetime'] . '" ';
    echo "/>\n";
  }

  // End XML file
  echo '</markers>';

  // Free up the resources
  mysql_free_result ($result);

  // Close the database connection
  mysql_close();

?>

Entering Google Map marker co-ordinates

To be able to enter into the database the latitude and longitude of your position – the co-ordinates – a further file is required. This file will be a web page that contains only a simple form to be used on your mobile phone. Mine is as follows, and I've named it input.php. Upload it to your web space.

<?php

  $showbutton = TRUE;

  if (isset($_POST['submit'])) { // If form submitted

    // Get vars
    $lat = $_POST['lat'];
    $lng = $_POST['lng'];

    // Check string lengths
    if (strlen($lat) < 6) {
      $problem = TRUE;
      $response0 = "LATITUDE too short.<br />";
    }
    if (strlen($lng) < 6) {
      $problem = TRUE;
      $response1 = "LONGITUDE too short.<br />";
    }

    // Check if numeric
    if(!is_numeric($lat)) {
      $problem = TRUE;
      $response0a = "LATITUDE not numeric.<br />";
    }
    if(!is_numeric($lng)) {
      $problem = TRUE;
      $response1a = "LONGITUDE not numeric.<br />";
    }

    if (!$problem) { // If no problem, connect to database
      require("path/to/your_connection_script.php");
      // Build MySQL query
      $query = "INSERT INTO markers (lat, lng, datetime)
      VALUES ('$lat', '$lng', NOW())";
      // Run query
      $result = @mysql_query ($query);
      // Check result
      if ($result) {
        mysql_close();
        $response2 = "MySQL query OK.<br />";
      } else { // No result
        $response2 = "MySQL query didn't run.<br />";
      }
      $response3 = "Co-ordinates entered."; // End
      $showbutton = FALSE;
    } else { // Problem
      $response3 = "Try again."; // End
    }

  }

?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="lat" size="12" maxlength="12" value="
<?php if (isset($_POST['submit'])) echo $_POST['lat']; ?>"
tabindex="1"><br />
<input type="text" name="lng" size="12" maxlength="12" value="
<?php if (isset($_POST['submit'])) echo $_POST['lng']; ?>"
tabindex="2"><br />
<?php
  if ($showbutton == TRUE) {
 // Only show the Insert button if form not yet submitted
?>
<input type="submit" name="submit" value="Insert" tabindex="3">
<?php } ?>
</form>
<?php

  // Response section
  if (isset($_POST['submit'])) {
    echo "\n";
    echo $response0;
    echo $response0a;
    echo $response1;
    echo $response1a;
    echo $response2;
    echo $response3;
  }

?>

Here is my actual script »

The Google Map

Of course you need a web page where your Google Map displays the markers according to their co-ordinates, with a line linking them in the correct sequence. This page will need to call an external JavaScript file, and this is the one I use:

  function load() {
    if (GBrowserIsCompatible()) {

      // Get map (Version 2)
      var map = new GMap2(document.getElementById("map"));
      map.setUIToDefault(); // Default user interface

      // Get course
      GDownloadUrl("output-xml.php", function(data) {
        var xml = GXml.parse(data);
        var markers =
        xml.documentElement.getElementsByTagName("marker");
        var points = new Array(0); // For polyline
        // Loop through the markers
        for (var i = 0; i < markers.length; i++) {
          var datetime = markers[i].getAttribute("datetime");
          var point =
          new GLatLng(parseFloat(markers[i].getAttribute("lat")),
          parseFloat(markers[i].getAttribute("lng")));
          points[i] =
          new GLatLng(parseFloat(markers[i].getAttribute("lat")),
          parseFloat(markers[i].getAttribute("lng")));
          var marker = createMarker(point, datetime);
          map.addOverlay(marker);
        } // End loop
        // Polyline
        var polyline = new GPolyline(points, "#ff0000", 4);
        map.addOverlay(polyline);
        // Set map centre (to last point), zoom level
        map.setCenter(point, 9);
        // InfoWindow HTML (last marker)
        var html = "";
        html += "<div id=\"infobox\">";
        html += "Hello. This is my latest position on";
        html += "<br />" + datetime;
        html += "<br />updated manually with my mobile.";
        html += "</div>";
        map.openInfoWindowHtml(point, html);
      });
    }
  }

  // General markers
  function createMarker(point, datetime) {
    var marker = new GMarker(point, datetime);
    var html = "<div id=\"infobox\">Co-ords: " + point + "<br />"
    + datetime + "<br /><a href=\"/map\">Re-load</a></div>";
    GEvent.addListener(marker, 'click', function() {
      marker.openInfoWindowHtml(html);
    });
    return marker;
  }

Here is my actual JavaScript file »

The map

The actual Google Map is here »

Obviously, the red lines that link the markers are not the precise route travelled. Their purpose is to indicate the markers' chronological sequence, so that someone following the travellers' progress can get a general picture, and know they were in a particular place at a particular time. Typically, the cycle tourist would switch on their mobile phone at the end of each day, navigate to their input.php page in the phone's web browser, and manually enter their latitude and longitude read as decimal co-ordinates from their GPS device, the whole process taking two minutes at the most, at a cost of just a few pence.

Summary

  • Obtain a Google Map key from Google
  • Obtain a web hosting account with a MySQL database and create the database
  • In the database, create the markers table (code above)
  • Create and upload to your web space input.php to input the markers (code above) – this will need a script that connects to the database
  • Create and upload to your web space output-xml.php to output the markers (code above) – this will need a script that connects to the database
  • Create and upload to your web space the JavaScript file to call the map and the markers (code above)
  • Create and upload to your web space the HTML map page with Google Map key, and call the JavaScript file (view source of sample maps)
  • Begin entering markers via input.php on your mobile phone
  • View the markers in your map page on the web

Further related guidance at Google: Using PHP/MySQL with Google Maps »


8 comments on “Tracking your route on Google Maps with a non-GPS enabled mobile phone”

  1. Charlie wrote:

    Hi man. I found this code very useful but I don't how have you implemented it by your own . Can u send me the code for this if you don't mind.

    Thanks man :)

  2. Dan wrote:

    This is brilliant! Thankyou! I've Implimented this flawlessly!
    A big thankyou Patrick for sharing your code!

    Regards
    Dan.

  3. Dan wrote:

    Im struggling getting the Icon's to change too, is there an easier way to change the pins to show the latest entry with a differnt icon??

    Cheers
    Dan.

  4. simon wrote:

    Dear sir, i'm very interested on this. I have follow the instruction and coding that you provide to build up my system. But i doesnt look complete, and not really work well. Do u mind send me the complete coding. thx

  5. Patrick wrote:

    All the coding is either on this page or in the links above. You also need a Google Maps key to place in the <head> of your HTML output page. Another example from May last year. If you view the source code (that page) you'll see the key in the document head. I would need to know more about what isn't working in your case.

    Also required:

    <body onload="load()" onunload="GUnload()">
    

    Dan seems to have made it work. I've only just seen his question about the pins and I don't know the answer, though I'm sure it's possible.

  6. simon wrote:

    well. i put output-xml.php, and GMAP in different pages.
    in order to make the GMAP display the latest marker, i need to refresh output-xml.php first and then refresh GMAP.

    is tat anyway to make it refresh automatically or. And is it u combine all the codes in one pages ?

  7. Patrick wrote:

    The XML output URL (page) for the markers is a different URL to the map page. First, you need to test your XML output page by itself. It should be something like this. The markers come from the database, so check that you have your markers.

    Then that URL is entered into the JavaScript file. See the lines:

    // Get course
    GDownloadUrl("output-xml-02.php", function(data) {
    

    This will call your markers into the map, but see also (in the JavaScript file):

    // General markers
    function createMarker(point, datetime) {
        var marker = new GMarker(point, datetime);
        var html = SEE THE LINK TO THE MAP PAGE
    
  8. simon wrote:

    Thank you SIR. i need to try it now. Anyway thx u for your guide. GOD bless

Leave a comment

Add a Smiley Smiley »