Мне нужно удалить многоугольник, который я только что создал на событии клика. Когда я снова нажимаю другой, он должен удалить существующий многоугольник и добавить новый. Вместо этого, когда я нажимаю его во второй раз, он добавляет второй многоугольник, но не удаляет первый.Удалить многоугольник и добавить новый с помощью Google Maps
Я использую полигоны в сочетании с таблицами Fusion. Таблицы Fusion удаляют на aclick, как должны, это только Полигоны, которые отказываются.
<script type="text/javascript">
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);
function init() {
poly = "";
// Basic options for a simple Google Map
var mapOptions = {
// How zoomed in you want the map to start at (always required)
zoom: 4,
scrollwheel: false,
// The latitude and longitude to center the map (always required)
center: new google.maps.LatLng(-15.614057, 23.351191),
// Get the HTML DOM element that will contain your map
// We are using a div with id="map" seen below in the <body>
var mapElement = document.getElementById('map');
// Create the Google Map using our element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);
var mapDiv = document.getElementById('map');
// Add Fusion Tables Layer
var layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1rOaSNuoP1LwPf7-5j5Hr4tSWxjKT265MmuS8vd_l'
},
options : {suppressInfoWindows:true, clickable:false}
});
layer.setMap(map);
// Add Dynamic Markers which loads when Map loads
function setupMarkers(){
var locations = [
<?php $custom_query = new WP_Query(array('post_type' => 'lodge', 'posts_per_page' => 20));
$counter = 0;
while($custom_query->have_posts()) : $custom_query->the_post(); $counter++; $image = get_field('page_image');?>
['<div class="info-popup"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><p class="lodge-rating"><?php $stars="<i class=\'fa fa-star\'></i>";$x = get_field('rating');echo str_repeat($stars, $x);?></p><a href="<?php the_permalink(); ?>"><img src="<?php echo $image['url']; ?>"/></a><p><?php the_field('intro') ?></p><a href="<?php the_permalink(); ?>">View Lodge</a></div>', <?php the_field('latitude'); ?>, <?php the_field('longitude'); ?>, <?php echo $counter; ?>],
<?php endwhile; ?>
];
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
setupMarkers()
// Setup the Countries using the Fusion Table Data
function setCountries(blurb, countryLat, countryLong, zoomLev) {
layer.setMap(map);
var options = {
styles: []
};
var styles = [];
Kenya = blurb;
var latLng = new google.maps.LatLng(countryLat, countryLong);
map.setZoom(parseFloat(zoomLev));
map.panTo(latLng);
options.styles.push({
where: "'name' = '" + Kenya + "'",
polygonOptions: {
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.3
}
});
layer.setOptions(options);
};
// Setup the Destinations with user provided coordinates.
function setDestinations(countryLat, countryLong, zoomLev, shapesLatArr, shapesLongArr) {
layer.setMap(null);
pOptions = "";
jQuery.each(shapesLatArr, function(i, item) {
if (i < shapesLatArr.length - 1){
myCoordinates.push(new google.maps.LatLng(parseFloat(shapesLatArr[i]) , parseFloat(shapesLongArr[i])));
}
});
var polyOptions = {
path: myCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.3
};
var latLng = new google.maps.LatLng(countryLat, countryLong);
map.setZoom(parseFloat(zoomLev));
map.panTo(latLng);
var pOptions = polyOptions;
poly = new google.maps.Polygon(pOptions);
clearPoly();
poly.setMap(map);
myCoordinates = [];
};
// Clear Polygons
function clearPoly() {
poly.setMap(null);
}
// Setup the Click Events For Countries
allCuntries = jQuery(".heatmap");
allCuntries.each(function() {
jQuery(this).click(function() {
blurb = jQuery(this).text();
countryLat = jQuery(this).attr('data-lat');
countryLong = jQuery(this).attr('data-long');
zoomLev = jQuery(this).attr('data-zoom');
setCountries(blurb, countryLat, countryLong, zoomLev);
});
});
// Setup the Click Events For Destinations
allDestins= jQuery(".heatrat span");
allDestins.each(function() {
jQuery(this).click(function() {
myCoordinates = [];
shapesLat =[];
shapesLong =[];
countryLat = jQuery(this).attr('data-lat');
countryLong = jQuery(this).attr('data-long');
zoomLev = jQuery(this).attr('data-zoom');
shapesLat = jQuery(this).attr('data-shape-lat');
shapesLong = jQuery(this).attr('data-shape-long');
shapesLatArr = shapesLat.split(',').map(Number);
shapesLongArr = shapesLong.split(',').map(Number);
setDestinations(countryLat, countryLong,zoomLev, shapesLatArr, shapesLongArr);
});
});
}
</script>
Чтобы уточнить, что мой ответ действительно касается проблемы, было бы полезно, если бы вы могли настроить https://jsbin.com/?html,js,output, чтобы служить в качестве кода, с которым мы можем играть, чтобы определить проблему. –
Привет, Дэвид, спасибо за ответ, я сделал, как показано ниже, но все равно не повезло. Проверьте ссылку dev, www.weloveweb.co.za/africaandyou. Я не могу настроить bin, поскольку данные загружаются динамически из БД. Вы можете проверить его, прокрутив к карте, щелкнув по Южной Африке, затем на Квазулу-Натале, затем в Кейптауне, просто уменьшив масштаб, и вы увидите оба полигона. –
См. Мое редактирование - кажется, что у вас есть проблема с добавлением слишком большого количества прослушивателей кликов. Сколько мест включено? –