Javascript 寻找在地图上隐藏或显示街道的正确方法
我试图在谷歌地图上隐藏/显示道路图层,这对我来说很有用,但正如你所看到的,代码在添加样式中重复了很多次! 关于: 你们能不能看一下演示,让我看看有什么更好的方法来实现这一点?没有多次重复这种风格Javascript 寻找在地图上隐藏或显示街道的正确方法,javascript,jquery,google-maps,google-maps-api-3,Javascript,Jquery,Google Maps,Google Maps Api 3,我试图在谷歌地图上隐藏/显示道路图层,这对我来说很有用,但正如你所看到的,代码在添加样式中重复了很多次! 关于: 你们能不能看一下演示,让我看看有什么更好的方法来实现这一点?没有多次重复这种风格 谢谢您可以将样式保存在变量中,例如: var stylesOff = [{ "featureType": "road", "stylers": [{ "visibility": "off" }] }]; var stylesOn = [{ "fe
谢谢您可以将样式保存在变量中,例如:
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
道路
POI
地方
水
基于此,当其中一个复选框更改时,您可以构建样式数组:
// 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
});
});
//获取所有样式控件
变量控件=$('.styles控件');
$('.styles控件').change(函数(){
风格=[];
//循环浏览样式控件
对于(变量i=0;i
您好,Upsidown先生,谢谢您的回复,我喜欢您这样做,但我注意到了一个我以前没有提到的问题(对不起!我的错!)。关键是,如果我们只有一个选择“开”或“关”道路的复选框,那么这个解决方案就完美了,但是如果我们有多个选择,比如说街道、行政管理,甚至水呢。如果未选择一个或某些样式,如何打开或关闭所有样式?非常感谢这正是我想要的
// 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
});
});