找到你要的答案

Q:Remove Polygon and add a new one with Google Maps

Q:删除多边形,并添加一个新的谷歌地图

I need to remove a Polygon I just created on a click event. When I click another again, it should remove the existing polygon and add a new one. Instead when I click it the second time it adds the second polygon but does not remove the first one.

I am using polygons in combination with Fusion Tables. The Fusion Tables remove on aclick as they should, it is just the Polygons that refuse.

<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>

我需要删除一个多边形,我刚刚创建的点击事件。当我再次点击另一个,它应该删除现有的多边形,并添加一个新的。相反,当我点击它的第二次,它增加了第二个多边形,但不删除第一个。

I am using polygons in combination with Fusion Tables. The Fusion Tables remove on aclick as they should, it is just the Polygons that refuse.

<script type="text/javascript">
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);

function init() {

    聚=“;

    // 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>
answer1: 回答1:

The code looks fine from what I can see but you should declare poly outside the scope of the init() function and using:

var poly;

rather than:

poly = "";


There is an also an error of Uncaught RangeError: Maximum call stack size exceeded in chrome which is suggesting that

google.maps.event.addListener(marker, 'click', (function(marker, i) {
  return function() {
    infowindow.setContent(locations[i][0]);
    infowindow.open(map, marker);
  }
})(marker, i));

is iterating over too many locations and adding a large number of listeners.

代码看起来很好我知道但你应该宣布聚在()函数和使用范围:

VaR的聚;

而不是:

聚=“;


有一个也是一个错误:在捕获的rangeerror Chrome提示超过最大堆栈大小

google.maps.event.addListener(marker, 'click', (function(marker, i) {
  return function() {
    infowindow.setContent(locations[i][0]);
    infowindow.open(map, marker);
  }
})(marker, i));

在太多的地方,增加了大量的听众迭代。

javascript  jquery  google-maps  google-maps-api-3  polygons