put the geocoder creation into its one useeffect so that it doesn't create duplicates on the map
This commit is contained in:
parent
3d7573b65e
commit
52c762fa74
1 changed files with 19 additions and 12 deletions
|
|
@ -1,6 +1,6 @@
|
|||
import { ControlPosition, useMap } from "react-map-gl/mapbox-legacy";
|
||||
import MapboxGeocoder, { Result } from "@mapbox/mapbox-gl-geocoder";
|
||||
import { useEffect } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
// export interface GeocoderObject {
|
||||
// id: string;
|
||||
|
|
@ -32,6 +32,7 @@ interface Props {
|
|||
|
||||
export default function Geocoder(props: Props) {
|
||||
const { mapboxAccessToken, position, customEntries, resultFunction, customTransition } = props;
|
||||
const [geoCoder, setGeoCoder] = useState<MapboxGeocoder>()
|
||||
const { current: map } = useMap();
|
||||
|
||||
const localSearch = (query: string) => {
|
||||
|
|
@ -91,6 +92,19 @@ export default function Geocoder(props: Props) {
|
|||
return matchingResults;
|
||||
};
|
||||
|
||||
//create the geocoder
|
||||
useEffect(()=>{
|
||||
const g = new MapboxGeocoder({
|
||||
accessToken: mapboxAccessToken,
|
||||
localGeocoder: localSearch,
|
||||
flyTo: customTransition ? false : true,
|
||||
marker: false,
|
||||
zoom: 18,
|
||||
});
|
||||
|
||||
setGeoCoder(g)
|
||||
},[mapboxAccessToken])
|
||||
|
||||
// //set the geocoder options
|
||||
// useEffect(() => {
|
||||
// //connects the localSearch function to the geocoder if there are custom entries passed in
|
||||
|
|
@ -106,15 +120,7 @@ export default function Geocoder(props: Props) {
|
|||
|
||||
//attach custom functions to event handlers
|
||||
useEffect(() => {
|
||||
const geoCoder = new MapboxGeocoder({
|
||||
accessToken: mapboxAccessToken,
|
||||
localGeocoder: localSearch,
|
||||
flyTo: customTransition ? false : true,
|
||||
marker: false,
|
||||
zoom: 18,
|
||||
});
|
||||
//events that fire as the search bar is typed into, note the function will run AFTER the event fires
|
||||
|
||||
if(geoCoder){
|
||||
//event is fired when the search bar is cleared
|
||||
geoCoder.on("clear", () => {});
|
||||
|
||||
|
|
@ -137,10 +143,11 @@ export default function Geocoder(props: Props) {
|
|||
}
|
||||
});
|
||||
//once the map ref and access token are set up add the control to the map
|
||||
if (map && mapboxAccessToken) {
|
||||
if (map) {
|
||||
map.addControl(geoCoder, position);
|
||||
}
|
||||
}, [map, mapboxAccessToken, position]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}
|
||||
}, [map, geoCoder]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
return null;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue