Saturday, June 11, 2011

Simple Geolocation API demo, one-shot position requests.

It's a simple HTML with Javascript to get user current position using W3C Geolocation API.

Geo.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
if (window.navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
} else {
alert("Sorry! your browser does not support Geolocation API.");
}

function successCallback(position){
var msg ="";

msg += "Latitude: " + position.coords.latitude + "\n";
msg += "Longitude: " + position.coords.longitude + "\n";
msg += "Accuracy: " + position.coords.accuracy;

alert(msg);
}

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

</script>
<meta charset="UTF-8">
<title>Simple Geolocation API demo</title>
</head>
<body>
<h1>Simple Geolocation API demo</h1>


</body>
</html>


Result:
Run in Chrome under Ubuntu Linux on desktop PC - function errorCallback() is called with error of PositionError! (Refer to Get details of PositionError object)
Fail to run Geolocation API on desktop running Chrome

Run in Opera mobile on Android phone - function successCallback() is called with my position.
(To test the HTML on Android mobile, simple copy the HTML file to SD Card, and open with browser)
Geolocation API run on Android mobile

Related Post:
- Get repeated position updates using Geolocation API, navigator.geolocation.watchPosition()

No comments:

Post a Comment