mapbox-gl-geocoder
mapbox-gl-geocoder copied to clipboard
Reverse Geocoding Event
Is there a way in reverse geocoding that every click on marker that will result the reverse geocoding ?
example code
const map = useRef(null);
const marker = useRef(null);
const mapGeocoder = useRef(null);
const mapContainer = useRef(null);
const [latLng, setLatLng] = useState(value || {});
const className = `map-container ${inputClassName}`;
useEffect(() => {
// Initializes the map only once
if (map.current) return;
map.current = new MapboxGL.Map({
zoom: 9,
minzoom: 3,
maxzoom: 9,
dragRotate: false,
container: mapContainer.current,
center: [120.984222, 14.599512],
maxBounds: [
[115, 4],
[128, 21],
],
style: "mapbox://styles/mapbox/outdoors-v11?optimize=true",
});
// Integrates Geocoder
mapGeocoder.current = new MapboxGeocoder({
marker: false,
countries: "ph",
mapboxgl: MapboxGL,
accessToken: MapboxGL.accessToken,
types: "country, region ,postcode, district, place, locality ,neighborhood ,address",
reverseGeocode: true,
draggable: true,
color: "#FDBE2C",
});
map.current.addControl(mapGeocoder.current);
// Creates Marker
marker.current = new MapboxGL.Marker({
draggable: true,
color: "#FDBE2C",
});
// Input Persistence
if (Object.keys(latLng).length) {
const { lng, lat } = latLng;
marker.current.setLngLat([lng, lat]).addTo(map.current);
}
// mapbox revergeocoding result
mapGeocoder.current.on("result", (e) => {
console.log(e);
// const { lng, lat } = e.result.center;
var lng = e.result.center[0];
var lat = e.result.center[1];
setLatLng({ lng, lat });
marker.current.setLngLat([lng, lat]).addTo(map.current);
setFieldValue(fieldName, { lng: lng, lat: lat });
});
// Creates click listener. // when click that will also return the expected sample values is in the image
map.current.on("click", (e) => {
// map.current.addControl(mapGeocoder.current);
console.log("e", e);
// const { lng, lat } = e.lngLat;
// console.log({ lng, lat })
// setLatLng({ lng, lat });
// marker.current.setLngLat([lng, lat]).addTo(map.current);
// setFieldValue(fieldName, { lng: lng, lat: lat });
});
});