Current Location with Javascript
July 1st, 2012 • 2 notesBoth Breeze, and another little mobile app I’m working on utilize javascript’s geolocation API. It’s actually very easy to obtain a users longitude and latitude with this API, using the following snippet:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var lat = (position.coords.latitude);
var lon = (position.coords.longitude);
}, // next function is the error callback
function (error) {
switch (error.code) {
case error.TIMEOUT:
alert('A timeout has occured, and your location was unable to be determined.');
break;
case error.POSITION_UNAVAILABLE:
alert('Your current position was not able to be retrieved. This is most likely due to a lack of network connectivity.');
break;
case error.PERMISSION_DENIED:
alert('Unable to retrieve your location because permission was denied. Please ensure location services are turned on for Safari.');
break;
case error.UNKNOWN_ERROR:
alert('An unknown error occured. :(');
break;
}
});
}
Easy right? Once you have a user’s coordinates, you can use all kinds of location based API’s to write to neat apps and features.
