An object with this interface is obtained using the navigator.geolocation
property.
Before using Geolocation
the following permission need to be added to the manifest.webapp
:
"permissions": {
"geolocation": {
"description": "Get/watch your current position."
}
}
On the first usage of the API, a dialog will ask the user to allow or deny the permission.
To add something else to the many examples on Internet, the Promise
API is also available in KaiOS and might be useful to use them together.
For example:
function locate(enableHighAccuracy, retryTimeout) {
return new Promise(function(resolve, reject) {
navigator.geolocation.getCurrentPosition(
function(position) {
resolve(position);
},
function(error) {
if (error.code === 3 && retryTimeout + 1 <= maxTimeouts) {
locate(enableHighAccuracy, retryTimeout + 1).then(resolve).catch(reject);
} else {
reject(error);
}
},
{
maximumAge: 0,
timeout: 30000 + (retryTimeout * 30000),
enableHighAccuracy: true,
}
);
});
}
To be used like:
locate(false, 0)
.then(function(position) {
const lat = position.coords.latitude;
const lng = position.coords.longitude;
console.log(`You're at ${lat.toFixed(4)}, ${lng.toFixed(4)}`);
})
.catch(function(error) {
if (error.code === 1) {
console.log('Please allow geolocation permissions');
} else if (error.code === 2) {
console.log('Geolocation failed');
} else if (error.code === 3) {
console.log('Geolocation took too long');
}
});
Remember that
Geolocation
API cannot be request on page load and must be triggered by an user action.
Once the success function is called, is given a GeolocationPosition
object which has the position timestamp
and coords
.
GeoLocationCoordinates
object will have many juicy items to work with:
speed === 0
, then you are still. Heading is an angle in degrees and speed meters by seconds.For functions of this API that accept options, the following are expected:
true
, as it might be enabling wifi even is it off.Infinity
by default, so no error with code 3
will ever be thrown.0
. Recommended to keep it like this.Read GeolocationPositionOptions
for more info.
There are three reasons that an error could be thrown with this API:
Read GeolocationPositionError
for more info.