如何更改Google地图中的某些多边形样式
问题描述:
我试图让两组多边形表现为不同的图层,允许独立切换图层的可见性。例如,当添加geojson中没有'rgb'属性的多边形时,我想不必为已绘制的多边形重新定义样式。如何更改Google地图中的某些多边形样式
我试图不指定任何返回值的多边形,我不想改变,但它离开了多边形与默认的谷歌地图样式,尽管他们的初始风格。
var mapFrame = frames.getAtcMap(index);
// load the geojson
var file = "Council_Districts_2016.geojson";
$.get(file, function(data){
var geojson = GetParsedForGoogleMaps(data);
mapFrame.googleMap.data.addGeoJson(geojson);
mapFrame.googleMap.data.setStyle(function(feature) {
if(typeof feature.getProperty('rgb')==="undefined"){
return {
fillColor: "white",
fillOpacity:0,
strokeColor:"blue",
strokeOpacity: 0.8,
strokeWeight: 2.5,
zIndex:11
};
};
});
});
我明白setStyle
重新定义了整个地图的风格,但他们是无论如何重新定义样式只有一套多边形的?
答
谷歌搜索我发现主要有两种可能性。
使用不同的层
更一般的和永久的解决方案。它只是为第二组多边形定义了一个新的独立层。它是如何定义一个谷歌地图上的多个层的好例子:
// global name of the layer to allow later reference
var layerCouncilDistricts = {};
function addOnTopCouncilDistricts(elem){
// identification of the map in my multiple maps environment
var index = elem.id.replace("addCouncilDistrict","");
var mapFrame = frames.getAtcMap(index);
// construct the new layer
layerCouncilDistricts = new google.maps.Data(mapFrame);
// attach it to a google map
layerCouncilDistricts.setMap(mapFrame.googleMap);
// load the geojson
var file = "Council_Districts_2016.geojson";
$.get(file, function(data){
// parse the geojson
var geojson = GetParsedForGoogleMaps(data);
// add the geojson to the layer
layerCouncilDistricts.addGeoJson(geojson);
// set the style of the layer
layerCouncilDistricts.setStyle(function(feature){
return {
fillColor: "white",
fillOpacity:0,
strokeColor:"blue",
strokeOpacity: 0.8,
strokeWeight: 2.5,
zIndex:11
}});
});
}
对于临时变化
第二种方法是精细的临时变化,但该组的从别人特征不分离。可以使用foreach()
of the data class查看所有功能并覆盖样式。在我的例子中是这样的:
// examine each feature
mapFrame.googleMap.data.forEach(function(feature) {
// is feature to be changed
if(typeof feature.getProperty('rgb')==="undefined") {
// override existing style for this feature
overrideStyle(feature,{
fillColor: "white",
fillOpacity:0,
strokeColor:"blue",
strokeOpacity: 0.8,
strokeWeight: 2.5,
zIndex:11
});
}
}
它很好用,并且允许进一步与图层进行完全独立于其他项目的交互。
@duncan我发布了更多的代码,但我不确定如何在'Polygon.setOptions'中定义“Polygon”。将非常感谢一个片段显示如何使用geojson导入的东西setOptions – cmbarbu 2015-04-03 11:58:07
是的,我在错误的轨道上,我删除了我以前的评论。您的代码看起来与https://developers.google.com/maps/documentation/javascript/datalayer上的示例类似。 – duncan 2015-04-03 12:07:31