在Mapbox中显示嵌套GeoJson的属性

时间:2018-10-17 16:53:13

标签: nested geolocation mapbox geojson mapbox-gl-js

我无法查询从geojson源导入并显示在地图框地图上的嵌套属性功能。

我可以通过点击监听器获得该功能,但是一旦属性被嵌套,该对象就会被表示为字符串

{
 ...
  properties: {
   address: "{"place":"Bern","street":"Fischerweg","street_nr":"11","zip":"3012"}"
   price: 4500
 }
}

因此,单击后,我只能在弹出窗口中显示未嵌套的属性。

我的代码:

const features = this.queryRenderedFeatures(e.point, {
        layers: ['unclustered-point']
      });

console.log(feature.properties.price) --> 4500
console.log(feature.properties.address) --> string instead of object {"place":"Bern","street":"Fischerweg","street_nr":"11","zip":"3012"}
console.log(feature.properties.address.street) --> undefined (--> NOT WORKING because of nested property)


const popup = new mapboxgl.Popup({offset: [0, -15]})
   .setLngLat(feature.geometry.coordinates)
   .setHTML('<h3>Price: ' + feature.properties.price + '</h3>
                  <p>Street: ' + feature.properties.address.street + '</p>')--> NOT WORKING because of nested property
   .setLngLat(feature.geometry.coordinates)
   .addTo(map);

我读到您可以使用表达式访问嵌套属性,但是如何将表达式应用于弹出窗口的html? 有什么方法可以访问嵌套属性,还是必须重新设计geojson的结构?

我们非常感谢您的帮助!非常感谢你,

关于西蒙

1 个答案:

答案 0 :(得分:0)

由于属性值已转换为JSON字符串,因此需要反向转换:

Object.keys(feature.properties).forEach(function(key) {
  feature.properties[key] = JSON.parse(feature.properties[key]);
});

[https://jsfiddle.net/s1d7hL82/]