javascript - 如何使用外部选择下拉组件在 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
组件以实现相同的功能,同时从下拉列表中选择区域。
解决方案
如果我们假设您的下拉列表中有地区名称,并且与 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>
</>
你可以在这个演示中看到更多
推荐阅读
- python - 如何找到矩阵中某个位置的相邻元素的最小元素
- typescript - 如何配置 tsconfig.json 来获得这个输出?
- python - ManagedIdentityCredential 身份验证不可用,未找到托管身份端点
- node.js - http-proxy-middleware 异步更改标头
- ios - 如何将字符串转换为绑定
在 DatePicker SwiftUI 中? - c# - 如何获取程序集的目标框架?
- c# - 无法通过 httpclient 调用 web api
- c# - How to create a UserControl which accepts adding child elements in XAML
- c# - C# - 从 MySQL 读取
- ios - 如何更新服务器上的 AAACertificateServices 以发送 apns?