HTML5 Geolocation
There are 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 cell triangulation, GPS, A-GPS, WIFI based positioning techniques, etc. The Geolocation API will use any one of these techniques to identify the user’s location.
The Geolocation API protects the user’s privacy by mandating 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 popover or dialog requesting for the user’s permission to share the location information. The user can accept or deny the request.
Now let us first understand the API and then plot your location in the Google Maps.
The first step in using any of the APIs in HTML5 is to check for its compatibility with the browser.
Check for Browser compatibility
The geolocation property of the global navigator object helps in detecting the browser support for the Geolocation API.
1
2
3
4
5
|
if (navigator.geolocation) { // Get the user's current position } else { alert('Geolocation is not supported in your browser'); } |
Get the user’s current location
The current location of the user can be obtained using the getCurrentPosition
function of the navigator.geolocation
object. This function accepts three parameters – Success callback function, Error callback function and position options. If the location data is fetched successfully, the success callback function will be invoked with the obtained position
object as its input parameter. Otherwise, the error callback function will be invoked with the error
object as its input parameter.
1
2
3
4
5
6
7
|
if (navigator.geolocation) { // Get the user's current position navigator.geolocation.getCurrentPosition(showPosition, showError, optn); } else { alert('Geolocation is not supported in your browser'); } |
- Success callback function
This callback function is invoked only when the user accepts to share the location information and the location data is successfully fetched by the browser. The location data will be available as a position object and the function will be called with the position object as its input parameter. A position object contains atimestamp
property denoting the time at which the location data is retrieved and acoords
object.Thecoords
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
123function
showPosition(position) {
document.write(
'Latitude: '
+position.coords.latitude+
'Longitude: '
+position.coords.longitude);
}
- Error callback function
This is an optional callback function that takes a ‘Position Error’ object as its input parameter. This function is invoked under any one of the following circumstances- Unknown Error occurred
- Request timed out
- User has denied to share the location information
- Location information itself is unavailable
12345678910111213141516function
showError(error) {
switch
(error.code) {
case
error.PERMISSION_DENIED:
alert(
"User denied the request for Geolocation."
);
break
;
case
error.POSITION_UNAVAILABLE:
alert(
"Location information is unavailable."
);
break
;
case
error.TIMEOUT:
alert(
"The request to get user location timed out."
);
break
;
case
error.UNKNOWN_ERROR:
alert(
"An unknown error occurred."
);
break
;
}
}
- Position OptionsIt describes the options to use while retrieving the user’s location.
- enableHighAccuracy: 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.
- 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 infinity value indicates that the cached location data must be used by the user agent.
12345678910if
(navigator.geolocation) {
var
optn = {
enableHighAccuracy :
true
,
timeout : Infinity,
maximumAge : 0
};
navigator.geolocation.getCurrentPosition(showPosition, showError, optn);
}
else
{
alert(
'Geolocation is not supported in your browser'
);
}
Track Location changes
The watchPosition()
can be used to get the location data at regular intervals. The success callback function is invoked automatically as and when the device or the useragent position changes. The parameters to this function is similar to the getCurrentPosition()
function. It returns a watch ID
value which can be used to unregister the success callback function by passing it to the clearWatch()
function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
function startWatch(){ 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 stopWatch() { . if (watchId) { navigator.geolocation.clearWatch(watchId); watchId = null ; } } |
Show My Location on Google Maps
In order to plot your location on Google Maps we can make use of Google Maps API along with Geolocation API.
- First of all, we should convert the latitude and longitude coordinates of the position object obtained using the Geolocation API into a Google maps
latLng
object.1var
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 below three map display options are specified
- Zoom – Specifies the zoom level
- Center – Specifies that the map should be centered at the user location
- mapTypeId – Can be Roadmap, Satellite or Hybrid
1234567var
mapOptions = {
zoom : 12,
center : googlePos,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
var
mapObj = document.getElementById(
'mapTxt'
);
var
googleMap =
new
google.maps.Map(mapObj, mapOptions);
- Create a marker at the location as given below
1234567
var
markerOpt = {
map : googleMap,
position : googlePos,
title :
'Hi , I am here'
,
animation : google.maps.Animation.DROP
};
var
googleMarker =
new
google.maps.Marker(markerOpt);
In the above code marker options indicate the following
- 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.
123456789101112131415161718192021
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);
}
});
Sample Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
<!DOCTYPE html> < html > < head > < title >Sample Map</ title > < style > #mapdiv { margin: 0; padding: 0; width: 500px; height: 500px; } </ style > < 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 > |
Conclusion
Start exploring Google maps API and see what more features you can build on top of the sample given above.
Source Link: http://www.sitepoint.com/html5-geolocation/