我使用 kboul 代码在 React-leaflet v3.1.0 中添加了一个搜索框,但我收到此错误“TypeError: Object(...) is not a function”,可能是因为我已经在我的 MapContainer 中设置了一个地图实例选项“whenCreated”。我可以使用我在 MapContainer 中定义的同一个地图实例吗?
这是我的代码。感谢帮助!
import React, { useState, useEffect, useMap } from "react";
import { MapContainer, Marker, Popup, TileLayer } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet-geosearch/dist/geosearch.css";
import { GeoSearchControl, OpenStreetMapProvider } from "leaflet-geosearch";
import SearchForm from '../SearchForm'
import "./map.css";
import icon from "./constants";
const zoom = 5;
function Map({ regionCoord, regionName }) {
const [map, setMap] = useState(null);
const [position, setPosition] = useState()
function FlyToButton() {
const onClick = () => {
map.locate().on("locationfound", function (e) {
setPosition(e.latlng);
map.flyTo(e.latlng, map.getZoom());
});
}
// map.flyTo(regionCoord, zoom);
return <button className="button" onClick={onClick}>Locate on click</button>;
}
function LeafletgeoSearch() {
const map = useMap();
useEffect(() => {
const provider = new OpenStreetMapProvider();
const searchControl = new GeoSearchControl({
provider,
marker: {
icon
}
});
map.addControl(searchControl);
return () => map.removeControl(searchControl);
// eslint-disable-next-line
}, []);
return null;
}
return (
<>
{/* create the button to geolocate */}
<FlyToButton />
{/* open the component SearchForm to create an input field to look for a city*/}
<SearchForm />
{/* create a map with coordinates from props */}
{regionCoord && (
<MapContainer
center={regionCoord}
zoom={zoom}
style={{ height: "90vh" }}
whenCreated={setMap}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={regionCoord} icon={icon}>
<Popup>{regionName}</Popup>
</Marker>
{/* if position is located put a marker on new coordinates */}
{position && (
<Marker position={position} icon={icon}>
<Popup>Vous êtes ici</Popup>
</Marker>
)}
<LeafletgeoSearch />
</MapContainer>
)}
</>
);
}
export default Map;