A Thought on HTML5 Geolocation

If you want to recognize user’s location, the Geolocation API of HTML5 helps to provide location based information or route navigation details of the user.

A Thought on HTML5 Geolocation

Different techniques are available for identifying the user’s location. Generally, WIFI or IP based positioning techniques are used by a desktop browser while GPS, A-GPS, WIFI based positioning techniques are used by mobile browsers.

For identifying the user’s exact location, the Geolocation API will use only one of above mentioned techniques. The user’s privacy is protected by the Geolocation API by authorizing that the user permission should be wanted and got before sending the location information of the user to any other website. So, it is recommended to users to prompt by popping over or dialoging requirements for the user’s permission to share location details. It is totally up to user to deny or accept the request.

Firstly, let’s understand the API and plot of the exact location in the Google Maps. In the first step, you have to check compatibility with the browser using any of the APIs in HTML5.

Checking Browser Compatibility

With the help of geolocation property of the global navigator object, one can easily detect the browser sipper for Geolocation API.

if (navigator.geolocation) {
    // Get the user's current position
} else {
    alert('Geolocation is not supported in your browser');
}

Get the User’s Current Location

Get the user’s current location with the getCurrentPosition function of the navigator.geolocation object. Three parameters are accepted by this function, i.e. position options, Success callback function and Error callback function.

The success callback function will be raised with the obtained position object as its input parameter, if location data is brought successfully. Otherwise, it will be raised with the error object as its input parameter.

if (navigator.geolocation) {

// Get the user's current position
navigator.geolocation.getCurrentPosition(showPosition, showError, optn);
} else {
    alert('Geolocation is not supported in your browser');
}

Success Callback Function

One can only see the raise of callback function when users allow sharing the location details and browser successfully fetches the location data. One can get location details as a position object and the function will be called the position object as its input parameter.

A timestamp property is included in a position object that indicates the time of the location data is retrieved and a coords object. One can find the following properties in cords object such as:

  • Altitude: it indicates the height of the position above the sea level in meters
  • Heading – it gives 360 degree heading information
  • Speed – it denotes relative speed in meters per second
  • Latitude, longitude – it gives details of geographic coordinates in decimal degrees
  • Accuracy- it provides information about Accuracy level of the latitude and longitude in meters. Smaller the number higher is the accuracy.
  • AltitudeAccuracy- it simply provides information of the distance of the altitude position from the actual attitude value obtained in meters. Smaller the number higher is the accuracy.
function showPosition(position) {
document.write('Latitude: '+position.coords.latitude+'Longitude: '+position.coords.longitude);
}

Error Callback Function

Error callback function is an alternative function that takes a ‘Position Error’ object takes a ‘Position Error’ object. This function rose because of any one of the following circumstances

  • Request timed out
  • Unknown Error occurred
  • Location information itself is unavailable
  • User has denied to share the location information
function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            alert("User denied the request for Geolocation.");
            break;
        case error.POSITION_UNAVAILABLE:
            alert("Location information is unavailable.");
            break;
        case error.TIMEOUT:
            alert("The request to get user location timed out.");
            break;
        case error.UNKNOWN_ERROR:
            alert("An unknown error occurred.");
            break;
    }
}

Position Options

It gives information about the choices available while retrieving the user’s location.

Timeout: It gives information about the maximum time (in milliseconds) that user agent can take to respond with the location data. Default value is Infinity.

enableHighAccuracy: This gives exact information of the most accurate position that result into slower response time and more power consumption. If it is false, it shows less accurate position.

maximumAge: With this, the user agent can simply know about the cached location data before trying to get latest location data. With zero value, one can simply now that the user agent must use the cached location data and infinity value denotes the cached location data must be used by the user agent.

if (navigator.geolocation) {
var optn = {
	enableHighAccuracy : true,
	timeout : Infinity,
	maximumAge : 0
	};
		navigator.geolocation.getCurrentPosition(showPosition, showError, optn);
} else {
	alert('Geolocation is not supported in your browser');
}

Track Location Changes

If you want to get the location data, the watchPosition() can be used. As and when the device or the useragent position changes, the success callback function is invoked repeatedly. One can find the parameter to this function as same as the getCurrentPosition() function. A watch ID value is returned by it that can be used to unregister the success callback function by passing it to the clearWatch() function.

function startWatch(){
if (navigator.geolocation) {
	var optn = {
	enableHighAccuracy : true,
	timeout : Infinity,
	maximumAge : 0
	};
watchId = navigator.geolocation.watchPosition(showPosition, showError, optn);
} else {
	alert('Geolocation is not supported in your browser');
}
}
function stopWatch() {
.   if (watchId) {
	navigator.geolocation.clearWatch(watchId);
	watchId = null;
	}
}

Show My Location on Google Maps

Google Maps API along with Geolocation API is used for plotting the location on Google Maps. Firstly, the latitude and longitude coordinates of the position object are converted to attain using the Geolocation API into a Google maps latLng object.

var googlePos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); 

Now, create a Map object to specify the map display options and the HTML div container, where the map should be showed. Below given are three map display options:

  • mapTypeId – shows Roadmap, Satellite or Hybrid
  • Zoom – indicates the zoom level
  • Center – Specifies that the map should be centered at the user location
var mapOptions = {
	zoom : 12,
	center : googlePos,
	mapTypeId : google.maps.MapTypeId.ROADMAP
		};
var mapObj = document.getElementById('mapTxt');
var googleMap = new google.maps.Map(mapObj, mapOptions);

Now, develop a marker at the location as given below

var markerOpt = {
	map : googleMap,
	position : googlePos,
	title : 'Hi , I am here',
	animation : google.maps.Animation.DROP
	};
var googleMarker = new google.maps.Marker(markerOpt);
One can simply see the following things in above code marker options:

Title – It displays when you hover on the marker

Map – it can be seen where the marker should appear

Position- it is latlng position, where marker should be showed.

It is recommended to use the reverse geocoding API to find the address of your location and displayed the address obtained when you click on the marker.

var geocoder = new google.maps.Geocoder();
	geocoder.geocode({
	latLng' : googlePos
	}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
	if (results[1]) {
	var popOpts = {
	content : results[1].formatted_address,
	position : googlePos
	};
var popup = new google.maps.InfoWindow(popOpts);
		google.maps.event.addListener(googleMarker, 'click', function() {
		popup.open(googleMap);
	});
	} else {
	alert('No results found');
	}
	} else {
	alert('Geocoder failed due to: ' + status);
	}
});

If you want to add some excellent features, start surfing Google maps API. You can also take help of HTML5 developers for adopting Geolocation service.

Like it? Share it.

2 Comments

Leave a Comment Yourself

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>