我有一個 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 秒獲取一次位置和更新點。
uj5u.com熱心網友回復:
change:position只要設備的 GPS 更新,就會觸發一個事件。要以固定間隔更新,只需以 5 秒間隔讀取位置
setInterval(function () {
const coordinates = geolocation.getPosition();
console.log(geolocation.getPosition());
positionFeature.setGeometry(coordinates ? new ol.geom.Point(coordinates) : null);
}, 5000);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/395770.html
標籤:javascript 地理定位 开放层
上一篇:承諾解決未定義的值
