The HTML Geolocation API is used to locate a user's position. There are many technique used to specify the location of a user. In web browser, WIFI or IP address are used to identify the location and in mobile based browsers WIFI, GPS or triangulation techniques are used to identify the location. Gelocation API use any of these techniques. Geolocation API protect 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 in a Google map.
Browser Support:
The following table show the first browser version that supports the Geolocation.
Firstly, we create a Web page and paste the following code in that page.
Html Code
- <body>
- <divid="div1"> <span>************HTML5 Geolocation*************</span> </div>
- <div>
- <inputtype="button" id="btn" value="Show My Location" onclick="loadScript()" /> </div>
- <divid="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 section 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 navigator object is used to check the compatibility of browsers for geolocation API.
Get User’s Location navigator.geolocation.getCurrentPosition(Success, Show_Error, Geo_Options) The getCurrentPosition method of navigator.geolocation object get the current location of user. This method takes three parameters (success callback method, error callback method and position option). Description of each parameter is described below.
Success Callback Method In above code “Success” is called when we user accept the request for share location. Callback method contain a position object. This position object contain information about the user’s location. This position parameter contain the following information:
- Timestamp: Denote the time at which location is captured.
- Coords object: Contain information about location. The cords object contain the following information about the location of object.
Property | Description |
latitude, longitude | Geographic coordinates in decimal degrees |
Accuracy | 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;
- }
- };
Error callback method is called when a position error is occurred. This error may be occurred due to any reason (request denied by user, request timeout, position not available or due to any other reason).
Position Option
Position option parameter provide some option during retrieval of location information. This parameter contains the following options.
- varGeo_Options = {
- enableHighAccuracy: false,
- timeout: Infinity,
- maximumAge: 0
- }
Option | Description |
enableHighAccuracy | If value is true then browser provide more most accurate position. But it slow the process. Default value is false |
Timeout | Maximum Time in milliseconds that a user agent can take to retrieve location of user. |
maximumAge | It denotes that how long time ( milliseconds) the user agent can take using the cached location data before trying to obtain new location data. Zero means user agent doesn’t use cached location and infinity means user agent used cached location for a long time. |
Show location of user in Google Map:
- 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 above code we create a Google Map object and define the center of google map 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 web browser we get the current location of 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>
Thanks for reading the article.