HTML5 GeoLocation

Many websites can benefit from knowing exactly where the user accessing their site is from, enabling a more personalized local experience. As part of the HTML5 efforts, the W3C has developed a set of APIs to effectively allow the client-side device (i.e. your iPhone 3G+, Android 2.0+ phones, or even your conventinal desktop browsers) to retrieve geographic positioning information with JavaScript.

To get the current position, use the getCurrentPosition() API call. When called, it must immediately return and then asynchronously acquire a new Position object. If successful, this method must invoke its associated successCallback argument with a Position object as an argument. If the attempt fails, and the method was invoked with a non-null errorCallback argument, this method must invoke the errorCallback with a PositionError object as an argument.

In order to protect the privacy of the user, when the browser is loaded the user is initially prompted to disclose this current location of deny it.

This is the prompt on Firefox.

Here is the code snippet that is used to obtain the current position.

<!DOCTYPE html> // indicate that it is a HTML5 doc
<html>
<head>

<!– initialize for google maps –>
<meta name=”viewport” content=”initial-scale=1.0, user-scalable=no” />

</head>

<body onload=”initialize()”>

</body>

</html>

function initialize() {
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(handle_geolocation_query, handle_errors);
}

function handle_errors(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED: alert(“user did not share geolocation data”);
break;

case error.POSITION_UNAVAILABLE: alert(“could not detect current position”);
break;

case error.TIMEOUT: alert(“retrieving position timedout”);
break;

default: alert(“unknown error”);
break;
}
}

function handle_geolocation_query(position){
clat = position.coords.latitude;
clng = position.coords.longitude;

console.log(‘values to map current location’ + ‘lat: ‘ + clat + ‘ lng: ‘ + clng);

}
}

Many kinds of applications and games can enriched by adding automatic location information. The location API can be paired up with google maps, bing maps or proprietary geolocation data to provide compelling solutions.

In this post I will show how to pair location API with google maps.

To display the position on the map we need to include the google maps library in the head tag.

<script type=”text/javascript” src=”http://maps.google.com/maps/api/js?sensor=false”></script&gt;

sensor=false implies that the devise has no inbuilt location detection capabilities, like GPS.

The location API response contains, the coords and timestamp fields. The timestamp field simply denotes the time at which the instance of geolocation data was created. The coords attribute contains a set of geographic coordinates together with their associated accuracy, as well as a set of other optional attributes such as altitude and speed.

Before initializing the map we need to create a LatLng object with the latitude and longitude.

Initializing the Map

var myLatlng = new google.maps.LatLng(38,-97);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
mymap = new google.maps.Map(document.getElementById(“map”), myOptions);

map” is the id of the div in the body of the html.

Once we have initialized the map, we can add markers to the map and display information for each marker. Store the initialized map and latitude and longitude in global variables called mymap, clat, clng so that they can be used through out the code.

// function for adding a marker to the page.
function addMarker(location, message) {
marker = new google.maps.Marker({
position: location,
map: mymap,
animation: google.maps.Animation.DROP
});

addInfoWindow(marker, message)
}

// function to add info window for markers
function addInfoWindow(marker, message) {
var cinfoWindow = new google.maps.InfoWindow();
var chtml = message;

google.maps.event.addListener(marker, ‘click’, function() {
cinfoWindow.setContent(chtml);
cinfoWindow.open(mymap, marker);
});
}

// function to drop marker at currentlocation
function CurrentLocation() {
Marker1=new google.maps.LatLng(clat, clng); addMarker(Marker1, “Current Location”);
}

The complete code for this app is available at the following github repository.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s