如何处理数据集上 react-leaflet v3 中的事件?

How to handle events in react-leaflet v3 on a dataset?

我一直在使用 react-leaflet v3 来绘制给定半径内的医院。我有一个从端点检索该信息的组件,即以下代码中的 Hospitals 组件:

import React from "react";
import { MapContainer, TileLayer } from "react-leaflet";
import Hospitals from "./Hospitals";

export default class MyMap extends React.Component {
  
  constructor(props) {
    super(props);    
    this.state = {
      id: 0,
      lat: -23.550519,
      lng: -46.633309,
      zoom: 12
    };
  }

  render() {
    const position = [this.state.lat, this.state.lng];
    return (
      <MapContainer center={position} zoom={this.state.zoom}>
        <Hospitals />
        <TileLayer
          attribution="&amp;copy <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
      </MapContainer>
    );
  }
}

所以,这真是太棒了!

检索数据集并在地图上显示标记,每个标记对应上述数据集中的一家医院。

现在,我想在每个标记上应用事件以显示有关每个标记的信息,即名称、地址和每家医院可用的 ICU 数量。

如何才能在 MapContainer 中的数据集上应用事件? documentation 并没有详尽无遗,我在尝试匹配目前为止用谷歌搜索过的几个例子时遇到了错误。

我找到了这个 of ,但是当我尝试应用相同的逻辑时,我发现了如下错误:

React Hook "useMap" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function

我已经创建了一个组件来处理地图上的事件。然后我将该组件连接到 MapContainer。显然它不起作用,因为它不适用于数据集。

编辑: 添加医院的组件代码

import React from "react";
import { GeoJSON } from "react-leaflet";
const overpass = require("query-overpass");

export default class Hospitals extends React.Component {

 constructor(props) {
   super(props);
   this.state = {
     geojson: undefined,
     map: undefined,
     setMap: undefined
   };
 }

 render() {
   return this.state.geojson ? <GeoJSON data={this.state.geojson} /> : null;
 }

 componentDidMount() {
   const query = `[out:json];(way[healthcare~"^(hospital|clinic)$"](around:50000, -23.550519, -46.633309);\
                              relation[healthcare~"^(hospital|clinic)$"](around:50000, -23.550519, -46.633309););\
                              out center;>;out skel qt;`;
   const options = {
     flatProperties: true
   };
   overpass(query, this.dataHandler, options);
 }

 dataHandler = (error, osmData) => {
   if (!error && osmData.features !== undefined) {
     this.setState({ geojson: osmData });
   }
 };

}

此组件使用查询立交桥库来检索 OpenStreetMaps 中可用的信息。在这种特殊情况下,医疗中心的信息采用 geojson 格式。

要考虑的一个选项是通过 Marker.bindPopup 方法将弹出窗口绑定到标记点击。就 react-leaflet 库而言,GeoJSON 组件公开了 onEachFeature 事件,该事件在每个功能上被调用并且可以在其中初始化弹出窗口。

这是一个修改后的 Hospitals 组件,它演示了如何将弹出窗口绑定到标记点击:

class Hospitals extends React.Component {
  handleEachFeature(feature, layer) {    
    const popupContent = feature.properties.hospitalDesc; //it is assumed  GeoJSON feature contains hospitalDesc property
    layer.bindPopup(popupContent);
  }

  render() {
    return (
      <GeoJSON data={hostpitalData} onEachFeature={this.handleEachFeature} />
    );
  }
}

Here is a demo供大家参考