Toggle kml-Layer on styled map only works once

社会主义新天地 提交于 2020-01-05 05:55:10

问题



I'd like to have checkboxes to turn kml-Layers on and off. I tried to do that with a styled map in the google maps api v3. The Layers really do appear and I can toggle them off. But the button only works once.
This (http://jsbin.com/irahef/186/edit) helped me a lot. Here they also use a styled google map: http://www.strahlen.org/map/map.htm I'm sure it's just a small mistake but I don't get it working. Does somebody has a clue?
The Javascript looks like this:

<html>
<head>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"</script>
<script>
var layers = [];
function toggleLayer(i) {
  if(layers[i].getMap() == null) {
    layers[i].setMap(map);}
  else {
    layers[i].setMap(null);}}

function initialize() {  var styles = [ { "featureType": "poi", "elementType": "geometry", "stylers": [ { "color": "#dcdcdc" } ] },{ "featureType": "landscape", "elementType": "geometry.fill", "stylers": [ { "color": "#d2d2d2" } ] },{ "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [ { "color": "#ffffff" } ] }, ]; 
var styledMap = new google.maps.StyledMapType(styles,
  {name: "Styled Map"});
var latlng = new google.maps.LatLng(52.5028910, 13.41032740);
var myOptions = {
    zoom: 10,
    center: latlng,
mapTypeControlOptions: {
  mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'meine_styles']
}
};

var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);

layers[0] = new google.maps.KmlLayer({url:'https://sites.google.com      /site/kmykmlfiles/mykml/einkaufen.kml'}, {preserveViewport: true});
layers[1] = new google.maps.KmlLayer({url:'https://sites.google.com/site/kmykmlfiles/mykml/1_entspannen.kml'}, {preserveViewport: true});
layers[2] = new google.maps.KmlLayer({url:'https://sites.google.com/site/kmykmlfiles/mykml/1_essen.kml'}, {preserveViewport: true});
for (var i = 0; i < layers.length; i++) {
    layers[i].setMap(map);}

map.mapTypes.set('meine_styles', styledMap);
map.setMapTypeId('meine_styles');
}

google.maps.event.addDomListener(window, 'load', initialize);
</script> </head>
<body onload="initialize()">
<div id="map_canvas"></div>
Einkaufen <input type="checkbox" id="layer0" onclick="toggleLayer(0)" checked>
Entspannen <input type="checkbox" id="layer1" onclick="toggleLayer(1)" checked>
Essen <input type="checkbox" id="layer2" onclick="toggleLayer(2)" checked>
</body>

Grateful for any help!
Anne


回答1:


Your map variable is local to the initialize function and is not available in the global scope where the checkbox handlers execute:

var map = null;

function initialize() {  

// removed code for clarity

map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

working example



来源:https://stackoverflow.com/questions/16799912/toggle-kml-layer-on-styled-map-only-works-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!