Skip to content

Instantly share code, notes, and snippets.

@Faria-Ejaz
Last active May 20, 2024 12:14
Show Gist options
  • Save Faria-Ejaz/816263a04264bdb516cd23f98e69ad79 to your computer and use it in GitHub Desktop.
Save Faria-Ejaz/816263a04264bdb516cd23f98e69ad79 to your computer and use it in GitHub Desktop.
react Leaflet Map with Auto-suggest Search #leaflet #react-leaflet #search
/** @format */
import { Map, TileLayer, Marker, Popup } from "react-leaflet";
import React, { useEffect, useState, useRef } from "react";
import { geosearch } from "esri-leaflet-geocoder";
import "leaflet/dist/leaflet.css";
import "esri-leaflet-geocoder/dist/esri-leaflet-geocoder.css";
import L from "leaflet";
function MapView(props) {
const mapRef = useRef();
const [position, setPosition] = useState([50, 10]);
const [icon, setIcon] = useState();
useEffect(() => {
const { current = {} } = mapRef;
const { leafletElement: map } = current;
if (!map) return;
const control = geosearch();
control.addTo(map);
control.on("results", handleOnSearchResuts);
let greenIcon = L.icon({
iconUrl:
"https://upload.wikimedia.org/wikipedia/commons/c/c9/Font_Awesome_5_solid_map-marker-alt.svg",
shadowUrl:
"https://upload.wikimedia.org/wikipedia/commons/c/c9/Font_Awesome_5_solid_map-marker-alt.svg",
iconSize: [20, 30],
// iconAnchor: [22, 94],
// popupAnchor: [-3, -76],
shadowSize: [20, 30],
// shadowAnchor: [22, 94],
});
setIcon(greenIcon);
return () => {
control.off("results", handleOnSearchResuts);
};
}, []);
/**
* handleOnSearchResuts
* @param {object} data Results object from esri-leaflet-geocoder
*/
const handleOnSearchResuts = (data) => {
console.log("Search results", data);
setPosition([data.latlng.lat, data.latlng.lng]);
}
return (
<Map
ref={mapRef}
center={position}
zoom={6}
style={{ width: "400px", height: "400px" }}
>
<TileLayer url="http://{s}.tile.osm.org/{z}/{x}/{y}.png" />
<Marker position={position} icon={icon}>
<Popup>Popup for any custom information.</Popup>
</Marker>
</Map>
);
}
export default MapView;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment