HTML5 Geolocation API

HTML5 Geolocation is an API Object that you can use to find current location/position of user. HTML5 Geolocation API is a beautiful feature of HTML5. You can use this API to display web page customized result based on user's location.

The Geolocation API lets you share your location with trusted web sites. Geolocation API comes with wide range of properties and methods that help you to get latitude and longitude in Javascript code.

Google map API can use these latitude and longitude and display popup message or display pin up on that particular location. In a nutshell, Geolocation allows you to give your current location information to the browser.

Syntax

var position = navigator.geolocation;
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;

Browser Support

Almost all latest browsers like Safari, Google Chrome, Mozilla Firefox, Opera, Internet Explorer 9.0 support many HTML5 features and functionalities. The good thing is that now many mobiles web browsers like iPhones, iPads, and Android phones all have excellent support for HTML5.

Below are the properties of HTML5 Geolocation API.

PropertiesTypeDescriptions
coordsobjectThis object is intended to get latitude and longitude of current position.
coords.latitudedoubleThis property is intended to get latitude of current position.
coords.longitudedoubleThis property is intended to get longitude of current position.
coords.altitudedoubleThis property is intended to get altitude in meters from sea level.
coords.accuracydoubleThis property is intended to get accurate position.
coords.altitudeAccuracydoubleThis property is intended to get altitude accuracy of position.
coords.headingdoubleThis property is intended to get degrees clockwise from North.
coords.speeddoubleThis property is intended to get speed in meters per second.
timestampDOMTimeStampThis property is intended to get response date/time.

Below are the Methods of HTML5 Geolocation API.

MethodsDescriptions
getCurrentPositionThis method is intended to get current position of device.
watchPositionThis method is intended to register a handler function and to get change position of the device.
clearWatchThis method is intended to unregister a handler function.

Example

<!DOCTYPE html>
<html>
  <head> <!-- www.techstrikers.com -->
    <title>Geolocation</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
    <script>
var map;

function initialize() {
  var mapOptions = {
    zoom: 12
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);
  // Try HTML5 geolocation
  if(navigator.geolocation) {
   
    navigator.geolocation.getCurrentPosition(function(position) {
        var latitude = position.coords.latitude;  
        var longitude = position.coords.longitude; 
      
      var pos = new google.maps.LatLng(latitude,longitude);

      var infowindow = new google.maps.InfoWindow({
        map: map,
        position: pos,
        content: 'Your current location using HTML5.'
      });

      map.setCenter(pos);
    }, function() {
      
    });
  } else {
    alert("Browser doesn't support Geolocation");
  }
}
google.maps.event.addDomListener(window, 'load', initialize);

</script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html>
Try Now

Below are the Error code of HTML5 Geolocation API

To handle error in HTML5 Geolocation, getCurrentPosition() method accepts second parameter as function to handle errors. This specified function runs if it fails to get the user's location.

CodeConstantDescriptions
0UNKNOWN_ERRORFails if any unknown error occure.
1PERMISSION_DENIEDIf denies you access to the location.
2POSITION_UNAVAILABLEIf position are not detected.
3TIMEOUTFails if gets position info in maximum time.

Example

navigator.geolocation.getCurrentPosition(function(position) {
      var pos = new google.maps.LatLng(position.coords.latitude,
                                       position.coords.longitude);

    }, function() {
      ErrorOccure(error);
    });
  } else {
    // Browser doesn't support Geolocation
    ErrorOccure(error);
}

function ErrorOccure(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            alert("Permission Denied.");
            break;
        case error.POSITION_UNAVAILABLE:
            alert("Position Unavailable.")
            break;
        case error.TIMEOUT:
            alert("Timed Out.")
            break;
        case error.UNKNOWN_ERROR:
            alert("An unknown error occurred.")
            break;
    }
}

See Also

HTML5 Web Storage
HTML5 Audio Tag
HTML5 Video Tag
HTML5 Canvas
HTML5 SVG Tag


 
 
SHARE THIS IF YOU LIKE!
submit to reddit

SUBSCRIBE FOR LATEST UPDATES
HAVE WE CONNECTED ON FACEBOOK?
TOP TUTORIALSTOP CODE EXAMPLESTOP LIVE DEMOLINKSSTAY CONNECTED
HTML Tutorial
HTML5 Tutorial
Bootstrap3 Tutorial
Javascript Tutorial
TypeScript Tutorial
AngularJS Tutorial
CSharp Tutorial
PHP Tutorial
Developer Tools
Javascript
AngularJS
Google MAP API V3
ASP.NET
Javascript
AngularJS
Google MAP API V3
Contact Us
Advertise with Us
Privacy Policy
Disclaimer
Stay connected. We actually like you. If you want to get up to the minute updates, then connect with us on your fav below.
 
Twitter   Linkedin   Facebook   Google+    RSS   Pinterest
 
Protected by Copyscape Original Content Checker
 
 
Copyright ©2017 www.techstrikers.com Unauthorized reproduction/replication of any part of this site is prohibited.