How to Add Markers to Google Maps in React.js — Part 2
4 min readApr 17, 2024
Hello Everyone!
In the previous article, I shared the steps to integrate Google Maps into your React.js Application.
Today, I want to show how to add markers to the map. So, I aim to implement a click on the specific location on the map and save it in a list.
Create New States
First of all, I want to create some new states to show/hide the dialog box, store the dialog box location, and store the clicked location.
// store clicked location
const [selectedLocation, setSelectedLocation] = useState({});
// store show dialog state to add location
const [showDialog, setShowDialog] = useState(false);
// store dialog location
const [dialogLocation, setDialogLocation] = useState("");
Create handleMapClick function
I created the handleMapClick function to show a dialog box containing a button to add this location to the list.
// handle click on map
const handleMapClick = (mapProps) => {
// checks if location clicked is valid
if (mapProps.detail.placeId) {
const lat = mapProps.detail.latLng.lat;
const lng = mapProps.detail.latLng.lng;
setShowDialog(true);
setDialogLocation({ lat, lng });
setSelectedLocation({ lat…