fanaimi pic

FANAIMI tutorial

How to create a simple geolocation application

Our goal

This is the first of a series of HTML5 tutorials.

Here I will show how to use the new Geolocation API, together with Google map API, to locate the user position and display a map with that position.

After the map is ready, I will show how to add a marker on that map, and how to retrieve further info about user's location with a Reverse Geolocation

geolocation preview

All the content of this tutorial (except fanaimi logo and name) is free and open source. You can use it , copy it, reproduce it, sell it (sell it? ...come on!), destroy it, eat it or do whatever you want. If you like it, you can just link back to this address.

Click on the button to see the working demo LIVE DEMO

Let's get it on.. again

+ Prepare our assets

First thing first, let's have a look to our external assets (inside head tag), you will need:

<!-- Modernizr -->
<script src="assets/js/modernizr-latest.js"></script>
<!-- jQuery -->
<script src="assets/js/jquery-1.6.1.min.js"></script>
<!-- googlemap API: fundamental to show the map -->
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
           		
  • modernizr if you want to use HTML5 or any support detection.
  • An updated version of jQuery.
  • Google map Api V3 script to visualise, modify and enrich our maps.

+ The html content

Let's have a look at the html structure:

<!--this is all we need: a container, an ajax loader, and a map holder-->               
<div id="map">
   <img id="mapAjaxLoader" src="assets/imgs/ajax-loader.gif" width="32" height="32" alt="loader">
   <!--this will hold the map-->
   <div id="mapHolder"> </div>
</div>
 
                
  • a container div (map)
  • an ajax loader gif
  • "mapHolder" will be dynamically filled with our Google map

+ The style

Not much to show here, just a box.. you can customise it as you like

/*-------------------  map holder  --------------------------*/
#mapHolder{ 
	width:336px;
	height:224px;
}  

                
  • style your map holder as you like

+ All the fun here: JavaScript

First step: detect if the brower supports Geolocation

//detecting browser support for Geolocation
if(navigator.geolocation !== 'undefined'){
	//yay! display an happy message and go on..
} else {
	//nay! display a sorry message
}
                

Use a navigation.geolocation method: getCurrentPosition

                
if(navigator.geolocation !== 'undefined'){
    document.getElementById('yourHappyDiv').innerHTML = 'Your browser supports geolocation';
    
    //triggering getCurrentPosition method
    navigator.geolocation.getCurrentPosition(displayLocation, displayError);
    
} else {
    document.getElementById('yourSadDiv').innerHTML = 'Your browser do not support geolocation';
}              
                
  • displayLocation => success handler
  • displayError => error handler

the displayLocation handler

                
/**
*	displayLocation
*
*	gives a text response and starts the map creation
*	@param    position		OBJ		
*/	
function displayLocation(position){
	var lat = position.coords.latitude;
	var lon = position.coords.longitude;
	var latitude = document.getElementById('yourLatitudePar');
	var longitude = document.getElementById('yourLongitudePar');
	latitude.innerHTML = lat+'.';
	longitude.innerHTML = lon+'.';
	
	//calling createMap with position coordinates
	createMap(position.coords);
};//end displayLocation               
                
  • position => this object is automatically generated by getCurrentPosition.
  • position will hold two properties: coords.latitude and coords.longitude

Let's create the map

                
/**
*	createMap
*
*	creates the map using a new  google.maps.Map obj
*	@param coords    OBJ
*/
function createMap(coords){
	//creating a LatLng OBJECT 
	var googleCoords = new google.maps.LatLng(coords.latitude, coords.longitude);
    
    //options to be parsed to google.maps.Map
	var mapOpts = {
		zoom: 15,								//zoom in to show a precise area
		center: googleCoords,					//put user's location in the middle of the map
		mapTypeId: google.maps.MapTypeId.ROADMAP //[ROADMAP - SATELLITE - HYBRID]
	};
	var mapDiv = document.getElementById("mapHolder");
    
    //map creation, new google.maps.Map() OBJ
	map = new google.maps.Map(mapDiv, mapOpts);
}//end createMap              
                
  • make the two coordinates intelligible for google.maps with LatLng
  • position will hold two properties: coords.latitude and coords.longitude
  • create an object of properties to customize the map
  • create a new new google.maps.Map() object

Bonus: add a marker and do a 'reverse geolocation'

+ Google.maps.Marker

Add a marker on your map

//adding a marker to the map [put this line at the end of createMap]
addMarker(map, googleCoords);
                
  • trigger addMarker() from createMap
/**
*	addMarker
*
*	adds a marker on the map using google.maps.Marker
*
*	@param		map
*	@param		googleCoords
*/
function addMarker(map, googleCoords){
	//OBJECT with options for marker
	var markerOpts = {
		animation: google.maps.Animation.BOUNCE,  //[DROP / BOUNCE]
		position: googleCoords,
		map: map,
	}//end markerOpts
	
	var marker = new google.maps.Marker(markerOpts);
}//end addMArker
                
  • create a new marker with 'google.maps.Marker()' constructor

+ Reverse Geolocation

Retrieve information about user's location

//add this line at the end of createMap
getCity(coords);
                
  • create a new marker with 'google.maps.Marker()' constructor
/**
*	getCity
*
*	retrieves info about the location from given coordinates
*
*	@param	coords	latitude and longitude
*/
function getCity(coords){
	var point = new google.maps.LatLng(coords.latitude, coords.longitude);
	
    //creating a new Geocoder OBJ
	var geocoder = new google.maps.Geocoder();
	geocoder.geocode({'latLng': point}, function(results, status){
		if (status == google.maps.GeocoderStatus.OK){
			if (results[1]){
            	//happy feedback
				document.getElementById("yourCITYdiv").innerHTML=results[1].formatted_address;
			}else{
            	//sad feedback and errors
				document.getElementById("yourCITYdiv").innerHTML="City search failed due to: " + status;
			} 
		}
	});
}//end getCity
                
  • create a new LatLng point with 'google.maps.LatLng()' constructor
  • create a new geocoder with 'google.maps.Geocoder()' constructor
  • parse point to geocoder's 'geocode' method
  • results[1].formatted_address is the verbose address of user's location

Conclusions

This was just an example of a map creation using both HTML5 Golocation API and Google.MAPS API.

Creating a map is quite simple, then you can customise it using all sorts of methods and properties from Google.MAPS API, you can add a marker, retrieve info about user's location, animate the marker, add an info window for your location and much more...

To read more about Google.Maps API, just have a look at the documentation.

If you want, you can stay tuned for more following me on twitter.