Google Places Web API 在 nearbySearch 上错误地抛出错误并破坏地图

Google Places Web API incorrectly throwing error and breaking maps on nearbySearch

我正在尝试从 Places Web API 中提取一些地点,以便在地图上绘制一些标记。它似乎不正确地抛出错误:

Uncaught Error: Missing parameter. You must specify location.

in places_impl.js:35

我的代码如下:

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

service.nearbySearch({
    bounds: bounds,
    type: ['natural_feature']
}, callback);

它应该按照文档工作:

This method takes a request with the following fields:

Either of: bounds, which must be a google.maps.LatLngBounds object defining the rectangular search area; or

a location and a radius; the former takes a google.maps.LatLng object, and the latter takes a simple integer, representing the circle's radius in meters. The maximum allowed radius is 50 000 meters. Note that when rankBy is set to DISTANCE, you must specify a location but you cannot specify a radius or bounds.

https://developers.google.com/maps/documentation/javascript/places#place_search_requests

问题是当您调用该服务时 bounds 无效。

地图是异步初始化的,边界在 bounds_changed 事件第一次触发之前不可用。

等到 'bounds_changed' 事件在地图上触发,然后再使用 map.getBounds()

google.maps.event.addListener(map, 'bounds_changed', function() {
  var bounds = map.getBounds();
  var service = new google.maps.places.PlacesService(map);

  service.nearbySearch({
    bounds: bounds,
    type: ['natural_feature']
  }, callback);
});

proof of concept fiddle

代码片段:

var geocoder;
var map;
var infowindow = new google.maps.InfoWindow();

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  google.maps.event.addListener(map, 'bounds_changed', function() {
    var bounds = map.getBounds();
    var service = new google.maps.places.PlacesService(map);

    service.nearbySearch({
      bounds: bounds,
      type: ['natural_feature']
    }, callback);
  });

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

  function createMarker(place) {
    var placeLoc = place.geometry.location;
    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);
    });
  }
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places"></script>
<div id="map_canvas"></div>