我正在使用angular / typescript为bing maps实现创建一个组件。我经历了一个过程,在地图上添加一个最初对用户不可见的信息框。当用户点击地图上的任何图钉时,应该显示信息框。
然而它没有,并且属性显示为undefined。
注意:'DataPoints'包含一个包含纬度长坐标和任意ID号的对象列表。
import { Component, AfterViewInit } from '@angular/core';
import { DataPoint } from '../common/data-point'
import { DataPoints } from '../common/data-points'
@Component({
selector: 'app-simple-bing-map',
templateUrl: './simple-bing-map.component.html',
styleUrls: ['./simple-bing-map.component.css'],
providers: []
})
export class SimpleBingMapComponent implements AfterViewInit {
private map: any;
private infobox: any;
ngAfterViewInit() {
this.getMap();
}
populateMap(){
for(var i in DataPoints){
var pushpin = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(DataPoints[i].Lat, DataPoints[i].Long) , null);
pushpin.metadata = {
title: "Test Pushpin",
description: DataPoints[i].ID,
};
//Add a click event handler to the pushpin.
Microsoft.Maps.Events.addHandler(pushpin, 'click', this.displayInfobox);
//place pushpin
this.map.entities.push(pushpin);
}
}
getMap() {
//check if Microsoft is available
if ((window as any).Microsoft && (window as any).Microsoft.Maps) {
//if it is available create map instance
this.map = new Microsoft.Maps.Map(document.getElementById('mapId'), {
credentials: 'Your Bing Maps Key Here',
});
//initialize infobox
this.infobox = new Microsoft.Maps.Infobox(this.map.getCenter(), {
title: 'Pushpins',
description: 'ID Number'
}
);
//hide infobox
this.infobox.setOptions({ visible: false })
//Assign the infobox to a map instance.
this.infobox.setMap(this.map);
this.populateMap();
}
//wait and try again
else {
setTimeout(() => { this.getMap() }, 1000);
}
}
displayInfobox(e) {
//hide any previous infobox
this.infobox.setOptions({ visible: false });
//Make sure the infobox has metadata to display.
if (e.target.metadata) {
//Set the infobox options with the metadata of the pushpin.
this.infobox.setOptions({
location: e.target.getLocation(),
title: e.target.metadata.title,
description: e.target.metadata.description,
visible: true
});
}
}
}
如前所述,地图完全加载并按预期工作。就在我进入'displayInfobox'方法之后,事情很奇怪。
答案 0 :(得分:0)
要在displayInfobox
方法中保留此内容,我建议您使用bind
方法,例如:
Microsoft.Maps.Events.addHandler(pushpin, 'click', this.displayInfobox.bind(this));
或箭头功能:
Microsoft.Maps.Events.addHandler(pushpin, 'click', (e) => this.displayInfobox(e));
有关其他解决方案,请参阅