堆叠地图样式(Google Maps API)
所以我找不到答案,但是我知道这是可能的,因为我已经看过了.
So I can't find an answer to this, but I know it's possible, because I've seen it.
我试图在自定义样式的地图上切换特定的样式选项,而不必重新初始化地图,也不会丢失任何固定的针脚或搜索到的位置.
I'm trying to toggle specific style options on my custom styled map without having to reinitialize the map and losing any pins dropped, or locations searched.
例如,关闭和打开道路标签.我以一种不客气的方式实现了这一点,在该方式中,我创建了两个完整的样式对象,然后使用map.setMapTypeId
在它们之间进行切换.
For example, turning off and on road labels. I have accomplished this in a hacky way where I've created two complete style objects, and I switch between them with map.setMapTypeId
.
此问题是a)非常重复,并且b)我想切换的选项很多,因此不必为可切换选项的每个变体制作样式表现实的.
The problem with this is that a) it's very repetitive, and b) I have a lot of options I want to be able to toggle, so having to make styled sheets for every single variation of my toggle-able options is not realistic.
一种现实的解决方案是能够将对象合并到我的样式选项上,而不必完全撤消以前的样式选项.
The realistic solution is to be able to concat objects on to my style options without undoing the previous style options entirely.
例如
{
'featureType': 'landscape',
'elementType': 'geometry',
'stylers': [{'color': '#eaeaea'}]
}
然后串联此样式:
{
'featureType': 'all',
'elementType': 'labels',
'stylers': [{'visibility': 'off'}]
}
我不能只更改原始对象,因为样式要等到重新加载地图后才能采用,这会导致我丢失标记和地图位置.
I can't just alter the original object because the styles won't take until the map is reloaded, causing me to lose my markers and map position.
我需要它来执行类似map.setMapTypeId('styled_map', 'styled_map_2');
这样的功能,在此我的样式才被编译.
I need it to function something like map.setMapTypeId('styled_map', 'styled_map_2');
where my styles are just compiled.
希望我已经解决了这个难题.
Hopefully I've made the dilemma clear.
// create a variable for the element you want an option for
var styleOptionCityLabels = {
featureType: 'administrative',
elementType: 'labels',
stylers: [{'visibility': 'on'}]
};
// create a variable for your map styles that pulls any option variables you have
var mapStyle = [styleOptionCityLabels];
// get the checkbox element you want to control your toggle
var cityCheck = $('#city-labels-checkbox');
// apply a click listener to the box
cityCheck.on('click', function(){
// check if the box is checked
if ($(cityCheck).is(':checked')) {
// change the desired style
styleOptionCityLabels.stylers = [{'visibility': 'on'}];
} else {
// change the desired style
styleOptionCityLabels.stylers = [{'visibility': 'off'}];
}
// call the setOptions method to reload the altered styles
map.setOptions({styles: mapStyle});
});