简体   繁体   中英

How to use Google Map Places API with react?

In my app I've to fetch data from Google Places API and to dispaly markers on the Google Map. Here in this part I've to show the marker and then fetch the location and have to send that to my back end. Can anyone help?

          <input
            type="text"
            id="pac-input"
            className="controls"
            placeholder="Search Box"
            value={this.state.fields["event_location"] || ''}
            onChange={this.onChange.bind(this, "event_location")} />
          <div id="map"></div>
          <p>Unable to locate? <button className="btn btn-default inline" data-toggle="collapse" data-target="#address_panel">Enter an Address</button></p>

You can use the method textSearch() to do what you want. For example:

var map;
var service;
var infowindow;

function initialize() {
  var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);

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

  var request = {
    location: pyrmont,
    radius: '500',
    query: 'restaurant'
  };

  service = new google.maps.places.PlacesService(map);
  service.textSearch(request, callback);
}

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

Google Places API is really good, so take some time to read it.

If you want to use a package that uses React components, I recommend react-google-maps . You should take a look.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM