Hide Table of Contents
Tutorials
About the API
Work with the API
Graphics and feature layers
Popups and Info Windows
Mobile
ArcGIS Server Services
References
What's New archive
The HTML5 Geolocation API is used to get the geographical position of the device. It permits users to opt-in to sharing their location with websites.
navigator.geolocation object is available. The position object will return the coords.latitude, coords.longitude, and coords.accuracy. The position object may also return the coords.altitude, coords.altitudeAccuracy, coords.heading, coords.speed and timestamp.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(zoomToLocation, locationError);
navigator.geolocation.watchPosition(showLocation, locationError);
}
getCurrentPosition() method returns a location object if it is successful. The latitude, longitude and accuracy properties are always returned. The other properties mentioned above are returned if available. Once we have the coordinates we can zoom to the location using coords.latitude and coords.longitude.
require([
"esri/map", "esri/geometry/webMercatorUtils", "esri/geometry/Point", ...
], function(Map, webMercatorUtils, Point, ... ) {
var map = new Map(...);
function zoomToLocation(location) {
var pt = webMercatorUtils.geographicToWebMercator(new Point(location.coords.longitude, location.coords.latitude));
map.centerAndZoom(pt, 16);
}
});
watchPosition() to return an updated position as the user moves. clearWatch() can be used to stop the watchPosition() method.
function showLocation(location) {
if (location.coords.accuracy <= 500) {
// the reading is accurate, do something
} else {
// reading is not accurate enough, do something else
}
getCurrentPosition() and watchPosition() method is used to handle errors. It simply specifies a function to execute if obtaining the user's location fails.
function locationError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("Location not provided");
break;
case error.POSITION_UNAVAILABLE:
alert("Current location not available");
break;
case error.TIMEOUT:
alert("Timeout");
break;
default:
alert("unknown error");
break;
}
}