【发布时间】:2021-12-28 12:12:24
【问题描述】:
我有一个 WebView 应用程序。我想每 5 秒更新一次我的位置。我正在运行下面的代码,但是每次坐标更改时都会显示此代码。我将这些数据保存在数据库中。我怎么解决这个问题?谢谢。
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],
}),
});
我从 openlayers 的网站获得了这段代码。我所做的唯一更改:
geolocation.setTracking(1);
我想在地图打开后立即获取我的位置。但是太多的数据即将到来。我只想每 5 秒获取一次位置和更新点。
【问题讨论】:
标签: javascript geolocation openlayers