use*_*094 2 javascript geocoding leaflet reactjs react-leaflet
我想使用react-leaflet并在其顶部添加一个地理编码器字段。我发现leaflet-control-geocoder这看起来很棒,但没有反应包装器可以将其与反应传单一起使用。有人做过这个并且可以分享一个沙箱吗?或者也许它存在于 GitHub 上,但我没有使用正确的关键字?
感谢您的帮助,最诚挚的问候
对于react-leaflet v.3.x
创建您自己的包装器:
安装leaflet-control-geocoder
并导入其依赖项:
import "leaflet-control-geocoder/dist/Control.Geocoder.css";
import "leaflet-control-geocoder/dist/Control.Geocoder.js";
Run Code Online (Sandbox Code Playgroud)
使用演示中的代码构建您的 React 包装器。
function LeafletControlGeocoder() {
const map = useMap();
useEffect(() => {
var geocoder = L.Control.Geocoder.nominatim();
if (typeof URLSearchParams !== "undefined" && location.search) {
// parse /?geocoder=nominatim from URL
var params = new URLSearchParams(location.search);
var geocoderString = params.get("geocoder");
if (geocoderString && L.Control.Geocoder[geocoderString]) {
geocoder = L.Control.Geocoder[geocoderString]();
} else if (geocoderString) {
console.warn("Unsupported geocoder", geocoderString);
}
}
L.Control.geocoder({
query: "",
placeholder: "Search here...",
defaultMarkGeocode: false,
geocoder
})
.on("markgeocode", function (e) {
var latlng = e.geocode.center;
L.marker(latlng, { icon })
.addTo(map)
.bindPopup(e.geocode.name)
.openPopup();
map.fitBounds(e.geocode.bbox);
})
.addTo(map);
}, []);
return null;
}
Run Code Online (Sandbox Code Playgroud)
将其导入为 MapContainer 子项
<MapContainer center={position} zoom={13} style={{ height: "100vh" }}>
...
<LeafletControlGeocoder />
</MapContainer>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4487 次 |
| 最近记录: |