JavaScript Geolocation API
It's time to add a very mobile-specific element to our code—geolocation or "zoom to my current location" functionality. We discussed the Geolocation API in Chapter 2, Understanding Mobile Frameworks and APIs. Let's now put it to use. First, we will need to set an event listener, in this case, a map load listener:
map.on("load", myLoadHandler);
Inside the myLoadHandler
function we will reference the Geolocation API. We will detect whether or not the navigator.geolocation
object is available. This is a best practice because not all browsers support geolocation-based navigation. The position object will return coords.latitude
, coords.longitude
, and coords.accuracy
. It might also return coords.altitude
, coords.altitudeAccuracy
, coords.heading
, coords.speed
, and timestamp. Note that this varies by browser. We also need to handle any errors if the object is not available with the locationError()
function. The following code snippet...