如何通过Google Maps API访问嵌套GeoJSON数据中的color属性?
解决Google Maps API中嵌套JSON属性的访问问题
嘿,这问题我之前也踩过坑!你拿不到color值的核心原因是:它并不是properties下的直接属性,而是嵌套在category这个子对象里的,所以直接用feature.getProperty('color')肯定找不到目标值。
正确的访问方式
你需要先通过feature.getProperty('category')拿到整个category对象,再从里面提取color以及其他样式属性。这里给你修改后的代码,还加了容错处理,避免因为category不存在导致页面报错:
map.data.setStyle(function (feature) { // 先获取嵌套的category对象 const category = feature.getProperty('category'); // 从category中提取样式属性,同时设置默认值兜底 const strokeColor = category?.color || '#000000'; const strokeWeight = category?.['stroke-width'] || 3; const strokeOpacity = category?.['stroke-opacity'] || 1; return { strokeColor: strokeColor, strokeWeight: strokeWeight, strokeOpacity: strokeOpacity }; });
关键细节说明
feature.getProperty()只能直接获取properties下的一级属性,对于嵌套的子属性,必须先拿到父对象再访问。- 我用了可选链操作符
?.来安全访问嵌套属性,如果category为null或undefined,会直接返回undefined,再通过||设置默认值,让代码更健壮。 - 注意
stroke-width这种带连字符的属性,必须用方括号['stroke-width']的方式访问,不能用点语法category.stroke-width(会被JS解析成减法运算,直接报错)。
另外顺便提一句,你提供的JSON里coordinates数组好像没闭合([ [ 0, 0 ]这里少了一个]),实际使用的时候要确保JSON格式是正确的哦!
内容的提问来源于stack exchange,提问作者user144271
相关产品推荐
相关产品推荐

