Google Maps Geolocation and Directions to a Specific Destination

While helping in the redesign of Signum’s website I took a look at Google Maps. It’s been almost 2 years since I last used the API for my end career project.

Now I wanted to know if I could make use of geolocalization and directions to show a visitor the way to get to our headquarters from wherever he/she is, instead of just showing with a marker where we are. Thanks to geolocation we can find out with precission the position coordinates of the visitor.

Geolocation to guide visitor's to a specific place
View demo

The code makes use of HTML5 and Google geolocation services, as well as the new Google Maps API v3.

Some time ago I would have done this (in fact in the project I did this way) querying an IP address to Location database to get the position, having to update data almost every month, as IP addresses were reassigned.

Now you can get it done by using HTML5 geolocation feature primarily an then use an alternative service as a fallback in case the browser does not support HTML5 or it throws an error when getting the location.

Here is the code:

<!DOCTYPE html>
<html>
<head>
<title>How to get to our headquarters</title>
<style type="text/css">
html {
height: 100%;
}

body {
font: 12px Helvetica, Arial ,sans-serif;
height: 100%;
margin: 0;
padding: 0;
}

#map, #route {
width: 100%;
height: 50%;
}
#route {
overflow-y:auto;
}
#method {
position: absolute;
left: 75px;
top:15px;
padding:10px;
opacity: .9;
-moz-opacity: .9;
z-index: 10;
background-color:#fff;
border-radius:3px;
-moz-border-radius:3px;
-webkit-border-radius:3px;

}
</style>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://www.google.com/jsapi"></script>
<script>
var map; //the google map
var directionsService; //service that provides directions to get to our destination
var directionsDisplay; //rendeder that draws directions on map
var destinationName = "Ventorro del Cano, Madrid"; //our destination. Set yours!

function initiate_geolocation(skipHTML5){

if (!skipHTML5 && navigator.geolocation) {
// HTML5 GeoLocation
function getLocation(position) {
document.getElementById("method").innerHTML = "Location obtained using HTML5";
showMapAndRoute({
"lat": position.coords.latitude,
"lng": position.coords.longitude
});
}
navigator.geolocation.getCurrentPosition(getLocation, error);
} else {
// Google AJAX API fallback GeoLocation
if (typeof google == 'object') {
var geocoder = new google.maps.Geocoder();
if (google.loader.ClientLocation) {
document.getElementById("method").innerHTML = "Location obtained using Google Geocoder";
showMapAndRoute({
"lat": google.loader.ClientLocation.latitude,
"lng": google.loader.ClientLocation.longitude
});
} else
{
alert("Google Geocoder was unable to get the client position");
}
}
}
}

function showMapAndRoute(l)
{
var latlng = new google.maps.LatLng(l.lat,l.lng);

var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

map = new google.maps.Map(document.getElementById("map"), myOptions);
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("route"));

var request = {
origin: l.lat + ',' + l.lng ,
destination: destinationName,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}

function error(e)
{
switch(e.code)
{
case e.TIMEOUT:
alert ('Timeout');
break;
case e.POSITION_UNAVAILABLE:
alert ('Position unavailable');
break;
case e.PERMISSION_DENIED:
alert ('Permission denied');
break;
case e.UNKNOWN_ERROR:
alert ('Unknown error');
break;
}

//try to get location using Google Geocoder
initiate_geolocation(true);
}
</script>
</head>
<body onload="initiate_geolocation()">
<div id="method"></div>
<div id="map"></div>
<div id="route"></div>
</body>
</html>

You can view the demo. The code is mostly self-explanatory. We need to show the map, obtain the visitor’s position, ask for the directions and render them over the map.

In my tests I have seen that I get null when checking google.loader.ClientLocation. It means that Google couldn’t retrieve a position to the IP that it has detected, so in this case the fallback can fail some times (maybe we should use a second fallback?).

Comments are closed.