Google 地图迭代 API 搜索 - 首先搜索 'i' 次,然后回调 'i' 次

Iteration of Google Maps API Search - First does the search 'i' times, then call back 'i' times

我正在尝试获取一个坐标数组,对数组中的每个项目执行附近搜索 (https://developers.google.com/maps/documentation/javascript/places),然后将每组结果添加到单独的结果数组 (placesOfInterest).

而不是做: Search -> Put results to array -> Search -> Push results to array,好像在做Search -> Search -> Search -> Push results to array -> Push results to array,但我不明白为什么。

我最初试图将搜索结果推送到 placesOfInterest 数组,但后来更改为异步版本,因为我认为由于一些时间延迟而没有触发回调。我根据在本指南 https://codeburst.io/asynchronous-code-inside-an-array-loop-c5d704006c99 上找到的 'appendOutput(item) 创建了 superPush 函数,但这仍然没有解决问题。

HTML

...
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<APIKEY>k&libraries=places"></script>
...

JS

var points = [[2.627365,49.215369],[2.760591, 49.647163],[2.952975, 50.057504],[3.344742, 50.280862],[3.768293, 50.451306],[4.21659, 50.534029]]

   for (point of points) {
      googlePlaces(point);
    }



function googlePlaces(point) {
  var latLng = new google.maps.LatLng(point[1],point[0])
  var request = {
    location: latLng,
    radius: '10000'
  };

  service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, callback);  // hits this code [i] times first...
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    
//results.forEach(result => placesOfInterest.push(result)) // originally tried this way

    results.forEach(result => superPush(result)) // ...then hits this code [i] times

    
   }
}

function superPush(result) {

  fetchData(result).then(function() {
    placesOfInterest.push(result);
  })
}

我能做什么?没有办法不调用回调,但我想不出办法解决它。

一种选择是使用函数闭包来访问数组的索引,结果需要保存在:

function googlePlaces(point, index) { // function closure on index
  var latLng = new google.maps.LatLng(point[1], point[0])
  var request = {
    location: latLng,
    radius: '10000'
  };

  service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, function(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      resultsArray[index] = results;
    }
  })
}

这样称呼它:

var i = 0;
for (point of points) {
  googlePlaces(point, i);
  i++;
}

proof of concept fiddle

代码片段:

// 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;
var resultsArray = [];
var bounds;

function initMap() {
  bounds = new google.maps.LatLngBounds();
  infowindow = new google.maps.InfoWindow();
  map = new google.maps.Map(
    document.getElementById('map'));

  var points = [
    [2.627365, 49.215369],
    [2.760591, 49.647163],
    [2.952975, 50.057504],
    [3.344742, 50.280862],
    [3.768293, 50.451306],
    [4.21659, 50.534029]
  ]
  var i = 0;
  for (point of points) {
    googlePlaces(point, i);
    i++;
  }
}


function googlePlaces(point, index) {
  var latLng = new google.maps.LatLng(point[1], point[0])
  var request = {
    location: latLng,
    radius: '10000'
  };

  service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, function(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {

      resultsArray[index] = results; // ...then hits this code [i] times

      for (var i = 0; i < results.length; i++) {
        var marker = createMarker(results[i], "search " + index);
        bounds.extend(marker.getPosition());
      }
      map.fitBounds(bounds);
    }
  })
}

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

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(text + "<br>" + place.name);
    infowindow.open(map, this);
  });
  return marker;
}
html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}
<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>