I need to focus on the marker based on dynamic search results.
As far as I understood from other discussions, what I need is to make a use of panTo
function.
I gave a try, and it works partially.
Here is the code example and the codesandbox link
Note:
Provide your Google Maps key in .env
file to test the codesandbox.
Map.js
import { GoogleMap, LoadScript, Marker } from "@react-google-maps/api";
import React, { useEffect } from "react";
const containerStyle = {
width: "100%",
height: "500px"
};
const center = { lat: 45.4211, lng: -75.6903 };
const Maps = ({ filteredPark }) => {
const key = process.env.REACT_APP_GOOGLE_KEY; //test with your key please
if (!key) {
throw new Error("Google token is not set");
}
const mapRef = React.useRef();
const onMapLoad = React.useCallback((map) => {
mapRef.current = map;
}, []);
const panTo = React.useCallback(({ lat, lng }) => {
mapRef?.current?.panTo({ lat, lng });
mapRef?.current?.setZoom(18);
}, []);
useEffect(() => {
filteredPark.map((a) => {
const lat = a.coordinates[1];
const lng = a.coordinates[0];
return panTo({ lat, lng });
});
}, [filteredPark, panTo]);
return (
<div style={{ width: "100%", height: "100%" }}>
<LoadScript googleMapsApiKey={key}>
<GoogleMap
mapContainerStyle={containerStyle}
center={center}
zoom={6}
onLoad={onMapLoad}
>
{filteredPark &&
filteredPark.map((park) => (
<Marker
key={park.PARK_ID}
position={{
lat: park.coordinates[1],
lng: park.coordinates[0]
}}
/>
))}
</GoogleMap>
</LoadScript>
</div>
);
};
export default React.memo(Maps);
custom search hook component
import { useMemo } from "react";
import * as parkData from "./data/skateboard-parks.json";
const useParkFIlter = (DESCRIPT_1) => {
const gridRows = parkData.features.map((park) => park.properties);
const filteredParks = useMemo(() => {
return (
gridRows &&
gridRows.filter((dispo) =>
dispo.DESCRIPT_1.toLowerCase().includes(DESCRIPT_1.toLowerCase())
)
);
}, [DESCRIPT_1, gridRows]);
return [filteredParks];
};
export default useParkFIlter;
Any help will be appreciated.