Geolocation is the creativity of reckoning out where you are in the world & sharing information, for that HTML5 helps in identifying the user’s location, which can be used to provide location specific information or route navigation details to the user.
Among many techniques used to identify the location of the user, a desktop browser generally uses WIFI or IP based positioning techniques whereas a mobile browser uses GPS, cell triangulation, WIFI based positioning techniques, etc. The Geolocation API will use any one of these techniques to identify the user’s location.
The Geolocation protects the user’s privacy by authorizing that the user permission should be sought and obtained before sending the location information of the user to any website. So the user will be prompted with a request for the user’s permission to share the location information.
Set Geo location lat and long :
Bellow example is returning the latitude and longitude of the user’s current position which is obtained using the getCurrentPosition function of the navigator.geolocation object.
navigator.geolocation.getCurrentPosition(function(position, html5Error) { geo_loc = processGeolocationResult(position); currLatLong = geo_loc.split(“,”); initializeCurrent(currLatLong[0], currLatLong[1]); });
The coords object has the following properties:
- Latitude, longitude– Geographic coordinates in decimal degrees
- Accuracy– Accuracy level of the latitude and longitude coordinates in meters. Bigger the number lesser is the accuracy
- Altitude– Height of the position above the sea level in meters
- AltitudeAccuracy– Denotes how far off the altitude position could be from the actual attitude value obtained in meters. Bigger the number lesser is the accuracy
- Heading– Provides 360 degree heading information
- Speed– Indicates relative speed in meters per second
Get geo location result:
In Bellow example;
position.coords.latitude & position.coords.longitude returned latitude and longitude data to show the location.
A position object contains a timestamp property denoting the time at which the location data is retrieved and a coords object. position.timestamp gives the date/time of the response. position.coords.accuracy returns the accuracy of the user’s position.
function processGeolocationResult(position) { html5Lat = position.coords.latitude; html5Lon = position.coords.longitude; html5TimeStamp = position.timestamp; html5Accuracy = position.coords.accuracy; return (html5Lat).toFixed(8) + “, ” + (html5Lon).toFixed(8); }
You can also Use:
- Enable High Accuracy: Boolean. If true, the user agent will try to provide the most accurate position. This can result in slower response time and higher power consumption. Is false, less accurate position will be obtained. Default value is false.
- Timeout: Positive long value. It denotes the maximum time in milliseconds that the user agent can take to respond with the location data. Default value is Infinity.
- maximum Age: Positive long value. It denotes how long in milliseconds the user agent can keep using the cached location data before trying to obtain new location data. A zero value indicates that the user agent must not use the cached location data and infinity value indicates that the cached location data must be used by the user agent.
Check value is present or not & call google API function:
In order to figure out location we have used of Google Maps API along with Geolocation API. here we convert the latitude and longitude coordinates of the position object obtained using the Geolocation API
function initializeCurrent(latcurr, longcurr) { currgeocoder = new google.maps.Geocoder(); console.log(latcurr + “– ######## –” + longcurr); if (latcurr != ” && longcurr != ”) { var myLatlng = new google.maps.LatLng(latcurr, longcurr); return getCurrentAddress(myLatlng); } }
Get current address:
The address locator funcntion is the major component in the geocoding process. It is created based on a specific address locator style. The address locator also contains a set of address parsing and matching rules that directs the geocoding engine to perform address standardization and matching.
The purpose is to find all the possible matching address. Once possible address are identified, each individual variable in the address is compared with each corresponding address element. A score is generated indicating how well the address is matched. Finally, the address locator presents the best matches based on the score and the location of the address being matched.
Via google.maps.Geocoder object you access the Google Maps API geocoding service within your code and the Geocoder.geocode() method initiates a request.
We geocode an address and place a marker at the returned latitude and longitude values Here, google.maps.GeocoderStatus.OK indicastes that the geocode was successful
function getCurrentAddress(location) { currgeocoder.geocode({ ‘location’: location }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { console.log(results[0]); $(“#address”).html(results[0].formatted_address); } else { alert(‘Geocode was not successful for the following reason: ‘ + status); } }); }
Complete Sample Code:
<!DOCTYPE html> <html> <head> <script type=”text/javascript” src=”http://code.jquery.com/jquery-latest.min.js“></script> <script src=”https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true“></script> </head> <body> <p>Address: <div id=”address”></div></p> </body> <script type=”text/javascript” charset=”utf-8″> $(document).ready(function() { var currgeocoder; //Set geo location lat and long navigator.geolocation.getCurrentPosition(function(position, html5Error) { geo_loc = processGeolocationResult(position); currLatLong = geo_loc.split(“,”); initializeCurrent(currLatLong[0], currLatLong[1]); }); //Get geo location result function processGeolocationResult(position) { html5Lat = position.coords.latitude; //Get latitude html5Lon = position.coords.longitude; //Get longitude html5TimeStamp = position.timestamp; //Get timestamp html5Accuracy = position.coords.accuracy; //Get accuracy in meters return (html5Lat).toFixed(8) + “, ” + (html5Lon).toFixed(8); } //Check value is present or not & call google api function function initializeCurrent(latcurr, longcurr) { currgeocoder = new google.maps.Geocoder(); console.log(latcurr + “– ######## –” + longcurr); if (latcurr != ” && longcurr != ”) { var myLatlng = new google.maps.LatLng(latcurr, longcurr); return getCurrentAddress(myLatlng); } } //Get current address function getCurrentAddress(location) { currgeocoder.geocode({ ‘location’: location }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { console.log(results[0]); $(“#address”).html(results[0].formatted_address); } else { alert(‘Geocode was not successful for the following reason: ‘ + status); } }); } }); </script> </html>
You can check Demo here:
http://jsfiddle.net/hmy7e0fs/
<Original Code written by – Prasanna Champanerkar, Developer, Cuelogic>
Related Reading
[wcp-carousel id=”10008″]