Tracking location using iPhone and HTML5

Track a Mobile Device with HTML5

How to Track Your Mobile Device with HTML5

Yesterday I was walking through the city getting lost and wandering around in the sun, it was pretty good but it gave me the idea that it would be cool if I could track my location using my iPhone then look up where I walked. (I mean Apple already do it right, so I might as well see it :D) So at first I made a page that would output the latitude and longitude of the visitor using the API from hostip.info but it was pretty inaccurate so then I looked into using the cool new HTML5 to geolocate.

Getting a users geolocation in HTML5 is pretty easy, simply use JavaScript to get the location then output it to a “div” when the body loads.
Example: Html5 Geo-Locate Example
Source: geolocate.html

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Find Me</title>
<script type="text/javascript">
function findmeifyoucan()
{
     if( navigator.geolocation )
     {
          navigator.geolocation.getCurrentPosition( win, fail );
     }
     else
     {
          alert("No, you don't can has browzer support");
     }
}
 
function win(youare)
{
var longi;
longi=document.value = youare.coords.longitude;
var lati;
lati=document.value = youare.coords.latitude
var myDiv1 = document.getElementById("loco");
myDiv1.appendChild(document.createTextNode(lati));
myDiv1.appendChild(document.createTextNode(","));
myDiv1.appendChild(document.createTextNode(longi));
}
function fail()
{
	//didntwork
}
</script> 
</head>
 
<body onLoad="findmeifyoucan();">
<div id="loco"></div>
  </body>
</html>

Now we have the ability to get the Latitude and Longitude of the visitor we can have the page execute a line of code to add these to a MySQL database so that they can be tracked.
Since PHP is server side and JS is client side I assume that getitng the JS to output a line of PHP such as ” include(‘addtodatabase.php?la=xxx&lo=yyy’); ” won’t work.
So a kind of work around way I found was to have the JavaScript put out a line of HTML that loads the PHP file in a silent iframe.
So instead of this

var myDiv1 = document.getElementById("loco");
myDiv1.appendChild(document.createTextNode(lati));
myDiv1.appendChild(document.createTextNode(","));
myDiv1.appendChild(document.createTextNode(longi));

We say this:

var myDiv1 = document.getElementById("loco").innerHTML="<iframe src='http://yourdomain.com/addtodatabase.php?lati="+lati+"&longi="+longi+"' frameborder='0' width='0' height='0'></iframe>";

Now all we have to do is create a MySQL table to store the values and write the “addtodatabase.php” file to write the values to the database.
So go ahead and create a MySQL database with 4 columns: “ID”,”lat”,”long”,”time” where ID is auto increasing Primary key.
Then create the addtodatabase.php file with the following:

<?php
$longi = $_GET['longi'];
$lati =  $_GET['lati'];
$date = time();
mysql_connect('HOST', 'USERNAME', 'PASSWORD') or die(mysql_error());
mysql_select_db('DATABASE') or die(mysql_error());
$query = "INSERT INTO table VALUES ('','$lati','$longi','$date')";
mysql_query($query);   
mysql_close();
?>

And Finally to bring it all together we need to write a php file to get the location from the database and output a google map of that location along with how recent the data is.
Simple create a php file named “showlocation.php” with the following:

<?php
mysql_connect('HOST', 'USERNAME', 'PASSWORD') or die(mysql_error());
mysql_select_db('DATABASE') or die(mysql_error());
$query="SELECT * FROM table ORDER BY ID DESC LIMIT 1";
$result=mysql_query($query);
mysql_close();
$long=mysql_result($result,0,"long");
$lat=mysql_result($result,0,"lat");
$time=mysql_result($result,0,"time");
 
 
echo"<iframe width=\"200\" height=\"200\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"http://maps.google.co.uk/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=".$lat.",".$long."&amp;aq=&amp;sll=".$lat.",".$long."&amp;sspn=0.0,0.0&amp;gl=uk&amp;ie=UTF8&amp;ll=".$lat.",".$long."&amp;spn=0.0,0.0&amp;z=14&amp;output=embed\"></iframe>";
 
 
 
$unix_time_passed = time() - $time;
if ($unix_time_passed < 60)
{
if ($unix_time_passed != 1){
$elapsed = "Around " . $unix_time_passed . " seconds ago";
	}
	else {
		$elapsed = "Around 1 second ago";
	}}
elseif ($unix_time_passed < 3600)
{
	if (floor($unix_time_passed / 60) > 1){
$elapsed = "Around " . floor($unix_time_passed / 60) . " minutes ago";
	}
	else {
		$elapsed = "Around 1 minute ago";
	}
}
elseif ($unix_time_passed < 86400){
 
	if (floor($unix_time_passed / 3600) > 1){
$elapsed = "Around " . floor($unix_time_passed / 3600) . " hours ago";
	}
	else {
		$elapsed = "Around 1 hour ago";
	}
}
elseif ($unix_time_passed < 604800){
 
	if (floor($unix_time_passed / 86400) > 1){
$elapsed = "Around " . floor($unix_time_passed / 86400) . " days ago";
	}
	else {
		$elapsed = "Around 1 day ago";
	}
}
elseif ($unix_time_passed < 2592000){
 
	if (floor($unix_time_passed / 604800) > 1){
$elapsed = "Around " . floor($unix_time_passed / 604800) . " weeks ago";
	}
	else {
		$elapsed = "Around 1 week ago";
	}
}
elseif ($unix_time_passed < 31536000){
 
	if (floor($unix_time_passed / 2628000) > 1){
$elapsed = "Around " . floor($unix_time_passed / 2628000) . " months ago";
	}
	else {
		$elapsed = "Around 1 month ago";
	}
}
elseif ($unix_time_passed > 31536000){
$elapsed = "Over 1 year ago";
}
echo "<font size='-2'>" . $elapsed."<br \>";
echo "<a href=\"http://maps.google.co.uk/maps?f=q&amp;source=embed&amp;hl=en&amp;geocode=&amp;q=".$lat.",".$long."&amp;aq=&amp;sll=".$lat.",".$long."&amp;sspn=0.0,0.0&amp;gl=uk&amp;ie=UTF8&amp;ll=".$lat.",".$long."&amp;spn=0.0,0.0&amp;z=14\" style=\"color:#0000FF;text-align:left\">View Larger Map</a></font>";
?>

And so finally, wherever you want to show the map that has your last known location, simply add the line:

<?php include('path_to_file/showlocation.php');?>

To your site’s template.
Whenever you wish to update you location you simply open safari in your iPhone and surf to wherever your “geolocate.html” file is and press “allow” when asked if you want to share your location.

Or, if you’re really smart you could set things up to automatically load the file from your phone at specific time intervals.
I will go through how to automatically update your location every 20mins in Part 2.