我正在使用 openlayers5 和 angular 6 实现地理定位/位置跟踪功能。即使我没有收到任何错误并且这似乎工作正常,我也没有立即得到坐标。这是我的地理位置相关代码。
ngOnInit() {
//initialize everything in the ngOnInit
//set it
this.geolocation = new Geolocation({
trackingOptions: {
enableHighAccuracy: true
},
projection: 'EPSG:3857'
});
//handle errors
this.geolocation.on('error', (error) => {
this.geolocationerror=true;
this.geolocationmsg = error;
});
//accuracy
this.accuracyFeature = new Feature();
this.geolocation.on('change:accuracyGeometry', ()=> {
this.accuracyFeature.setGeometry(this.geolocation.getAccuracyGeometry());
});
//position point
this.positionFeature = new Feature();
this.positionFeature.setStyle(new Style({
image: new CircleStyle({
radius: 6,
fill: new Fill({
color: '#3399CC'
}),
stroke: new Stroke({
color: '#fff',
width: 2
})
})
}));
//track position
this.geolocation.on('change:position', ()=> {
let coordinates = this.geolocation.getPosition();
this.positionFeature.setGeometry(coordinates ?
new Point(coordinates) : null);
});
//on smaller screens toggle the geolocation on automatically
if(window.innerWidth < 600){
this.isChecked = true;
}
//geolocation has its own vector layer
this.geolocsource = new VectorSource({});
this.geoloclayer = new VectorLayer({
source: this.geolocsource,
title:'location'
});
}//ngOnInit closes here
//toggle geolocation on/off
toggleGeolocation(checked){
//erase any previous errors
this.geolocationmsg='';
this.geolocationerror=false;
////toggled on
if(checked){
this.geolocation.setTracking(checked); //set on
this.geolocsource.addFeatures([this.accuracyFeature, this.positionFeature]) ;
this.geolocOn = true; // to show info in html
let center = this.geolocation.getPosition();
//zoom there
if (center){
this.olmap.getView().animate({
center: center,
duration: 2000,
zoom:16
});
}
//show the geolocation coords in html all the time
this.geolocLiveCoords = this.geolocation.getPosition();
}
else{ //geolocation off
this.geolocation.setTracking(checked);
this.geolocOn = false;
this.geolocsource.clear();
this.geolocLiveCoords='';
}
}
这是HTML部分
<label for="track">track position<input id="trackpos" type="checkbox" [(ngModel)]="isChecked" (change)="toggleGeolocation(isChecked)"/></label>
<div *ngIf='geolocationerror'>{{geolocationmsg}}</div>
<div *ngIf='geolocOn'>{{geolocLiveCoords}}</div>
该复选框会自动检查较小的屏幕。
无论如何,即使我没有收到任何错误,我也必须自己手动检查复选框几次,以便查看地理位置坐标并使整个代码正常工作。我第一次打开它时它不起作用,它没有坐标,所以我将它关闭并再次打开。之后它工作正常,因为它应该。
这里有什么问题?我该如何解决?请指教。
谢谢