我正在用openlayers5和angular 6实现地理定位/位置跟踪功能。尽管我没有犯任何错误,而且这似乎很好,但我不会马上得到coords。这是我的地理位置相关代码。
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>
对于较小的屏幕,会自动选中该复选框。
在任何情况下,即使我没有收到任何错误,我也必须手动勾选并取消勾选复选框几次,以便查看地理位置坐标,并使整个代码正常工作。我第一次打开它时它不起作用,它没有咕咕声,所以我一次又一次地打开它。在那之后,它就可以正常工作了
这里有什么问题?我该怎么修?请提供建议。
感谢
只有当您用true
调用toggleGeolocation
时才打开跟踪,在这个阶段,只有当您选中复选框时才会发生这种情况。如果你想让它直接开始,你应该在ngOnInit
方法的末尾调用它:
this.toggleGeolocation(this.isChecked);