How to use GPS in HTML5

Using HTML5 it has become fairly easy to make use of a GPS on your website in order to determine the exact location of your visitors. The custom made HTML5 functionality to meet this request is the so-called HTML5 Geolocation API. Keep in mind though, this functionality needs some JavaScript to work is not supported by older browsers (luckily enough most smartphones do support the HTML5 Geolocation functionality).

Please find below a live example the HTML5 geolocation functionality which can be used on your website. Because of privacy reasons you should always take into account users have to grant their permission before Geolocation can be performed. Therefor we’ve chosen to let you first click a button before the browser asks you if you agree to share your location.

HTML5 geolocation demo / example:

HTML / CSS / JavaScript

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

<style type="text/css">#map-canvas{height:250px}</style>

<script type="text/javascript">
var map = null;
function showlocation() {
// One-shot position request.
navigator.geolocation.getCurrentPosition(callback);
}

function callback(position) {

var lat = position.coords.latitude;
var lon = position.coords.longitude;

document.getElementById('latitude').innerHTML = lat;
document.getElementById('longitude').innerHTML = lon;

var latLong = new google.maps.LatLng(lat, lon);

var marker = new google.maps.Marker({
position: latLong
});

marker.setMap(map);
map.setZoom(8);
map.setCenter(marker.getPosition());
}

google.maps.event.addDomListener(window, 'load', initMap);
function initMap() {
var mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);

}
</script>
</head>
<body>
<center>
<input type="button" value="Show my location on Map"
onclick="javascript:showlocation()" /> <br/>
</center>

Latitude: <span id="latitude"></span> <br/>
Longitude: <span id="longitude"></span>
<br/><br/>
<div id="map-canvas"/>
</body>
</html>

Thanks to Viral Patel.



Was this useful?