Get Current location using HTML5 GeoLocation API

HTML5 GeoLocation API
The Geolocation API provides a method to locate the user’s exact (more or less – see below) position. This is useful in a number of ways ranging from providing a user with location specific information to providing route navigation. For privacy reasons, the user is asked for permission to report location information.

DEMO

Browser compatibility

— Firefox 3.5+

— Internet Explorer 9+

— Chrome 9+

— Safari 5+

— Opera 10+

Functions used for location user

getCurrentPosition()

— Used to get current position of the device.

WatchPosition()

— This method will be called automatically each time the position of the device changes.

ClearWatch()

— This  method is used to unregister location/error monitoring handlers previously installed using navigator.geolocation.watchPosition()

Code to get user location using Geolocation API
 
var options = { 
     enableHighAccuracy: true, 
     timeout: 5000, 
     maximumAge: 0 
}; 
var success = function(position) { 
var loc = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); 
      marker = new google.maps.Marker({ 
      position: loc, 
      map: _this.map, 
      icon : ACC.config.commonResourcePath + "/images/map-logo.png", 
      title: "You are here" }); 
}; 
var error = function() { 
     output.innerHTML = "Unable to retrieve your location"; 
}; 
navigator.geolocation.getCurrentPosition(success, error, options); 
current_loca
Explanation
By using navigator.geolocation.getCurrentPosition function, we can retrive the user location. For privacy reasons, the user is asked for permission to report location information. This method has three parameters( Success, error, options).
Syntax is as follows

navigator.geolocation.getCurrentPosition(success[, error[, options]])

Parameters

success

A callback function that takes a Position object as input parameter. Using this object we can fetch the latitude and longtitude of the current device.

error (Optional)

An optional callback function that takes a PositionError object input parameter. Using this we can find reason of error.

CODE    REASON

   1         Permission Denied

   2         Position Unavailable

   3         Time Out

options (Optional)

Containing option properties to pass as a parameter for navigator.geolocation.getCurrentPosition() and navigator.geolocation.watchPosition() functions

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