How to use Google Maps Places Autocomplete with React JS
Tags: react, googlemap, javascript, autocompelete
Published: 2023-04-13 23:07:02


Hello everyone, I hope you are doing.
today I would like to explain how to use google maps places autocomplete without any libraries or npm's packages and headache 😂 so that let's get started 


##  Setup and Installing React JS

let's do it very quick just follow the steps I suppose you have some background how to do so 

1. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fqfpg6x9min1q3bp5q9e.png)

2. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o2os8v6bdpcnd4fw4udh.png)

3.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/flybvczf8aclgrrbudaa.png)

4.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i2j78ye6bh60qiaz14py.png)

5.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xz9jke8zfk54o5g9duha.png)

6.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q5czhecjw44yuzfp1jyf.png)

7.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ygm6mymuxc01cpjiao4m.png)


the first thing you have to do in index.html after setup the project is that

```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title> React js with Google Map AutoComplete </title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>

**    <script
      src="https://maps.googleapis.com/maps/api/js?key="your-api-key"&libraries=places&callback=initMap"
      async
    ></script>**
  </body>
</html>
```

after that create a component for Map using the library @react-google-maps/api 

```
import React, { useState, useCallback } from 'react'
import { GoogleMap, Marker, useJsApiLoader } from '@react-google-maps/api'


const mapStyle = { 
    height: '300px', 
    width: '100%'
 }



const Map = () => {
    const DEFAULT_ZOOM = 5
    const { isLoaded } = useJsApiLoader({
        id: 'google-map-script',
        googleMapsApiKey: "your-api-key"
    })

    const [map, setMap] = React.useState(null)
    const [markerPosition, setMarkerPosition] = useState({
        lat: 28.0289837,
        lng: 1.6666663,
      })

    const [defaultLocation, setDefaultLocation] = useState({
        lat: 28.0289837,
        lng: 1.6666663,
      })

    const onLoad = useCallback((map)=> {
        const bounds = new window.google.maps.LatLngBounds({
            lat: 28.0289837,
            lng: 1.6666663,
          });
        map.fitBounds(bounds);
        setMap(map)
      }, [])

      const onUnmount = useCallback(() =>{
        setMap(null)
      }, [])
    

    const handelClickOnMap  = ()=> {

      }
  return (
    <div>
     {
        isLoaded ? (
        <GoogleMap
        onLoad={onLoad}
        center={defaultLocation}
        zoom={DEFAULT_ZOOM}
        mapContainerStyle={mapStyle}
        onClick={handelClickOnMap}
        onUnmount={onUnmount}
        >
           <Marker position={markerPosition} />
        </GoogleMap>
        ) : <></>
     }  
   </div>
  )
}

export default Map
```
after that import Map component in App.jsx file 
and now let's create our input for search for places with autocomplete (suggestion places)

```
    import { useRef, useState } from 'react'
import MapView from './components/Map'


function App() {

  const inputRef = useRef()
  const inputStyle= {
    boxShadow: 'inset 0 0 10px #eee !important',
    border: '2px solid #eee',
    width: '456px',
    height: '40px',
    marginLeft: '16px',
    borderRadius: '20px',
    fontWeight: '300 !important',
    outline: 'none',
    padding: '10px 20px',
    marginBottom: '10px',
  }


  const autoComplete = new window.google.maps.places.Autocomplete(
    inputRef.current,
  )


  autoComplete.addListener('place_changed', () => {
    const place = autoComplete.getPlace()
    if (!place.geometry || !place.geometry.location) {
      // User entered the name of a Place that was not suggested and
      // pressed the Enter key, or the Place Details request failed.
        alert("this location not available")
    }
    if (place.geometry.viewport || place.geometry.location) {
        // do something
        console.log(place.geometry.location)
    }
  })
  return (
    <div className="App">
        <label >Location</label>
        <input
          placeholder='type your location'
          ref={inputRef}
          style={inputStyle}
        />
      <MapView/>
    </div>
  )
}

export default App

```
and voila here it is the result 😁

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fzp53z50wc2e6jz3kl6m.png)


Finally, Thank you for reading this post I will glad to hear your feedback.


## Github repo for code source 

[https://github.com/abdeldjalilhachimi/react-google-map-autocomplete](https://github.com/abdeldjalilhachimi/react-google-map-autocomplete)