【问题标题】:Is it possible to add custom property to an Openlayers VectorLayer and later access it when a feature is selected?是否可以将自定义属性添加到 Openlayers VectorLayer,然后在选择功能时访问它?
【发布时间】:2020-12-26 06:59:19
【问题描述】:

我在初始化图层时尝试向我的矢量图层添加自定义属性,因为源没有我需要的所有数据。

如果我对 API 文档的理解正确,应该可以,但我不知道在地图上的 VectorLayer 上选择要素时如何返回自定义属性的值。

我正在使用以下代码初始化 VectorLayer:

const someVectorLayer = new VectorLayer({
  source: new VectorSource({
    format: new GeoJSON(),
    url: "https://example.com/api/v1/foobar",
  }),
  customProperty: 'foobar'
});

我正在尝试访问该属性以设置我的 fetch url,以便在单击该功能时从正确的位置获取内容:

function onSelect(e) {
  const featureValues = e.target.getFeatures().getArray()[0];
  const featureId = featureValues.get('id');
  const featureCustomProperty = featureValues.get("customProperty");
  const fetchUrl = `https://example.com/api/v1/${featureCustomProperty}/${featureId}`;

  fetch(fetchUrl)
    .then((response) => response.json())
    .then((data) => console.log(data));
}

感谢我在该主题上获得的任何帮助。显然我还不是 Openlayers 专家。 :)

【问题讨论】:

    标签: javascript openlayers


    【解决方案1】:

    在向地图添加要素之前使用loader 设置属性。

    var vectorSource = new Vector({
      format: new GeoJSON(),
      loader: function (extent, resolution, projection) {
        var url = '***'
        fetch(url).then(data => {
            // format data to features , this step depends on your actual situation
            const features = new GeoJSON().readFeatures(data)
            features.forEach((feature, index) => {
                // add a custom properties to feature
                feature.setProperties({
                    index
                })
            });
            vectorSource.addFeatures(features)
        })
      },
      strategy: bbox,
    })
    
    function onSelect(e) {
      '''
      const props = selectedFeature.getProperties()
    
      '''
    }
    

    【讨论】:

    • 这似乎对我有帮助,谢谢! :)
    【解决方案2】:

    您似乎使用了错误的变量来访问您的自定义属性。

    selectedFeatureValues 应该是 someVectorLayer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-18
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多