首页 > 解决方案 > 如何使用外部选择下拉组件在 React Leaflet Map 上选择区域

问题描述

所以问题是如何使用外部Select下拉组件选择特定区域:

 <div className="Map">
  <Select
    onChange={setArea}
    size={"large"}
    className="Map-areaSelector"
    value={selectedArea}
  >
    {areaList}
  </Select>
  {colors && (
    <MapContainer center={getCenter()} zoom={getZoom()}>
      <>
        <GeoJSON
          style={setColor}
          data={germanyDis}
          onEachFeature={onEachArea}
        />
        <NewLegend arr={gradient} />
      </>
    </MapContainer>
  )}
</div>

想要这样的结果,而我从Select右上角的下拉列表中选择城市

在此处输入图像描述

目前我只能选择区域,而我直接单击该区域上的地图(使用onEachFeature功能)但无法理解如何连接Select组件以实现相同的功能,同时从下拉列表中选择区域。

标签: javascriptreactjsleafletgeojsonreact-leaflet

解决方案


如果我们假设您的下拉列表中有地区名称,并且与 geojson 中包含的名称相同,也就是地图实例,select那么onChange您将不得不使用 json ref 来查找具有所选地区名称的图层然后对其执行任何操作,例如打开其弹出窗口或缩放到所选图层。

const geoJsonRef = useRef();
const [selectValue, setSelectValue] = useState("");
...
const handleDistrictChange = (e) => {
    const newDistrict = e.target.value;
    setSelectValue(newDistrict);

    if (!newDistrict) return;

    const layer = geoJsonRef.current
      .getLayers()
      .find((layer) => layer._popup._content === newDistrict);
    layer.openPopup();
    map.fitBounds(layer.getBounds());
};

并在您的 GeoJSON 组件上添加 ref 以及从 MapContainer 获取地图实例。

<>
  <MapContainer
      center={position}
      zoom={13}
      style={{ height: "80vh" }}
      whenCreated={setMap}
   >
   ...
  {geoJSON && (
     <GeoJSON
        data={geoJSON}
        onEachFeature={handleEachFeature}
        ref={geoJsonRef}
     />
   )}
  </MapContainer>
  <select value={selectValue} onChange={handleDistrictChange}>
     <option value="">Select a district</option>
     {geoJsonRef.current
        ?.getLayers()
        .map((layer) => layer._popup._content)
        .map((district, index) => (
           <option key={`district-${index}`} value={district}>
            {district}
           </option>
      ))}
  </select>
 </>

你可以在这个演示中看到更多


推荐阅读