Thursday, February 23, 2012

Display Map on webpage to track location

In the previous article "Display Map of current location", we load current map of current using window.navigator.geolocation.getCurrentPosition() when page loaded. That means the map show the location when page load only, will not update when the user(or device) moved. We are going to replace it with window.navigator.geolocation.watchPosition() to get repeated position updates, to track the updated location.
Display Map on webpage to track location
<!DOCTYPE html>
<html>
<head>
<title>Mobile-Web-App: geolocation</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>

<style>#mapcanvas { height: 360px; width: 100%}</style>

<script type="text/javascript">

if (window.navigator.geolocation) {
window.navigator.geolocation.watchPosition(
successCallback, errorCallback);
} else {
alert("!!!Browser doesn't support Geolocation API.");
}

function successCallback(position){
loadmap();
var mylatitude = position.coords.latitude;
var mylongitude = position.coords.longitude;
document.getElementById("latitude").innerHTML
= "latitude: " + mylatitude;
document.getElementById("longitude").innerHTML
= "longitude: " + mylongitude;
document.getElementById("accuracy").innerHTML
= "accuracy: " + position.coords.accuracy;
loadmap(mylatitude, mylongitude);
}

function errorCallback(error) {
alert(error);
}

var map;

function loadmap(mylat, mylong){
var options = {
zoom: 15,
center: new google.maps.LatLng(mylat, mylong),
mapTypeId: google.maps.MapTypeId.SATELLITE,
};

map = new google.maps.Map(document.getElementById("mapcanvas"), options);
}

</script>

</head>
<body>
<h1>Mobile-Web-App: geolocation</h1>
<div id="mapcanvas"></div>
<div>
<p id="latitude"></p>
<p id="longitude"></p>
<p id="accuracy"></p>
</div>
</body>
</html>

No comments:

Post a Comment