Home > HTML5 > Using HTML 5 GeoLocation Feature

Using HTML 5 GeoLocation Feature

html5-geolocation-api

 

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.


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.


<!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="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
 <script src="script.js"></script>
</body>
</html>

Happy coding 🙂 .

Advertisements
Categories: HTML5 Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: