Using HTML 5 GeoLocation Feature




Have you ever experienced the following prompt when you navigate to particular web sites?
Html5_GeoLocation_watchPosition_1This is HTML 5 feature which can get the browsers/client location. Following code snippet shows how to do it.
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
window.onload = function() {
 
// Check to see if the browser supports the GeoLocation API.
 if (navigator.geolocation) {
 // Get the location
 navigator.geolocation.getCurrentPosition(function(position) {
 var lat = position.coords.latitude;
 var lon = position.coords.longitude;
 
// Show the map
 showMap(lat, lon);
 });
 } else {
 // Print out a message to the user.
 document.write('Your browser does not support GeoLocation :(');
 }
 
}
 
// Show the user's position on a Google map.
function showMap(lat, lon) {
 // Create a LatLng object with the GPS coordinates.
 var myLatLng = new google.maps.LatLng(lat, lon);
 
// Create the Map Options
 var mapOptions = {
 zoom: 8,
 center: myLatLng,
 mapTypeId: google.maps.MapTypeId.ROADMAP
 };
 
// Generate the Map
 var map = new google.maps.Map(document.getElementById('map'), mapOptions);
 
// Add a Marker to the Map
 var marker = new google.maps.Marker({
 position: myLatLng,
 map: map,
 title: 'Found you!'
 });
}
Attach the above js to html as follows.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>GeoLocation Example</title>
 
 <style>
 html, body, #map {
 margin: 0;
 padding: 0;
 height: 100%;
 }
 </style>
</head>
<body>
 <div id="map"></div>
 
 <script src="script.js"></script>
</body>
</html>
Happy coding :) .

Comments