为每个级别的缩放Google地图设置事件?

时间:2019-01-15 14:18:41

标签: javascript google-maps

当我缩放每级Google地图时,如何指定加载一个kml文件? 这是我的代码:

<!DOCTYPE html>
<html>
<head>
    <title>Getting Properties With Event Handlers</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
        #map {
            height: 100%;
        }
        html,
        body {
            height: 100%;
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    <div id="map"></div>
    <script>
        var kmlLayer;
        function initMap() {
            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 8,
                center: { lat: 10.89779, lng: 106.64619 }
            });

            map.addListener('idle', function () {
                if (map.getZoom() == 9) {
                    //alert('aa');
                    kmlLayer = new google.maps.KmlLayer({
                        url: 'a.kml',
                        map: map
                    });
                }
                else if (map.getZoom() == 10) {
                     kmlLayer = new google.maps.KmlLayer({
                        url: 'b.kml',
                        map: map
                }
            });
        }
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=MY_API&callback=initMap">
    </script>
</body>

</html>

这意味着map.getZoom() == 9时,地图将按文件a.kml绘制。 Map.getZoom() == 10将根据b.kml文件进行绘制,而a.kml文件所创建的所有细节都将被删除。

但是当a.kml文件创建缩放和细节时,我上面的代码并不平滑。 Map.getZoom() == 10不会将其删除。

请帮助我解决此问题。谢谢

1 个答案:

答案 0 :(得分:0)

您需要先隐藏现有的KmlLayer,然后再显示新的KmlLayer。像这样:

var kmlLayer;
map.addListener('idle', function () {
    if (map.getZoom() == 9) {
        if (kmlLayer && kmlLayer.setMap) kmlLayer.setMap(null);
        kmlLayer = new google.maps.KmlLayer({
            url: 'a.kml',
            map: map
        });
    }
    else if (map.getZoom() == 10) {
         if (kmlLayer && kmlLayer.setMap) kmlLayer.setMap(null);
         kmlLayer = new google.maps.KmlLayer({
            url: 'b.kml',
            map: map
         });
    }

(如果您为所有缩放级别定义了KmlLayers,则可能需要将隐藏现有图层的代码移到if之外)

proof of concept fiddle