【问题标题】:geoJSON bindPopup examplegeoJSON bindPopup 示例
【发布时间】:2021-04-01 18:18:12
【问题描述】:

尝试覆盖正在工作的 geojson 数据,但我希望用户能够单击一个区域并弹出显示该区域的详细信息。使用传单网站上的示例

L.geoJSON(data, {
    style: function (feature) {
        return {color: feature.properties.color};
    }
}).bindPopup(function (layer) {
   return layer.feature.properties.description;
}).addTo(map);

leaflet example

我收到关于 layer.feature 不是 L.Layer 类型属性的错误。我也将 @types/leaflet 用于 angular/typescript 类型,但它没有在其中列出。

如何访问 geojson 的特性属性来绑定弹出窗口?或者说真的,我想做一个 onClick 事件来获取信息来设置表单数据。

提前致谢。

编辑 1: 所以我想出了一个可行的方法。

在准备好地图时调用的函数中,我将 layer 设置为键入 any 而不是键入 L.Layer,因为该属性直到运行时才存在。

this.geojson = L.geoJSON(this.data);
this.geojson.bindPopup((layer: any) => {
    return layer.feature.properties ... ;
}

这将使用来自 geojson 数据的数据提供我正在寻找的弹出窗口。接下来将代替 bindPopup 使用事件来设置表单数据。

【问题讨论】:

    标签: angular leaflet ngx-leaflet


    【解决方案1】:

    您可以使用 geoJson(Leaflet) 的 onEachFeature 方法在每个图层上绑定 Popup,您可以在其中访问图层和功能道具,并使用该方法您可以使用功能道具在图层上绑定弹出窗口以显示内容。

          onEachFeature: function (feature, layer) {
            layer.addEventListener("click", () => {
              layer.bindPopup(feature.properties.name);
            });
          }
        });
    

    链接https://codesandbox.io/s/geojson-bind-popup-548yv?file=/src/leaflet.js进行演示。

    在该文件中,您可以看到使用我们渲染多边形的 geojson.json 文件。 因此,在单击每个多边形时,我们会绑定显示城市名称的弹出窗口

    【讨论】:

    • 我在我的问题中的编辑中得到了弹出窗口。我将如何通过点击事件获取价值?这就是我接下来要弄清楚的,所以我可以将点击的区域设置为表单数据中的选项。
    • 您可以在单击区域或图层时捕获您的特征数据,然后将其分配给可用于填充表单数据的变量
    【解决方案2】:

    如果GeoJSON结构是这样的:

    {
      "type": "FeatureCollection",
      "features": [
        {
          "type": "Feature",
          "properties": {   
            "Prop1": 1,
            "Prop2": "name1"
          },
          "geometry": {
            "type": "Point",
            "coordinates": [
              79.8046875,
              54.97761367069628
            ]
          }
        },
        {
          "type": "Feature",
          "properties": {   
            "Prop1": 2,
            "Prop2": "name2"
          },
          "geometry": {
            "type": "Point",
            "coordinates": [
              107.22656249999999,
              30.751277776257812
            ]
          }
        }
      ]
    }
    

    你可以像这样创建一个 Angular 接口:

    interface Geojson {
      type: string;
      features: {
        type: string,
        properties:{
          Prop1:number,
          Prop2:string
        }
      }[]
    }
    

    只需将layer: any 替换为layer: Geojson。您不需要为所有 GeoJSON 对象创建接口。它应该只涵盖您正在寻找的元素。所以你甚至可以像这样缩短它:

    interface Geojson {
      features: {
        properties:{
          Prop1:number,
          Prop2:string
        }
      }[]
    }
    

    【讨论】:

    • 有趣。我得试试这个。宁愿使用layer: Geojsonlayer: any
    • 当然可以。在 Angular 世界中,使用 any 不是一个好习惯。此外,如果这是正确答案,请不要忘记点击绿色勾号。
    猜你喜欢
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多