Ohsik
Ohsik

Reputation: 261

Implement Google maps API on React app

I'm a beginner on react and trying to implement Google Maps API to my React app

I have a search input and place for the map on the page http://localhost:8080/.

How do I implement Google maps autocomplete search into search input box and how the result on the map below. I also like to get json data of geolocation, business website, phone number, hours and etc from Google Maps API.

How do I implement this with React??

Upvotes: 1

Views: 644

Answers (2)

Berk Özel
Berk Özel

Reputation: 607

I think you don't need to use a third party library. First you, you need to embed the script in your index.html

<script src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]&libraries=places"></script>

Create a component for your autocomplete input element.

Inside this components componentDidMount method

this.autocomplete = new google.maps.places.Autocomplete(
      this.autocompleteInput.current,
      {
        types: ["geocode"],
        componentRestrictions: { country: "uk" }
      }
    );
    this.autocomplete.addListener("place_changed", this.handlePlaceChanged);

Autocomplete class has an event called place_changed. When you click on one of the results, you can trigger autocomplete classes getPlace() function and fetch coordinates and bunch of other fields.

handlePlaceChanged() {
    const place = this.autocomplete.getPlace();
    this.props.onPlaceChanged(place);
  } 

Upvotes: 1

JFAP
JFAP

Reputation: 3717

Try if you can find GMaps for react native like this one: https://github.com/teamrota/react-native-gmaps

Upvotes: 0

Related Questions