Search code examples
reactjsgoogle-mapsgoogle-maps-markersgoogle-places-apigoogle-maps-react

How to use react to implement google Place's Searches, to create markers on the map?


Im new with react and i have created a react project. I would like to know how i can use this default starter project to implement the code from: code link from google. The code is as the following, credit to google, linked above.

Css file- 

/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}


HTML file-

<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>

Java script (pure js) file -

// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

var map;
var service;
var infowindow;

function initMap() {
  var sydney = new google.maps.LatLng(-33.867, 151.195);

  infowindow = new google.maps.InfoWindow();

  map = new google.maps.Map(
      document.getElementById('map'), {center: sydney, zoom: 15});

  var request = {
    query: 'Museum of Contemporary Art Australia',
    fields: ['name', 'geometry'],
  };

  service = new google.maps.places.PlacesService(map);

  service.findPlaceFromQuery(request, function(results, status) {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        createMarker(results[i]);
      }

      map.setCenter(results[0].geometry.location);
    }
  });
}

function createMarker(place) {
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(place.name);
    infowindow.open(map, this);
  });
}

I understand i need to create my key with google maps js and google places, however since Im new to react I'm unsure to how i could implement this into my new react project. Coudl some one show me how these files of code could be put together to be fit for a react project please. I apologies if i sound all over the place.


Solution

  • You can refer to this code I made. Remember to change the value of "YOUR_API_KEY" so that the map will work properly.

    Here is the App.js code snippet:

    import React from 'react';
    import './App.css';
    import Map from './components/placeSearch';
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = { 
          map: {}
        }
      } 
    
      handleMapLoad = (map) => {
        this.setState({
          map: map
        })
      }
    
      render() {
        return (
          <div className="App">
            <Map id="myMap" options={{center: { lat: 51.501904, lng: -0.115871 }, zoom: 13}}    onMapLoad = {this.handleMapLoad}/>  
          </div>
    
        );
      }
    }
    
    export default App;
    
    

    The code for Place Search can be found in the Map components in placeSearch.js. Change the value of your API key here.

    import React from "react";
    import ReactDOM from 'react-dom';
    
    const map;
    var markers = [];
    var infowindow;
    const API_KEY = "YOUR_API_KEY";
    var place = [];
    
    
    class Map extends React.Component {
        constructor(props) {
            super(props);
        }
    
    
    
        componentDidMount() {
                const script = document.createElement('script');
                script.type = 'text/javascript';
                script.src = `https://maps.googleapis.com/maps/api/js?key=` + API_KEY + `&libraries=geometry,places`;
                script.id = 'googleMaps';
                script.async = true;
                script.defer = true;
                document.body.appendChild(script);
                script.addEventListener('load', e => {
                    this.onScriptLoad()
                })
    
        }
    
        onScriptLoad() {
            map = new window.google.maps.Map(document.getElementById(this.props.id), this.props.options);
            this.props.onMapLoad(map)
    
            var request = {
                query: 'Museum of Contemporary Art Australia',
                fields: ['name', 'geometry'],
            };
    
            var service = new google.maps.places.PlacesService(map);
    
            service.findPlaceFromQuery(request, function(results, status) {
                if (status === google.maps.places.PlacesServiceStatus.OK) {
                    for (var i = 0; i < results.length; i++) {
    
                        var place = results[i];
                        var marker = new google.maps.Marker({
                            map: map,
                            position:place.geometry.location,
                            title: place.formatted_address,
                        });
                        markers.push(marker);
    
                        infowindow = new google.maps.InfoWindow();
    
                        marker.addListener('click', () => {
                            infowindow.setContent(place.name);
                            infowindow.open(map, marker);
                        });
                    }
                    map.setCenter(results[0].geometry.location);
                }
    
            })
        }
    
    
        render() {
            return ( 
              <div id = "root" >
                <div className = "map" id = {this.props.id}/>
              </div>
    
            )
        }
    }
    
    export default Map;
    

    Hope this helps!