Я использую Карты Google в приложении Ionic/Angular, и у меня проблемы с удалением маркеров. Я использую https://developers.google.com/maps/documentation/javascript/examples/marker-remove
как руководство, но у меня проблемы. В приложении 1 маркер получает шнуровку, когда пользователь нажимает на карту (это в функции инициализации). Другой маркер получает место, когда вызывается getResult(). Когда я пытаюсь очистить маркеры, я не могу удалить тот, который помещен, нажав на карту. Но другой маркер удаляется. Я не знаю, почему это происходит. Любой совет?
$scope.initialise = function() {
$ionicLoading.show({
content: 'Loading',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0,
duration: 5000
});
var myLatlng = new google.maps.LatLng(37.758446, -122.411789);
$scope.markersArray = [];
//Initial settings for the map
var mapOptions = {
center: myLatlng,
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: [{ featureType: "poi", elementType: "labels", stylers: [{ visibility: "off" }]}]
};
//Load the initial map
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
//Event listener to add a marker
google.maps.event.addListener(map, 'click', function(e) {
$scope.clearOverlays();
$scope.coordinates = e.latLng;
$scope.placeMarker(e.latLng, $scope.map);
});
//Actual function to add a marker
$scope.placeMarker = function(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
$scope.markersArray.push(marker);
map.panTo(position);
}
$scope.clearOverlays = function() {
for (var i = 0; i < $scope.markersArray.length; i++ ) {
$scope.markersArray[i].setMap(null);
}
$scope.markersArray = [];
}
$scope.map=map;
$ionicLoading.hide();
};
// End of initialise
google.maps.event.addDomListener(window, 'load', $scope.initialise());
$scope.getResult = function() {
// Add actual coordinates to map
actualCoor = new google.maps.LatLng(Number($scope.active_location.Lat), Number($scope.active_location.Long));
$scope.placeMarker(actualCoor, $scope.map);
// Resize the map
window.setTimeout(function(){
google.maps.event.trigger(map, 'resize');
},100);
// Add actual coordinates to map
actualCoor = new google.maps.LatLng(Number($scope.active_location.Lat), Number($scope.active_location.Long));
$scope.placeMarker(actualCoor, $scope.map);
// Resize the map
window.setTimeout(function(){
$scope.map.panTo($scope.coordinates);
},100);
// Add circle overlay to map
$scope.circle = new google.maps.Circle({
map: $scope.map,
center: actualCoor,
radius: 500000, //500km away
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2,
fillColor:"#0000FF",
fillOpacity:0.4
});
// Add line between points
var flightPlanCoordinates = [$scope.coordinates, actualCoor];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap($scope.map);
// Show info window for user guess
$scope.infowindow = new google.maps.InfoWindow({
content: 'Your guess'
});
var marker = new google.maps.Marker({
position: $scope.coordinates,
map: $scope.map,
title: 'Your guess'
});
$scope.infowindow.open($scope.map,marker);
}
$scope.reset_map = function() {
console.log($scope.markersArray[0]);
$scope.markersArray[0].setMap(null);
console.log($scope.markersArray[0]);
console.log($scope.markersArray[1]);
$scope.markersArray[1].setMap(null);
console.log($scope.markersArray[1]);
$scope.markersArray = [];
// Remove line
flightPath.setMap(null);
// Remove circle
$scope.circle.setMap(null);
// Remove infowindow
$scope.infowindow.close();
$scope.infowindow = null;
// $scope.clearOverlays();
}
Я уверен, что это происходит, потому что я добавляю infowindow и маркер для загрузки при загрузке, но я не уверен, как это исправить.
Вы не нажимаете маркер, который вы создаете для Infowindow, на markersArray. Вот почему его не удаляют. Просто добавьте эти строки.
$scope.markersArray.push(marker); // Add this line
$scope.infowindow.open($scope.map,marker);
$scope.getResult
добавляет 2$scope.getResult
в одно и то же место (у вас есть дублированный код), поэтому вашclear
код может очищать только первый.