Introduction
The HTML Geolocation API is used to locate a user's position. There are many techniques used to specify the location of a user. In a web browser, WIFI or IP address is used to identify the location and in mobile-based browsers WIFI, GPS or triangulation techniques are used to identify the location. Geolocation API uses any of these techniques. Geolocation API protects the user’s privacy by accepting the permission of a user before sending location information to any website.
In this article, we learn how to identify the user location and show it on a Google map.
Browser Support
The following table shows the first browser version that supports Geolocation.
Firstly, we create a Web page and paste the following code in that page.
Html Code
- <body>
- <dividdivid="div1"> <span>************HTML5 Geolocation*************</span> </div>
- <div>
- <inputtypeinputtype="button" id="btn" value="Show My Location" onclick="loadScript()" /> </div>
- <dividdivid="map">
- </div>
- </body>
Script
- <script>
- $(document).ready(function()
- {
- $("#btn").click(function()
- {
- if (navigator.geolocation)
- {
- varGeo_Options = {
- enableHighAccuracy: false,
- timeout: Infinity,
- maximumAge: 0
- }
- navigator.geolocation.getCurrentPosition(Success, Show_Error, Geo_Options)
- }
- else
- {
- alert("OOPS! Your Browser Doesn't Support GeoLocation \n" + "Please Update Your Browser")
- }
-
- function Success(position)
- {
- alert(" Show My Location \n" + "Latitude is " + position.coords.latitude + "\n Longitude is " + position.coords.longitude + "\n Accuracy is " + position.coords.accuracy + "\n Altitude is " + position.coords.altitude + "\n Altitude Accuracy is " + position.coords.altitudeAccuracy);
- varmapProp = {
- center: newgoogle.maps.LatLng(position.coords.latitude, position.coords.longitude),
- zoom: 13,
- mapTypeId: google.maps.MapTypeId.ROADMAP
- }
- var marker = newgoogle.maps.Marker(
- {
- position: newgoogle.maps.LatLng(position.coords.latitude, position.coords.longitude),
- title: 'Hello ! I am Here!'
- });
- var map = newgoogle.maps.Map(document.getElementById("map"), mapProp);
- marker.setMap(map);
- }
- functionShow_Error(error)
- {
- switch (error.code)
- {
- caseerror.PERMISSION_DENIED: alert("User denied the request");
- break;
- caseerror.POSITION_UNAVAILABLE: alert("Location information Not available.");
- break;
- caseerror.TIMEOUT: alert("Request time out");
- break;
- caseerror.UNKNOWN_ERROR: alert("Unknown error ");
- break;
- }
- };
- })
- });
- </script>
Now we divide the script in several sections and read about each section separately.
Check Browser Compatibility
- if (navigator.geolocation)
- {
-
- }
- else
- {
- alert("OOPS! Your Browser Doesn't Support GeoLocation \n" + "Please Update Your Browser")
- }
The geolocation property of the navigator object is used to check the compatibility of browsers for geolocation API.
Get a User’s Location
- navigator.geolocation.getCurrentPosition(Success, Show_Error, Geo_Options)
The getCurrentPosition method of navigator.geolocation object gets the current location of the user. This method takes three parameters (success callback method, error callback method and position option). The description of each parameter is described below.
Success Callback Method
In the above code “Success” is called when we user accepts the request for share location. The callback method contain a position object. This position object contains information about the user’s location. This position parameter contains the following information:
- Timestamp: Denote the time at which location is captured.
- Coords object: Contain information about the location. The cords object contains the following information about the location of the object.
Property |
Description |
latitude, longitude |
Geographic coordinates in decimal degrees |
Accuracy |
The accuracy level of coordinates |
Speed |
Indicates relative speed in meters per second |
Heading |
Provides 360-degree heading information |
Altitude |
Height of the position above the sea level in meters |
AltitudeAccuracy |
Accuracy of actual attitude value obtained in meters. Big the number lesser is the accuracy |
When success method call it will show the information about user location,
- function Success(position) {
-
- alert(" Show My Location \n" +
- "Latitude is " + position.coords.latitude +
- "\n Longitude is " + position.coords.longitude +
- "\n Accuracy is " + position.coords.accuracy +
- "\n Altitude is " + position.coords.altitude +
- "\n Altitude Accuracy is " + position.coords.altitudeAccuracy);
- }
Output
Error Callback Method
- functionShow_Error(error)
- {
- switch (error.code)
- {
- caseerror.PERMISSION_DENIED: alert("User denied the request");
- break;
- caseerror.POSITION_UNAVAILABLE: alert("Location information Not available.");
- break;
- caseerror.TIMEOUT: alert("Request time out");
- break;
- caseerror.UNKNOWN_ERROR: alert("Unknown error ");
- break;
- }
- };
The error callback method is called when a position error occurs. This error may be occurred due to any reason (request denied by the user, request timeout, a position not available or due to any other reason).
Position Option
The position option parameter provides some options during the retrieval of location information. This parameter contains the following options.
- varGeo_Options = {
- enableHighAccuracy: false,
- timeout: Infinity,
- maximumAge: 0
- }
Option |
Description |
enableHighAccuracy |
If the value is true then the browser provides a more most accurate position. But it slows the process. The default value is false |
Timeout |
Maximum Time in milliseconds that a user agent can take to retrieve the location of the user. |
maximumAge |
It denotes how long time ( milliseconds) the user agent can take using the cached location data before trying to obtain new location data. Zero means the user agent doesn’t use cached location and infinity means the user agent used cached location for a long time. |
Show the location of the user on Google Maps.
- varmapProp = {
- center: newgoogle.maps.LatLng(position.coords.latitude, position.coords.longitude),
- zoom: 13,
- mapTypeId: google.maps.MapTypeId.ROADMAP
- }
- var marker = newgoogle.maps.Marker(
- {
- position: newgoogle.maps.LatLng(position.coords.latitude, position.coords.longitude),
- title: 'Hello ! I am Here!'
- });
- var map = newgoogle.maps.Map(document.getElementById("map"), mapProp);
- marker.setMap(map);
Using the above code we create a Google Map object and define the center of google Maps using latitude and longitude retrieved from geolocation API. We also create a marker and maintain the property of marker and at last, we assign this marker to map object.
So when we run this program in a web browser we get the current location of the current location in Google Map.
Complete code
- <htmlxmlns="http://www.w3.org/1999/xhtml">
- <headrunat="server">
- <title></title>
- <scriptsrc="jquery-ui-1.11.4.custom/jquery-ui-1.11.4.custom/external/jquery/jquery.js">
- </script>
- <!--Goolge API-->
- <scriptsrc="http://maps.googleapis.com/maps/api/js">
- </script>
- </head>
- <script>
- $(document).ready(function()
- {
- $("#btn").click(function()
- {
- if (navigator.geolocation)
- {
- varGeo_Options = {
- enableHighAccuracy: false,
- timeout: Infinity,
- maximumAge: 0
- }
- navigator.geolocation.getCurrentPosition(Success, Show_Error, Geo_Options)
- }
- else
- {
- alert("OOPS! Your Browser Doesn't Support GeoLocation \n" + "Please Update Your Browser")
- }
-
- function Success(position)
- {
- alert(" Show My Location \n" + "Latitude is " + position.coords.latitude + "\n Longitude is " + position.coords.longitude + "\n Accuracy is " + position.coords.accuracy + "\n Altitude is " + position.coords.altitude + "\n Altitude Accuracy is " + position.coords.altitudeAccuracy);
- varmapProp = {
- center: newgoogle.maps.LatLng(position.coords.latitude, position.coords.longitude),
- zoom: 13,
- mapTypeId: google.maps.MapTypeId.ROADMAP
- }
- var marker = newgoogle.maps.Marker(
- {
- position: newgoogle.maps.LatLng(position.coords.latitude, position.coords.longitude),
- title: 'Hello ! I am Here!'
- });
- var map = newgoogle.maps.Map(document.getElementById("map"), mapProp);
- marker.setMap(map);
- }
- functionShow_Error(error)
- {
- switch (error.code)
- {
- caseerror.PERMISSION_DENIED: alert("User denied the request");
- break;
- caseerror.POSITION_UNAVAILABLE: alert("Location information Not available.");
- break;
- caseerror.TIMEOUT: alert("Request time out");
- break;
- caseerror.UNKNOWN_ERROR: alert("Unknown error ");
- break;
- }
- };
- })
- });
- </script>
- <style>
- #div1 {
- background-color: coral;
- color: ButtonHighlight;
- font-size: 30px;
- height: 80px;
- width: 1000px;
- text-align: center;
- margin-left: 150px
- }
-
- #map {
- height: 700px;
- width: 1000px;
- text-align: center;
- margin-left: 150px;
- margin-top: 10px
- }
-
- #btn {
- color: chocolate;
- background-color: aquamarine;
- font-size: 26px;
- margin-left: 550px;
- margin-top: 10px
- }
- </style>
-
- <body>
- <divid="div1"> <span>************HTML5 Geolocation*************</span> </div>
- <div>
- <inputtype="button" id="btn" value="Show My Location" onclick="loadScript()" />
- </div>
- <divid="map">
- </div>
- </body>
-
- </html>
Summary
In this article, we learned about HTML5 Geolocation.
Thanks for reading the article.