Google Maps in React
The integration
now we start with the fun part and build our react app
The code here is written with a functional component and not a class component but it similar to each other.
create your react app
npm init react-app my-app
Create 2 env files
.env.development and .env.production and put in the project folder(not in the src folder).
there you gonna save your access key to add env var that react will recognize we need to use REACT_APP at the start of every variable like REACT_APP_API_KEY and set it equal to you to access key
REACT_APP_API_KEY = access_key
**Remember if you upload your code with git add in the .gitignore those file
1. Add useRef to your component
we need to useRef because we need to get the element reference in the future code
const googleMapRef = useRef();
<div
id="google-map"
ref={googleMapRef}
style={{ width: '400px', height: '300px' }}/>
2. Write useEffect to implement the script load
we here use useEffect because we want to load the google maps script after the component render
useEffect(() => {
const googleMapScript = document.createElement('script');
googleMapScript.src=`https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_API_KEY}&libraries=places`;
googleMapScript.async = true;
window.document.body.appendChild(googleMapScript);
googleMapScript.addEventListener('load', () => {
getLatLng();
});
})
},[])
you can add at the end of the src &language=en to be only English without this it will be localized.
3. Create google map function
here we see how see the code that will print the map to the element from the ref.
const createGoogleMap = (coordinates) => {
googleMap = new window.google.maps.Map(googleMapRef.current, {
zoom: 16,
center: {
lat: coordinates.lat(),
lng: coordinates.lng(),
},
disableDefaultUI: true,
})
};
I added isableDefaultUI: true because I wanted to remove the default button that comes with it like in the image below.

4. Get LAT & LNG for the map
in this method, we insert the location place and we get the LAT & LNG of the location and add send the result to the previous function we see, Also as you can see there is Marker so when I print the location it will print it with the red marker
(if you don’t use the marker you will see the location without the red marker).
const getLatLng = () => {
let lat, lng, placeId;
new window.google.maps.Geocoder().geocode({ 'address': `${placeName}` }, function (results, status) {
if (status === window.google.maps.GeocoderStatus.OK) {
placeId = results[0].place_id;
createGoogleMap(results[0].geometry.location);
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
new window.google.maps.Marker({
position: { lat, lng },
map: googleMap,
animation: window.google.maps.Animation.DROP,
title: `${placeName}`
});
setGoogleMapInfo({ ...GoogleMapInfo, lat, lng, placeId, isLoading: false, googleMap });
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
without marker:

with Marker:

5. add everything to one component
const GoogleMap = ({ placeName }) => {
const googleMapRef = useRef();
let googleMap;
useEffect(() => {
const googleMapScript = document.createElement("script");
googleMapScript.src = `https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_API_KEY}&libraries=places`;
googleMapScript.async = true;
window.document.body.appendChild(googleMapScript);
googleMapScript.addEventListener("load", () => {
getLatLng();
});
}, []); const createGoogleMap = (coordinates) => {
googleMap = new window.google.maps.Map(googleMapRef.current, {
zoom: 16,
center: {
lat: coordinates.lat(),
lng: coordinates.lng(),
},
disableDefaultUI: true,
});
};
const getLatLng = () => {
let lat, lng, placeId;
new window.google.maps.Geocoder().geocode(
{ address: `${placeName}` },
function (results, status) {
if (status === window.google.maps.GeocoderStatus.OK) {
placeId = results[0].place_id;
createGoogleMap(results[0].geometry.location);
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
new window.google.maps.Marker({
position: { lat, lng },
map: googleMap,
animation: window.google.maps.Animation.DROP,
title: `${placeName}`,
});
} else {
alert(
"Geocode was not successful for the following reason: " + status
);
}
}
);
};
return (
<div
id="google-map"
ref={googleMapRef}
style={{ width: "400px", height: "300px" }}
/>
);
};