简体   繁体   中英

Set event for each level zoom google map?

How do I specify load one kml file when I zoom each level google map? This is my code:

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

It means when map.getZoom() == 9 , The map will draw by file a.kml . Map.getZoom() == 10 will draw by b.kml file and all detail created by a.kml file will be removed.

But my code above doesn't smooth when zoom and detail is created by a.kml file. It is not removed when Map.getZoom() == 10 .

Please help me fix this. Thanks

You need to hide the existing KmlLayer before displaying the new one. Something like:

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
         });
    }

(if you have KmlLayers defined for all the zoom levels, you may want to move the code that hides the existing layer outside of the if )

proof of concept fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM