Im using react google maps API. I am able to draw multiple polygons calling renderAllZipcodePolygons('ca','la');
which fetches database coordinates to draw polygons (in this case 2 polygons are drawn on the map). When polygons are drawn a “Remove Boundaries” Button appears. When clicked it should clear any drawn polygons.
The problem arises when clicking does not clear the polygons correctly. I attempt to set polygonPaths to the default value [] but it does nothing. What am I doing incorrectly?
const [polygonPaths, setPolygonPaths] = useState([]);
const [showRemoveBoundariesButton, setShowRemoveBoundariesButton] = useState(true);
const removedBoundariesButtonRef = useRef(null);
const mapRef = useRef(null);
const { isLoaded } = useJsApiLoader({
id: 'google-map-script',
googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
libraries: placesLibrary,
});
const mapOptions = isLoaded ? {
streetViewControl: false,
fullscreenControl: false,
mapTypeControl: true,
} : {};
const clearBoundaries = () => {
setPolygonPaths([]);
setSearchResult("Result: none");
setSearchText('');
setShowRemoveBoundariesButton(false);
};
async function renderAllZipcodePolygons(polygonInput) {
// filter out bad input
const polygoArr= Array.isArray(polygonInput) ? polygonInput: [polygonInput];
// Fetch polygon data for all
const polygonDataPromises = polygoArr.map(p=> fetchPolygonData(p));
const polygonData = await Promise.all(polygonDataPromises);
const validPolygons = polygonData.filter(poly => poly !== null);
setPolygonPaths(validPolygons);
const bounds = new window.google.maps.LatLngBounds();
validPolygons.forEach(polygon => {
polygon.forEach(coord => {
bounds.extend(new window.google.maps.LatLng(coord.lat, coord.lng));
});
});
if (mapRef.current) {
mapRef.current.fitBounds(bounds);
}
}
const onLoadMap = (map) => {
// Prevent multiple initializations
if(mapRef.current !== null) return;
mapRef.current = map;
const controlPosition = window.google.maps.ControlPosition.TOP_RIGHT;
const removeBoundariesButton = document.createElement('div');
ReactDOM.render(
<CustomMapButton
buttonText="Remove Boundaries"
buttonId="map-remove-boundaries"
onClick={() => clearBoundaries()}
isVisible={showRemoveBoundariesButton}
/>,
removeBoundariesButton
);
// add button to map and reference it
mapRef.current.controls[controlPosition].push(removeBoundariesButton);
removedBoundariesButtonRef.current = removeBoundariesButton;
setShowRemoveBoundariesButton(false);
};
return (
{isLoaded && (
<>
<GoogleMap
class="mapContainer"
mapContainerStyle={mapContainerStyle}
center={mapCenter}
zoom={12}
onLoad={onLoadMap}
options={mapOptions}
>
{polygonPaths.map((path, index) => (
<Polygon
key={index}
paths={path}
options={{
fillColor: "#2196F3",
fillOpacity: 0.3,
strokeColor: "#2196F3",
strokeOpacity: 0.8,
strokeWeight: 2,
}}
/>
))}
</GoogleMap>
</>
)}
);