Understand term Geolocation

Geolocation Object
Browser Compatibility
- If (navigator.geolocation)
- {
- //Get the user’s current position
- }
- Else
- {
- Alert (‘Geolocation is not supported in your browser’);
- }
Geolocation Methods
Properties of Position object
| Property | Value | Unit |
| Coords.latitude | Double | degrees |
| Coords.langitude | Double | degrees |
| Coords.altitude | Double or null | meters |
| Coords.accuracy | Double | meters |
| Coords.altitudeAccuracy | Double or null | meters |
| Coords.heading | Double or null | Degrees clockwise |
| Coords.speed | Double or null | Meters/second |
| timeStamp | DOMTimeStamp | Like the Date object |
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. Less accuracy when the number is big.
- 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. The larger the number the lesser the accuracy.
- Heading: Provides 360 degree heading information
- Speed: Indicates relative speed in Meters Per Second.
Syntax of getCurrentPosition ( ) method
getCurrentPosition (showLocation, ErrorHandler, options);
Let define parameters of getCurrentPosition
showLocation: This specifies the callback method that retrieves the location information. This method is called asynchronously with an object corresponding to the Position object that stores the returned location information.
ErrorHandler: This optional parameter specifies the callback method that is invoked when an error occurs in processing the asynchronous call. This method is called with the Position Error object that stores the returned error information.
Options: This optional parameter specifies a set of options for retrieving the location information. We can specify:
- Accuracy of the returned location information
- Timeout for retrieving the location information
- Use of cached location information.
CodeWhen you write, save and open this web page in your browser, it gives output like this;- <!DOCTYPE HTML>
- <head>
- <script type="text/JavaScript">
- function showLocation(position) {
- var latitude = position.coords.latitude;
- var longitude = position.coords.longitude;
- alert("Latitude : " + latitude + " Longitude: " + longitude);
- }
- function errorHandler(err) {
- if (err.code == 1) {
- alert("Error: Access is denied!");
- }
- else if (err.code == 2) {
- alert("Error: Position is unavailable!");
- }
- }
- function getLocation() {
- if (navigator.geolocation) {
- var options = { timeout: 60000 };
- navigator.geolocation.getCurrentPosition(showLocation, errorHandler,
- options);
- }
- Else
- {
- alert("Geolocation is not supported by browser");
- }
- }
- </script>
- </head>
- <html>
- <body>
- <form>
- <input type="button" onclick="getLocation();" value="Get Location"/>
- </form>
- </body>
- </html>

watchPosition: This method retrieves your current location periodically. The location information is returned in a Position object. Each update returns a new Position object. The watchPosition method returns a unique transaction ID (number) associated with the asynchronous call. Use this ID to cancel the watchPosition call and to stop receiving location updates.
Syntax
watchPosition(showLocation, ErrorHandler, options);
Code
- <!DOCTYPE HTML>
- <head>
- <script type="text/JavaScript">
- var watchID;
- var geoLoc;
- function showLocation(position) {
- var latitude = position.coords.latitude;
- var longitude = position.coords.longitude;
- alert("Latitude : " + latitude + " Longitude: " + longitude);
- }
- function errorHandler(err) {
- if (err.code == 1) {
- alert("Error: Access is denied!");
- }
- else if (err.code == 2) {
- alert("Error: Position is unavailable!");
- }
- }
- function getLocationUpdate() {
- if (navigator.geolocation) {
- var options = { timeout: 60000 };
- geoLoc = navigator.geolocation;
- watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
- }
- else {
- alert("Geolocation is not supported by browser!");
- }
- }
- </script>
- </head>
- <html>
- <body>
- <form>
- <input type="button" onclick="getLocationUpdate();"value="Watch Update"/>
- </form>
- </body>
- </html>

- <!DOCTYPE HTML><head><script type="text/javascript">var watchID;
- var geoLoc;
- function showLocation(position) {
- var latitude=position.coords.latitude;
- var longitude=position.coords.longitude;
- alert("Latitude : " + latitude + " Longitude: " + longitude);
- }
- function errorHandler(err) {
- if (err.code==1) {
- alert("Error: Access is denied!");
- }
- else if (err.code==2) {
- alert("Error: Position is unavailable!");
- }
- }
- function getLocationUpdate() {
- if (navigator.geolocation) {
- // timeout at 60000 milliseconds (60 seconds)
- var options= {
- timeout: 60000
- }
- ;
- geoLoc=navigator.geolocation;
- watchID=geoLoc.watchPosition(showLocation, errorHandler, options);
- }
- else {
- alert("Geolocation is not supported by your browser!");
- }
- }
- function stopWatch() {
- geoLoc.clearWatch(watchID);
- }
- </script></head>
- <html>
- <body>
- <form><input type="button" onclick="getLocationUpdate();" value="Watch Update"/><input type="button" onclick="stopWatch();" value="Stop Watch"/></form>
- </body>
- </html>

Error Callback Function ( )
- enableHighAccuracy: Boolean. If true, the user agent will try to provide the most accurate position. This can result in a slower response time and higher power consumption. If false then a less accurate position will be obtained. The 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. The default value is Infinity.
- maximumAge: 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 the infinity value indicates that the cached location data must be used by the user agent.
Use Google Maps
To plot our location on Google Maps we use the Google Maps API. The following explains all points step-by-step.
- Convert the latitude and longitude coordinates of the position object obtained using the Geolocation API into a Google maps latLng object.
var googlePos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
- Create a Map object specifying the map display options and the HTML div container where the map should be displayed. In the example we define the following three map options:
- Zoom: Specifies the zoom level
- Center: Specifies that the map should be centered at the user location
- mapTypeId: Can be Roadmap, Satellite or Hybrid
- 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 we create a marker at the location as in the following:
The Code marker options indicate the following three important points:
- var markerOpt = {
- map : googleMap,
- position : googlePos,
- title : 'Hi , I am here',
- animation : google.maps.Animation.DROP
- };
- var googleMarker = new google.maps.Marker(markerOpt);
- Map: Map object where the marker should appear
- Position: latlng position at which the marker should be displayed
- Title: Title that should appear when we hover on the marker
- Find the address of your location using the reverse geocoding API and show the address obtained when you click on the marker.
Now for the entire sample code:
- 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);
- }
- });
Result- <!DOCTYPE html>
- <html>
- <head>
- <title>Sample Map</title>
- <style>
- #mapdiv {
- margin: 0;
- padding: 0;
- width: 500px;
- height: 500px;
- }
- </style>
- <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
- <script>
- var watchId = null;
- function geoloc() {
- 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 showPosition(position) {
- var googlePos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
- var mapOptions = {
- zoom: 12,
- center: googlePos,
- mapTypeId: google.maps.MapTypeId.ROADMAP
- };
- var mapObj = document.getElementById('mapdiv');
- var googleMap = new google.maps.Map(mapObj, mapOptions);
- var markerOpt = {
- map: googleMap,
- position: googlePos,
- title: 'Hi , I am here',
- animation: google.maps.Animation.DROP
- };
- var googleMarker = new google.maps.Marker(markerOpt);
- 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);
- }
- });
- }
- function stopWatch() {
- if (watchId) {
- navigator.geolocation.clearWatch(watchId);
- watchId = null;
- }
- }
- function showError(error) {
- var err = document.getElementById('mapdiv');
- switch (error.code) {
- case error.PERMISSION_DENIED:
- err.innerHTML = "User denied the request for Geolocation."
- break;
- case error.POSITION_UNAVAILABLE:
- err.innerHTML = "Location information is unavailable."
- break;
- case error.TIMEOUT:
- err.innerHTML = "The request to get user location timed out."
- break;
- case error.UNKNOWN_ERROR:
- err.innerHTML = "An unknown error occurred."
- break;
- }
- }
- </script>
- </head>
- <body onload="geoloc()">
- <p id = 'mapdiv'></p>
- <button onclick="stopWatch()">
- Stop
- </button>
- </body>
- </html>


Abhishek JaiswalPosted Jan 29, 2014, 7:47 AM
nice work ...!