React+Google map address autocompletion
Before any further ,check the repo on my github:
https://github.com/HipsterSantos/react-google-map
To implement Google Maps Autocomplete in your input text, you need to follow these steps:
- Set Up a Google Cloud Project:
- Go to the Google Cloud Console.
- Create a new project or select an existing one.
- Enable the Places API for your project.
- Create an API key and restrict it to the Places API.
- Add Google Maps Script to Your HTML: Include the Google Maps JavaScript API script with your API key in your HTML file.
- Create an Input Field for Autocomplete: Add an input field in your HTML where users will type their addresses.
- Initialize the Autocomplete Function: Write JavaScript code to initialize the autocomplete functionality on the input field.
using React, you can integrate Google Maps Autocomplete using the @react-google-maps/api
library. Here's a step-by-step guide to help you set it up:
- Install the necessary packages:
npm install @react-google-maps/api
Set up the Google Maps Autocomplete component:
Create a MapAutocompleteComponent.jsx
file for your autocomplete component.
import React, { useEffect, useRef } from 'react';
import { useJsApiLoader } from '@react-google-maps/api';
const libraries = ['places'];
const MapAutocompleteComponent = ({ onPlaceSelected }) => {
const { isLoaded, loadError } = useJsApiLoader({
googleMapsApiKey: 'YOUR_API_KEY', // put your API key here
libraries,
});
const inputRef = useRef(null);
const autocomplete = useRef(null);
useEffect(() => {
if (isLoaded && inputRef.current) {
autocomplete.current = new window.google.maps.places.Autocomplete(inputRef.current, {
types: ['(cities)'], // Change this to fit your needs
});
autocomplete.current.addListener('place_changed', () => {
const place = autocomplete.current.getPlace();
onPlaceSelected(place);
});
}
}, [isLoaded]);
if (loadError) {
return <div>Error loading Google Maps</div>;
}
return (
<input
ref={inputRef}
type="text"
placeholder="Enter a location"
style={{ width: '100%', padding: '8px', boxSizing: 'border-box' }}
/>
);
};
export default MapAutocompleteComponent;
Use the Autocomplete Component in Your Application:
In your main component, you can use the MapAutocompleteComponent
component like this:
import React from 'react';
import MapAutocompleteComponent from './MapAutocompletecomponent.jsx';
const App = () => {
const handlePlaceSelected = (place) => {
if (place.geometry) {
console.log('Place details:', place);
console.log('Formatted address:', place.formatted_address);
} else {
console.log('No details available for input:', place.name);
}
};
return (
<div>
<h1>Google Maps Autocomplete Example</h1>
<MapAutocompleteComponent onPlaceSelected={handlePlaceSelected} />
</div>
);
};
export default App;
The code for this project , click here