【发布时间】:2017-10-07 14:49:36
【问题描述】:
我在 Angular 2 中添加了 JavaScript 的谷歌地图 API。 根据从 API 获取的位置在地图上添加自定义标记。 我在 UI 上显示了职位列表。单击位置后,我想替换该位置的相应标记图标并重置所有其他图标。 以下代码未按预期工作。
我已添加此功能以在地图上放置标记:
placeMarkers(markers: any, infoWindowContent: any) {
// Display multiple markers on a map
let infoWindow = new google.maps.InfoWindow();
let bounds = new google.maps.LatLngBounds();
let marker;
// Loop through our array of markers & place each one on the map
for(let i = 0; i < markers.length; i++ ) {
let position = new google.maps.LatLng(<number>markers[i].lat, <number>markers[i].lang);
bounds.extend(position);
marker = new google.maps.Marker(<google.maps.MarkerOptions>{
position,
map: this.map,
title: markers[i].name,
icon: this.iconUrl,
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i]);
infoWindow.open(this.map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
this.map.fitBounds(bounds);
}
}
这个代码替换所选位置的标记:
selectSite(site: any, index: any) {
this.placeMarkers(this.finalMarkers, this.finalInfoWindowContent);
let selection = this.finalMarkers.find(function(item) {
return item.name == site.Name
});
let infowindow = new google.maps.InfoWindow();
let position = new google.maps.LatLng(<number>selection.lat, <number>selection.lang);
let redMarker = new google.maps.Marker(<google.maps.MarkerOptions>{
position: position,
map: this.map,
title: selection.name,
icon: {url: require('../../../assets/img/red-marker.png'), scaledSize: {height: 30, width: 20}}
});
redMarker.addListener('click', function() {
infowindow.setContent(selection.name);
infowindow.open(this.map, redMarker);
});
}
上面的代码最初运行良好,但在多次更改位置后卡住了。 非常感谢任何帮助!
【问题讨论】:
标签: javascript google-maps google-maps-api-3