Skip to main content

Mobile Geolocation

Published on
With the new wave of mobile devices being a major way to access the Internet, it has become possible to customize web applications based on a user's location - or create web applications based on user location. This example will show you how to get a user's location, pull up a static Google Map, and the query a database for locations within one mile of the user's location. W3C released a Geolocation API, which is what browser's use to get geolocation information.
<script type="text/javascript">

//Do we support geolocation

if (navigator.geolocation) {

    //Get the location, requires callback functions for it's parameters
    navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
    alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}

// Success callback function
function displayPosition(pos) {
    var lat = pos.coords.latitude;
    var lng = pos.coords.longitude;

    //We'll place the code for getting database data here and more.
}

// Error callback function
function errorFunction(pos) {
    alert('Error!');
}
</script>
We invoke getCurrentPosition with two callback functions, one on success and one on error.  In the displayFunction we declare the latitude and longitude variables. This function is also where we will put the code to grab locations from the database. Since PHP is a server-side language and JavaScript a client-side language we cannot put PHP within our JavaScript. We'll have a different file for the PHP script and grab its contents using some JavaScript. Luckily, there is jQuery and the process is a lot simpler. Place this code within the displayFunction.
//Be sure to add jQuery to your site! Or it won't work
<script src="http://code.jquery.com/jquery-latest.js"></script>

//Uses jQuery to send an HTTP POST, then grabs the return data.
$.post("library/mobile_callback.php", {lat: ""+mylat+"", lng: ""+mylong+"", dst: 1 }, function(data){
if(data.length >0) {
$('#locations').html(data);
}
});
The code uses HTTP POST to send our parameters to the PHP script and will return an HTML unordered list that will be placed into the div field with the id of locations.  The PHP script access a database table which has the fields id, name, lat, lng. It takes the POST parameters and queries up to 20 results.  
<? require('mysql.php'); 

//Need to have Latitude and Longitude
if($_POST["lat"] && $_POST["lng"]) {

//Declare variables, make sure we have a distance
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$dst = (empty($_POST['dst']) ? 1 : $_POST['dst'];

//The query. I did a search for the math equation, this is first one I found from a math site.
$sql = 'SELECT *, ( 3959 * acos( cos( radians('.$lat.') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('.$lng.') ) + sin( radians('.$lat.') ) * sin( radians( lat ) ) ) ) AS distance
FROM locations HAVING distance < '.$dst.' ORDER BY distance';

echo '<ul id="locations_list">';

$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo '<li>'.$row['name'].'</a></li>';
}

echo '</ul>';
}
?>
And that's it! If you want to add a Google Map, just add this code in the displayFunction, for myself I put it under the $.post() call.
 var gCoords = lat + ', ' + long;
 var gMap = '<img src="http://maps.googleapis.com/maps/api/staticmap?center=' + gCoords;
 var gMap2 = '&zoom=14&size=320x200&markers=color:red%7Clabel:Your%20Location%7C' + gCoords + '&sensor=false" />';
$('#map_canvas').html(gMap+gMap2);

I'm available for one-on-one consulting calls – click here to book a meeting with me 🗓️