Reputation: 33
I want to use react-leaflet
and to add a geocoder field on top of it. I found leaflet-control-geocoder
which seems great but no react wrapper to use it with react-leaflet. Anyone has done this and can share a sandbox? Or maybe it exists on GitHub and i did not use the right keywords ?
Thanks for your help, Best regards
Upvotes: 3
Views: 5617
Reputation: 14570
For react-leaflet
v.3.x
Create your own wrapper:
install leaflet-control-geocoder
and import its dependencies:
import "leaflet-control-geocoder/dist/Control.Geocoder.css";
import "leaflet-control-geocoder/dist/Control.Geocoder.js";
Use the code from demo to build your React wrapper.
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;
}
Import it as MapContainer child
<MapContainer center={position} zoom={13} style={{ height: "100vh" }}>
...
<LeafletControlGeocoder />
</MapContainer>
Upvotes: 8