我正试图在This Demo上的Google地图上隐藏/显示道路图层,这对我有用,但正如您所看到的,代码在添加样式时多次重复! 于:
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,让我知道一个更好的方法来实现这个目标吗?没有多次重复这种风格?!
由于
答案 0 :(得分:0)
您可以将样式保存在变量中,例如:
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
属性来标识复选框所指的样式。
<input type="checkbox" class="styles-control" data-style="road" checked="checked"> Roads
<input type="checkbox" class="styles-control" data-style="poi" checked="checked"> POI
<input type="checkbox" class="styles-control" data-style="administrative.locality" checked="checked"> Localities
<input type="checkbox" class="styles-control" data-style="water" checked="checked"> 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
});
});