I have a WebView application. I want to update my location every 5 seconds. I'm running the code below, but this code shows every time the coordinate changes. I am saving this data in database. How can I solve this problem? Thanks.
const view = new ol.View({
center: [0,0],
zoom: 7,
projection: 'EPSG:4326',
});
const map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
],
target: 'map',
view: view,
});
const geolocation = new ol.Geolocation({
trackingOptions: {
enableHighAccuracy: true,
},
projection: view.getProjection(),
});
function el(id) {
return document.getElementById(id);
}
geolocation.setTracking(1);
// update the HTML page when the position changes.
geolocation.on('change', function () {
console.log(geolocation.getAccuracy() + ' [m]');
console.log(geolocation.getAltitude() + ' [m]');
console.log(geolocation.getAltitudeAccuracy() + ' [m]');
console.log(geolocation.getHeading() + ' [rad]');
console.log(geolocation.getSpeed() + ' [m/s]');
});
// handle geolocation error.
geolocation.on('error', function (error) {
const info = document.getElementById('info');
info.innerHTML = error.message;
info.style.display = '';
});
const accuracyFeature = new ol.Feature();
geolocation.on('change:accuracyGeometry', function () {
accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
});
const positionFeature = new ol.Feature();
positionFeature.setStyle(
new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
fill: new ol.style.Fill({
color: '#3399CC',
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 2,
}),
}),
})
);
geolocation.on('change:position', function () {
const coordinates = geolocation.getPosition();
console.log(geolocation.getPosition());
positionFeature.setGeometry(coordinates ? new ol.geom.Point(coordinates) : null);
});
new ol.layer.Vector({
map: map,
source: new ol.source.Vector({
features: [accuracyFeature, positionFeature],
}),
});
I got this code from openlayers' site. The only change I made:
geolocation.setTracking(1);
I wanted to get my location as soon as the map opened. But too much data is coming. I just want to get location and update point every 5 seconds.
A change:position
event will fire whenever the device's GPS updates. To update at a fixed interval simply read the position at 5 second intervals
setInterval(function () {
const coordinates = geolocation.getPosition();
console.log(geolocation.getPosition());
positionFeature.setGeometry(coordinates ? new ol.geom.Point(coordinates) : null);
}, 5000);