如何在Google MAP API中为多次addGeoJson调用设置不同颜色?
解决Google Maps API多GeoJSON路线不同颜色的问题
问题原因
map.data.setStyle()是全局样式设置,每次调用都会覆盖所有已添加到map.data的要素样式,所以你循环里最后一次设置的颜色会应用到所有路线。
解决方案1:给要素添加自定义属性,用回调函数动态设置样式
给每个GeoJSON的要素添加颜色属性,再通过setStyle的回调函数读取属性值来设置对应颜色,只需要调用一次全局样式设置:
let colors = ['#fcba03', '#035afc', '#03fc56']; // 循环添加GeoJSON,同时给每个要素标记颜色属性 for(let i = 0; i < self.opts.geojson_array.length; ++i){ try { // 复制原GeoJSON避免修改源数据 const geoJson = JSON.parse(JSON.stringify(self.opts.geojson_array[i])); const targetColor = colors[i%colors.length] || self.opts.geojson_stroke_color || "#3b5aa8"; // 给每个feature添加自定义颜色属性 geoJson.features.forEach(feature => { feature.properties = feature.properties || {}; feature.properties.routeColor = targetColor; }); map.data.addGeoJson(geoJson); } catch(error){ this.error = error; console.log(error); } } // 用回调函数为每个要素设置对应颜色 map.data.setStyle(feature => { return { strokeColor: feature.getProperty('routeColor') }; });
解决方案2:利用addGeoJson返回值,单独覆盖要素样式
map.data.addGeoJson()会返回本次添加的Feature对象数组,直接用overrideStyle给这些要素单独设置样式,不会影响全局:
let colors = ['#fcba03', '#035afc', '#03fc56']; for(let i = 0; i < self.opts.geojson_array.length; ++i){ try { // 获取本次添加的所有要素 const addedFeatures = map.data.addGeoJson(self.opts.geojson_array[i]); const targetColor = colors[i%colors.length] || self.opts.geojson_stroke_color || "#3b5aa8"; // 逐个覆盖要素样式 addedFeatures.forEach(feature => { map.data.overrideStyle(feature, { strokeColor: targetColor }); }); } catch(error){ this.error = error; console.log(error); } }
两种方案对比
- 方案1适合需要后续动态修改样式的场景,只需修改要素的
routeColor属性即可更新样式 - 方案2更直接,无需修改GeoJSON结构,适合一次性设置样式的场景
内容的提问来源于stack exchange,提问作者relipse
相关产品推荐
相关产品推荐

