0
votes

I'm attempting to add multiple kml layers to a map that can be turned on and off with check boxes. I got that part working (yay!). When I click on a layer to turn it on, it zooms in (this is fine), but when I unclick to turn the layer off, it zooms back out to my map extent. How do I get it to preserve the zoom of the last loaded layer? Code below.

<script>
var map;
var watershedLayer = new google.maps.KmlLayer ({
url: 'http://mvihes.bc.ca/mapping/watersheds.kmz'
});

var ere1949Layer = new google.maps.KmlLayer ({
url: 'http://mvihes.bc.ca/mapping/ere1949.kmz'
});
function initialize() {
var parksville= new google.maps.LatLng(49.316786, -124.308768);
var mapOptions = {
zoom: 9,
center: parksville
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
check();
}
function check()
{
    if(document.getElementById('watersheds').checked)
      {watershedLayer.setMap(map);}
    else
      {watershedLayer.setMap(null);}
    if(document.getElementById('ere1949').checked)
      {ere1949Layer.setMap(map);}
    else
      {ere1949Layer.setMap(null);}

}
google.maps.event.addDomListener(window, 'load', initialize);

</script>

I tried using the preserveViewport function but it just stopped the layer from zooming in, which is not what I wanted. I'm new to javaScript so possibly I'm missing something obvious...any help would be appreciated!

jsfiddle

2
There is nothing in your posted code to do that. Please post a Minimal, Complete, Tested and Readable example. jsfiddle of your code - geocodezip

2 Answers

1
votes

Set the map-property of a selected layer only when it's not set yet:

function check()
{
    if(document.getElementById('watersheds').checked)
      {if(!watershedLayer.getMap())watershedLayer.setMap(map);}
    else
      {watershedLayer.setMap(null);}
    if(document.getElementById('ere1949').checked)
      {if(!ere1949Layer.getMap())ere1949Layer.setMap(map);}
    else
      {ere1949Layer.setMap(null);}

}

http://jsfiddle.net/jhagmq7L/16/

0
votes

You can also attach max and min zoom levels to the map, something to consider the over all map zoom when loading kml layers.

// sets the min and max zoom levels of the map
    var opt = { minZoom: 6, maxZoom: 18 };
    map.setOptions(opt);