寻找在地图上隐藏或显示街道的正确方法

我试图在这个Demo上的Google Map上隐藏/显示Roads图层, 这对我来说很有用,但是你可以看到代码在添加样式时多次重复! 上:

map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); map.set('styles', [{ "featureType": "road", "stylers": [{ "visibility": "off" }] }]); $('input:checkbox').change(function () { if ($(this).is(':checked')) { map.set('styles', [{ "featureType": "road", "stylers": [{ "visibility": "on" }] }]); } else { map.set('styles', [{ "featureType": "road", "stylers": [{ "visibility": "off" }] }]); } }); 

你能不能看一下demo,让我有什么更好的方法来实现这个目标? 没有多次重复这种风格?!

谢谢

您可以将样式保存在变量中,例如:

 var stylesOff = [{ "featureType": "road", "stylers": [{ "visibility": "off" }] }]; var stylesOn = [{ "featureType": "road", "stylers": [{ "visibility": "on" }] }]; var myOptions = { zoom: 16, center: latlng, disableDefaultUI: true, mapTypeId: google.maps.MapTypeId.ROADMAP, styles: stylesOff }; map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); $('input:checkbox').change(function () { if ($(this).is(':checked')) { map.setOptions({ styles: stylesOn }); } else { map.setOptions({ styles: stylesOff }); } }); 

注意使用setOptions ,这是更改地图选项的文档化方法。

编辑:

正如您在评论中所说,您想要独立切换多个样式,这是一个解决方案。

它使用输入data属性来标识复选框所指的样式。

  Roads  POI  Localities  Water 

基于此,您可以在其中一个复选框更改时构建样式数组:

 // Get all styles controls var controls = $('.styles-control'); $('.styles-control').change(function () { styles = []; // Loop through styles controls for (var i = 0; i < controls.length; i++) { if ($(controls[i]).is(':checked')) { // Push the feature type to the styles array // The feature type is based on the input data-style attribute styles.push({ "featureType": $(controls[i]).data('style'), "stylers": [{ "visibility": "on" }] }); } else { styles.push({ "featureType": $(controls[i]).data('style'), "stylers": [{ "visibility": "off" }] }); } } map.setOptions({ styles: styles }); }); 

JSFiddle演示