Toggle Kml Layers In Maps Api
I am trying to now add the ability to toggle kmls with checkbox options for users to add kmls to a map that already has a couple of kmls loaded by default. I used this posts sugge
Solution 1:
You have two options:
- Maker your map variable global (it is currently local to your initialize function), and make the toggleLayers function global as well (they need to be global to be used in HTML click handlers.
- Use the google.maps.event.addDomListener to add click listeners to the check boxes, keep every thing local to the initialize function.
code snippet:
// layers to toggle var layers = [];
layers[0] = new google.maps.KmlLayer('http://www.geocodezip.com/geoxml3_test/utah-hunt_com_DeerSouthern_kml.xml', {
preserveViewport: true
});
layers[1] = new google.maps.KmlLayer('http://www.geocodezip.com/geoxml3_test/utah-hunt_com_DeerSoutheastern_kml.xml', {
preserveViewport: true
});
// end layers to toggle // intialize functioninitialize() {
var myLatlng = new google.maps.LatLng(40, -110);
var mapOptions = {
zoom: 5,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
loadKml = function(opts, map) {
var layer = new google.maps.KmlLayer();
opts.preserveViewport = true;
if (map) {
opts.map = map;
}
google.maps.event.addListener(layer, 'defaultviewport_changed', function() {
var map = this.getMap(),
bounds = map.get('kmlBounds') || this.getDefaultViewport();
bounds.union(this.getDefaultViewport());
map.set('kmlBounds', bounds);
map.fitBounds(bounds);
});
layer.setOptions(opts);
return layer;
};
functiontoggleLayers(i) {
if (layers[i].getMap() == null) {
layers[i].setMap(map);
} else {
layers[i].setMap(null);
}
google.maps.event.addListener(layers[i], 'status_changed', function() {
document.getElementById('status').innerHTML += "toggleLayers(" + i + ") [setMap(" + layers[i].getMap() + "] returns status: " + layers[i].getStatus() + "<br>";
});
}
// end toggle layers
google.maps.event.addDomListener(document.getElementById('layer_01'), 'click', function(evt) {
toggleLayers(0);
});
google.maps.event.addDomListener(document.getElementById('layer_02'), 'click', function(evt) {
toggleLayers(1);
});
// toggle layers at the beginningtoggleLayers(0);
toggleLayers(1);
}
google.maps.event.addDomListener(window, 'load', initialize);
body,
html,
#map {
height: 100%;
width: 100%;
}
<scriptsrc="https://maps.googleapis.com/maps/api/js"></script>
Layer1
<inputtype="checkbox"id="layer_01"checked="checked" />Layer2
<inputtype="checkbox"id="layer_02"checked="checked" /><divid="map"></div><divid="status"></div>
Post a Comment for "Toggle Kml Layers In Maps Api"