我是打字稿的初学者。 当我尝试从locateMe()调用方法drawMarker()时遇到问题。 我认为问题是我在.on内部调用drawMarker(' locationfound',function(e:any){}
EXCEPTION:this.drawMarker不是函数
drawMarker工作,我从其他方法中提取它
我的组件类中的两个方法:
drawMarker(item: any, elementId: any) {
if (elementId === 'inpStartWayPoint') {
if (typeof(this.startMarker) === 'undefined') {
this.startMarker = L.marker([parseFloat(item.lat), parseFloat(item.lon)]);
this.map.addLayer(this.startMarker);
this.startMarker.bindPopup('Départ').openPopup();
} else {
this.startMarker.setLatLng(([parseFloat(item.lat), parseFloat(item.lon)]));
}
//this.map.removeLayer(this.startMarker);
} else if (elementId === 'inpEndWayPoint') {
if (typeof(this.endMarker) === 'undefined') {
this.endMarker = L.marker([parseFloat(item.lat), parseFloat(item.lon)]);
this.map.addLayer(this.endMarker);
this.endMarker.bindPopup('Arrivée').openPopup();
} else {
this.endMarker.setLatLng(([parseFloat(item.lat), parseFloat(item.lon)]));
}
} else if (elementId === 'locateMyPosition') {
if (typeof(this.geoLocateMarker) === 'undefined') {
this.geoLocateMarker = L.marker([item.latitude, item.longitude]);
this.map.addLayer(this.geoLocateMarker);
this.geoLocateMarker.bindPopup('Votre Position').openPopup();
} else {
this.geoLocateMarker.setLatLng([item.latitude, item.longitude]);
}
}
}
locateMe(elementId: any) {
this.map.locate({
setView: true,
watch: true
}) /* This will return map so you can do chaining */
.on('locationfound', function(e: any) {
// var marker = L.marker([e.latitude, e.longitude]).bindPopup('Your are here :)');
var circle = L.circle([e.latitude, e.longitude], e.accuracy / 2, {
weight: 1,
color: 'blue',
fillColor: '#ca08c9',
fillOpacity: 0.2
});
console.log([e.latitude]);
this.drawMarker(e, elementId);
//this.map.addLayer(marker);
this.map.addLayer(circle);
})
.on('locationerror', function(e: any) {
console.log(e);
alert("Location access denied.");
});
}
我的boutton locateMe的html输入:
<div class="form-group input-group">
<span class="input-group-addon"><button type="button" id="locateMyPosition" title='Locate Me !'
(click)="locateMe('locateMyPosition')"><i
class="fa fa-map-marker"></i></button></span>
<input type="text" class="form-control" placeholder="Départ" value="" id="inpStartWayPoint">
<span class="input-group-btn"><button class="btn btn-secondary" type="button"
(click)="adressAutoComplete('inpStartWayPoint')"><i
class="fa fa-search"></i></button></span>
</div>
提前感谢您提供给我的任何帮助!
答案 0 :(得分:2)
使用lambda来保持对this
的引用:
.on('locationfound', (e: any) => {
...
}
答案 1 :(得分:1)
this
更改function
内的上下文,尝试使用箭头函数,它会保留this
上下文。
这样的事情:
this.map.locate({ setView: true, watch: true }) .on('locationfound', (e: any) => { // using arrow function here
var circle = L.circle([e.latitude, e.longitude], e.accuracy / 2, {
weight: 1,
color: 'blue',
fillColor: '#ca08c9',
fillOpacity: 0.2
});
console.log([e.latitude]);
this.drawMarker(e, elementId);
this.map.addLayer(circle);
})
.on('locationerror', (e: any) => {
console.log(e);
alert("Location access denied.");
});