I am using NearbySearch in Google Maps API Places library to get the primary schools of different locations nearby. I get the results successfully but the problem is every time when I enter other pages of other listings(different locations), the search result of the primary schools is the previous one, I have to refresh the page manually, then the new search result will come out. Does anyone know how to re-render the search result automatically based on the different locations? Thanks!
#map.jsx:
import React, { useState, useEffect } from "react";
import {
GoogleMap,
useLoadScript,
Marker,
InfoWindow,
} from "@react-google-maps/api";
import { useDispatch, useSelector } from "react-redux";
import { listListingDetails } from "../actions/listingActions";
import axios from "axios";
const containerStyle = {
height: "400px",
};
let service;
function Map({ match }) {
const [libraries] = useState(["places"]);
const [lat, setLat] = useState(() => {
const savedLat = localStorage.getItem("lat");
const initialValue = Number(savedLat);
return initialValue || 40.7106464;
});
const [lng, setLng] = useState(() => {
const savedLng = localStorage.getItem("lng");
const initialValue = Number(savedLng);
return initialValue || -74.01228809999999;
});
const [loadingmap, setLoadingmap] = useState(true);
const [school, setSchool] = useState([]);
.....
//Load Map
const { isLoaded } = useLoadScript({
googleMapsApiKey: process.env.REACT_APP_GEOCODE_API_KEY,
libraries,
});
//nearby search
const onMapLoad = (map) => {
let request = {
location: { lat, lng },
radius: "1000",
type: ["primary_school"],
};
service = new window.google.maps.places.PlacesService(map);
service.nearbySearch(request, (results, status) => {
if (status === window.google.maps.places.PlacesServiceStatus.OK) {
console.log(results);
let schools = [];
for (var i = 0; i < results.length; i++) {
const school = results[i].name;
schools.push(school);
}
setSchool(schools);
}
});
};
return (
<div>
<div >
<div>
<h5>Primary schools nearby</h5>
{school.map((s) => (
<p key={s}>{s}</p>
))}
</div>
{isLoaded ? (
<div>
<GoogleMap
zoom={11}
center={{ lat, lng }}
onLoad={(map) => onMapLoad(map)}
mapContainerStyle={containerStyle}
>
<Marker position={{ lat, lng }}></Marker>
</GoogleMap>
</div>
) : (
"Loading..."
)}
</div>
</div>):}
export default Map;