我正在开发Ionic应用程序。我的应用程序是从USGS获取数据json api地震,然后在Google地图上设置坐标。我正在遍历数组以创建标记。一切正常,但是当我单击任何图标标记时,都会得到重复的标题!
export class HomePage implements OnInit {
protected points: { lng: number, lat: number }[] = [];
items: any
pet: string = "Today";
map: GoogleMap;
mags: number;
constructor(
private http: HTTP) {
}
async ngOnInit() {
this.getData()
}
async getData() {
this.http.get(`https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson`, {}, {}).then(data => {
this.items = JSON.parse(data.data)
let earth = JSON.parse(data.data)
console.log(this.items)
for (let datas of earth['features']) {
this.points.push({ lng: datas.geometry.coordinates[0], lat: datas.geometry.coordinates[1] });
let mag = datas.properties.place
let title = datas.properties.title
/// Marker icon
let dest = this.points.map((coords) => {
return this.map.addMarker({
position: coords,
icon: this.mags_icons
title : title
}).then((marker: Marker) => {
marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(() => {
});
});
});
this.map = GoogleMaps.create('map_canvas');
}
})
}
}
答案 0 :(得分:1)
标记的实例化方式看起来不正确,因为在功能集合的每次迭代中,预置标记都在重新创建(这就是我猜测title
引用相同标记的原因值)。
给出示例,以下示例演示了如何创建标记并设置title
来引用适当的功能ptoperty:
getData() {
this.http
.get(
`https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson`,{},{}
)
.then(data => {
let geojson = JSON.parse(data.data);
for (let feature of geojson["features"]) {
let markerProps = {
title: feature.properties.title,
position: {
lng: feature.geometry.coordinates[0],
lat: feature.geometry.coordinates[1]
}
};
let marker = this.map.addMarker(markerProps).then(marker => {
marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(() => {
//...
});
});
}
});
}
另一种选择是利用map.addMarkerSync
函数:
let geojson = JSON.parse(data.data);
for (let feature of geojson["features"]) {
let markerProps = {
title: feature.properties.title,
position: {
lng: feature.geometry.coordinates[0],
lat: feature.geometry.coordinates[1]
}
};
let marker = this.map.addMarkerSync(markerProps);
marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(() => {
//...
});
}