To integrate Google Maps into a React.js app, you can use the react-google-maps
library, which provides a set of React components for Google Maps. Here are the steps to integrate Google Maps in a React.js app:
If you haven't already set up a React.js app, you can use Create React App to create a new project:
bashnpx create-react-app my-google-maps-app
cd my-google-maps-app
react-google-maps
libraryInstall the react-google-maps
library using npm or yarn:
bashnpm install react-google-maps
# or
yarn add react-google-maps
To use Google Maps in your app, you'll need to obtain an API key. Follow the instructions on the Google Cloud Platform Console to create a new project and enable the Google Maps JavaScript API. Once you have the API key, you can use it in your React app.
Create a new component for your Google Maps integration. For example, you can create a file called GoogleMap.js
:
jsx// GoogleMap.js
import React from 'react';
import { withGoogleMap, GoogleMap, Marker } from 'react-google-maps';
const Map = withGoogleMap(props => (
<GoogleMap
defaultCenter={{ lat: 37.7749, lng: -122.4194 }} // Set your initial map center
defaultZoom={12} // Set the initial zoom level
>
<Marker position={{ lat: 37.7749, lng: -122.4194 }} /> {/* Add a marker */}
</GoogleMap>
));
const GoogleMapComponent = () => (
<div style={{ height: '500px', width: '100%' }}>
<Map
containerElement={<div style={{ height: '100%' }} />}
mapElement={<div style={{ height: '100%' }} />}
/>
</div>
);
export default GoogleMapComponent;
Now, you can use the GoogleMapComponent
in your main App.js
or any other component:
jsx// App.js
import React from 'react';
import GoogleMapComponent from './GoogleMap';
function App() {
return (
<div className="App">
<h1>My Google Maps App</h1>
<GoogleMapComponent />
</div>
);
}
export default App;
Finally, add your Google Maps API key to the index.html
file in the public
folder of your React app:
html<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Other head elements -->
<!-- Add your Google Maps API key here -->
<script
src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY&libraries=places"
defer
></script>
</head>
<!-- Other body elements -->
</html>
Replace YOUR_GOOGLE_MAPS_API_KEY
with your actual API key.
That's it! Now, when you run your React app (npm start
or yarn start
), you should see a simple Google Map in your application. You can customize the map and markers according to your requirements.