[英]Google Maps/Angular JS: Map updates not always reflecting data, and can't remove markers
我有以下AngularJS方法,該方法采用lat / lng數組並將其繪制在地圖上。
$scope.zoomToIncludeMarkers = function(filteredPins) { // var defaultLatLng = '38.04973,-49.340406'; var bounds = new google.maps.LatLngBounds(); var infowindow = new google.maps.InfoWindow({}); infowindow.close(); filteredPins.forEach(function(c) { var latLng = new google.maps.LatLng(c.Latitude, c.Longitude); var siteInfo = '<h3>' + c.SiteName + '</h3>' + '<p>' + c.Address1 + '<br/>' + c.Address2 + '<br/>' + c.City + ', ' + c.State + ' ' + c.ZipCode + '</p>'; var marker = new google.maps.Marker({ position: latLng, map: $scope.map, icon: '/assets/img/locator.png' }); marker.setMap($scope.map); bounds.extend(latLng); if (typeof $scope.map != "undefined") { // $log.warn('$scope.map.fitbounnds ran...'); // $log.warn('lat/lng: ' + latLng); $scope.map.fitBounds(bounds); } marker.addListener('click', function() { infowindow.close(); infowindow.setContent(siteInfo) console.log('infowindow.open: ' + infowindow.open); infowindow.open($scope.map, this); $scope.findSelectedLocations(c.SiteName); }); }); google.maps.event.addListener(infowindow, 'closeclick', function() { console.log('infowindow closed ######'); console.log(infowindow); // marker.setMap(null); // $scope.resetSelectLists(); $rootScope.filteredData = $scope.dataObject; $scope.trialItemsSelected = []; }); };
第一次運行良好,但是隨着傳遞給它的數據集的變化,地圖不會更新以反映減少的引腳組。
我也不確定當傳遞給它的數據集(filteredPins)為空時如何去掉引腳。
第一次由#zoomToIncludeMarkers
創建和設置在地圖上的舊標記不會自動從地圖上刪除,只是因為創建了新標記,然后將其設置在同一地圖上。 我懷疑你剛剛開始積累的所有標記的所有filteredPins
不斷傳入此方法每次它叫。
您必須手動刪除以前的標記。
要在第二次運行#zoomToIncludeMarkers
僅保留一組新的減少的引腳,並在filteredPins
為空時也刪除所有引腳,我只想在#zoomToIncludeMarkers
頂部從地圖上清除所有標記的方法
var markers = [];
$scope.zoomToIncludeMarkers = function(filteredPins) {
// removeMarkers();
...
}
function removeMarkers () {
markers.forEach(function (marker) {
marker.setMap(null);
});
markers = [];
}
要利用這樣的模式,您需要將創建的標記存儲在數組中的某個位置(在這種情況下為markers
)。 像下面這樣的事情
filteredPins.forEach(function(c) {
var latLng = new google.maps.LatLng(c.Latitude, c.Longitude);
var marker = new google.maps.Marker({
position: latLng,
map: $scope.map,
icon: '/assets/img/locator.png'
});
markers.push(marker);
// FYI: I believe this is redundant. You don't need to manually set the marker on the map if you've already passed in the map via the markeroptions object
marker.setMap($scope.map);
...
}
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.