【问题标题】:Remove Polygon and add a new one with Google Maps使用 Google 地图删除多边形并添加一个新多边形
【发布时间】:2023-04-06 11:49:01
【问题描述】:

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

我将多边形与 Fusion Tables 结合使用。 Fusion Tables 应在单击时删除,它只是 拒绝的多边形。

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

【问题讨论】:

  • 为了澄清我的回答实际上是在解决这个问题,如果您可以设置一个jsbin.com/?html,js,output 作为我们都可以用来确定问题的代码,那将会很有用
  • 嗨,大卫,感谢您的回答,我按照下面的方法做了,但仍然没有运气。检查开发链接 www.weloveweb.co.za/africaandyou 。我无法设置 bin,因为数据是从数据库动态加载的。您可以通过滚动到地图来测试它,点击南非,然后点击夸祖鲁纳塔尔,然后点击开普敦,只要缩小,您就会看到两个多边形。
  • 查看我的编辑 - 您似乎在添加太多点击侦听器时遇到了问题。包括多少个地点?
  • 请提供一个 Minimal, Complete, Tested and Readable example 来说明问题,包括可能需要的任何数据(一些示例位置)和 HTML/CSS。
  • 什么多边形? fiddle

标签: javascript jquery google-maps google-maps-api-3 polygons


【解决方案1】:

从我所见,代码看起来不错,但您应该在 init() 函数的范围之外声明 poly 并使用:

var poly;

而不是:

poly = "";


chrome中还有一个Uncaught RangeError: Maximum call stack size exceeded的错误提示

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

正在迭代太多位置并添加大量侦听器。

【讨论】:

    猜你喜欢
    • 2020-05-20
    • 2015-08-26
    • 2019-04-11
    • 2014-05-21
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多