I am using react-google-maps
within my GoogleMapComponent.js
. This component should render multiple markers based on a prop called similarLocations
. At initial render, the array is empty, and no markers are shown on the map. Inside the parent component, when the user inputs any character, a fetch request is triggered, which responds with an array of similar locations that is passed to the GoogleMapComponent
, and the markers are successfully displayed on the map.
However, when the user inputs another character that results in an empty array response, the previous markers continue to be displayed on the map, even though I have confirmed that the prop is being passed with an empty array. How can I remove the markers when the array is empty?
Here’s the parent component CreateLocation.js
:
import React, { useEffect, useState } from 'react'
import Input from '../../../components/input'
import { checkLocationMatches} from '../api'
import GoogleMapComponent from './GoogleMapComponent'
const CreateLocation = ({
isEdit,
}) => {
const [locationData, setLocationData] = useState({
id: null,
client: null,
locationName: '',
googleLocationDetails: '',
nameAr: '',
nameEn: '',
street: '',
description: '',
category: null,
clientCode: '',
tags: [],
lat: 0,
lang: 0,
gov: '',
city: '',
area: ''
})
const [similarLocations, setSimilarLocations] = useState([])
const matchArabicName = async () => {
try {
const data = {
lat: locationData.lat,
lang: locationData.lang,
clientId: locationData.client.value,
matcher: 'name_ar',
name: locationData.nameAr
}
const response = await checkLocationMatches(data)
response.data ? setSimilarLocations(response.data) : setSimilarLocations([])
} catch (err) {
console.log(err.response, 'match err')
}
}
useEffect(() => {
if (locationData.lat !== 0 && locationData.nameAr.length > 0 && !isEdit) {
matchArabicName()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [locationData.lat, locationData.nameAr])
return (
<Container>
<Body>
<Form>
<Input
disableWithBorder={false}
label="Client Location Name (Arabic)"
name="nameAr"
placeholder="EX: Hyper one"
type="text"
value={locationData.nameAr}
onChange={e => handleLocationDetailsChange(e)}
required
isEditable
/>
</Form>
<MapContainer>
<GoogleMapComponent
isMarkerShown
containerElement={
<div style={{ height: '100%', width: '100%' }} />
}
setMapLocationData={handleSetMapLocationData}
lat={locationData.lat}
lang={locationData.lang}
isOpen={true}
similarLocations={similarLocations}
/>
</MapContainer>
</Body>
</Container>
)
}
export default CreateLocation
GoogleMapComponent.js
:
/* eslint-disable eqeqeq */
import React, { useEffect, useState } from 'react';
import { compose, withProps } from 'recompose';
import { withScriptjs, withGoogleMap, GoogleMap, Marker, InfoWindow } from 'react-google-maps';
import MapMarker from '../../../assets/icons/map-marker.svg'
import SimilarMarkerIcon from '../../../assets/icons/similar-marker.svg'
const GoogleMapComponent = compose(
withProps({
googleMapURL:
'https://maps.googleapis.com/maps/api/js?key=AIzaSyC8BSY4LG_gLmgrWTU6HqzxaKhC7hM_uH8®ion=EG&language=ar&v=3.exp&libraries=geometry,drawing,places',
loadingElement: <div style={{ height: `100%` }} />,
mapElement: <div style={{ height: `100%` }} />,
}),
withScriptjs,
withGoogleMap,
)(({
isMarkerShown,
multipleMarkers,
similarLocations,
readOnly
}) => {
useEffect(() => {
console.log(similarLocations, 'Similar locations')
console.log(similarLocations.length, 'Similar locations length')
}, [similarLocations])
const onMarkerDragEnd = (coord) => {
const { latLng } = coord;
const lat = latLng.lat();
const lng = latLng.lng();
setCurrentPosition({ lat: lat, lang: lng });
getReverseGeocodingData(lat, lng);
};
return (
<GoogleMap
defaultZoom={zoom || 12}
zoom={zoom || 12}
center={{ lat: currentPosition.lat, lng: currentPosition.lang }}
onClick={(e) => onMarkerDragEnd(e)}>
{isMarkerShown && !multipleMarkers && (
<Marker
position={{ lat: currentPosition.lat, lng: currentPosition.lang }}
defaultDraggable={!readOnly}
onDragEnd={(e) => onMarkerDragEnd(e)}
options={{
icon: {
url: MapMarker,
},
}}
/>
)}
{
similarLocations.length > 0 &&
similarLocations.map(marker => (
<Marker
key={marker.location.id}
position={{ lat: +marker.location.latitude, lng: +marker.location.longitude }}
onClick={() => {
handleActiveMarker(marker.location.id)
}}
options={{
icon: {
url: SimilarMarkerIcon,
},
}}
visible={similarLocations.includes(marker)}
>
{activeMarker === marker.location.id ? (
<InfoWindow onCloseClick={() => setActiveMarker(null)}>
<div>{marker.location.name_ar}</div>
</InfoWindow>
) : null}
</Marker>
))
}
</GoogleMap>
);
});
export default GoogleMapComponent;