Google Map Implementation in React.js with custom Marker
3 min readDec 23, 2023
Here is the implementation of a Google Map with a custom marker in React.js. In this code, we will learn how to obtain longitude and latitude from an address using Google Maps.
Create React App with command :
npx create-react-app my-app
cd my-app
npm start
Install dependencies using below command :
npm i @react-google-maps/api
Import dependencies in code like this and also import image for marker on google map :
import {
GoogleMap,
Marker,
InfoWindow,
useJsApiLoader,
} from "@react-google-maps/api";
import MarkerIcon from "Imgsource";
// this function for getting log and lat from address using google api
const [propertyCoordinates, setPropertyCoordinates] = useState([]);
const [selectedProperty, setSelectedProperty] = useState(null);
const defaultCenter = { lat: 000.00, lng: 00.0000 }; //set lat and lng which location you want to display bydefault
const address = `${street_address}, ${city}, ${state}`; // address of location we want to display on google map
const finalFilteredResult = data; // If you want to display data from a specific array on click...
async function getLatLngForAddress(address, apiKey) {
try {
const response = await fetch(
`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(
address
)}&key=${apiKey}`
);
if (response.ok) {
const data = await response.json();
if (data.results && data.results.length > 0) {
const location = data.results[0].geometry.location;
return {
lat: location.lat,
lng: location.lng,
};
}
}
throw new Error("Unable to retrieve coordinates for the address.");
} catch (error) {
console.error("Error fetching coordinates:", error);
throw error;
}
}
const handleMarkerClick = (property) => {
setSelectedProperty(property);
setSelectedMarkerPosition({
lat: property.lat,
lng: property.lng,
});
};
//Google map api key
const googleMapsApiKey = process.env.REACT_APP_GOOGLE_MAPS_API_KEY;
const coordinates = await getLatLngForAddress(address,googleMapsApiKey);
setPropertyCoordinates(coordinates.filter((coord) => coord !== null));
Now we will implement Google map and Google marker using longitude and latitude.
<GoogleMap
center={defaultCenter}
zoom={10} //set zoom according to you
mapContainerStyle={{ width: "100%", height: "100%" }} // style of map
options={{
// Show the zoom control on the map
zoomControl: true,
// Disable the street view control
streetViewControl: false,
// Disable the map type control
mapTypeControl: false,
// Disable the fullscreen control
fullscreenControl: false,
}}
>
{propertyCoordinates.map((coordinates, index) => (
<Marker
key={index}
position={coordinates}
icon={MarkerIcon}
onClick={() => handleMarkerClick(finalFilteredResult[index])}
>
// The infoWindow will populate data when the marker is clicked.
{selectedProperty === finalFilteredResult[index] && (
<InfoWindow
position={{
lat: selectedMarkerPosition.lat,
lng: selectedMarkerPosition.lng,
}}
onCloseClick={() => setSelectedProperty(null)}
>
// Display data upon clicking the marker
<>data you want to display on click on marker</>
</InfoWindow>
)}
</Marker>
))}
</GoogleMap>
Implement it in React component and set env variable and run using below command and go to http://localhost:3000 :
npm start
Now you will get google map with custom marker on you browser.
Thank you
Happy Coding…