I have been building the front end of an application that has the google maps API enabled. I want to have the user click on the map to add markers, and store it into an array; However after I implemented an add marker function to the onClick of the google map tag... The markers won't render.
I have had a lot of difficulty implementing the add marker function in react, and watched several tutorials but cannot seem to find a solution. Any help would be greatly appreciated!
const options = {
styles: mapStyles,
disableDefaultUI: true,
zoomControl: true,
}
var markersArray = [];
function addMarker(event){
let marker = new window.google.maps.Marker({
position: event.latLng,
time: new Date(),
draggable: true
});
markersArray.push(marker);
}
const Map = withScriptjs(withGoogleMap(props =>
<GoogleMap
defaultZoom={8}
defaultCenter={{ lat: this.state.mapPosition.lat, lng: this.state.mapPosition.lng }}
options={options}
onClick={(event) => {
console.log(event);
console.log(markersArray);
addMarker(event);
}}
>
{markersArray.map((marker) =>(
<Marker
key={marker.time.toISOString()}
position={{lat: marker.lat, lng: marker.lng }}
/>
))}
<AutoComplete
style={{width: "100%", height:'40px'}}
types={['(regions)']}
onPlaceSelected={this.onPlaceSelected}
/>
</GoogleMap>
));
I believe the issue is with this but i'm not sure how to make it work.
{markersArray.map((marker) =>(
<Marker
key={marker.time.toISOString()}
position={{lat: marker.lat, lng: marker.lng }}
/>
))}
markersArray
is a plain array. When you do addMarker(event);
you're not updating the state of your component, it's just a plain array. So probably React is not aware of that change. If you're using hooks, you could create a state with your markers like this
const [markers, setMarkers] = useState([])
use that markers
array to render the <Marker />
and then on your event to add the marker
onClick={(event) => {
setMarker(previousMarkers => previousMarkers.concat([event]))
}
this will cause a re-render with the new value of markers
and you should be able to see them.
If it's not a functional component and it's classes, it's the same, but you would define the markers in your class' state
constructor(props) {
super(props)
this.state = { markers: [] }
this.addMarker = this.addMarker.bind(this)
}
// function class below
addMarker(marker) {
this.setState(previousState => previousState.concat([marker])
}
and in your event, you'd call this.addMarker(marker)