地图 JavaScript Api:如何在每个动态创建的标记上放置一个信息框,其中包含地点名称,并且标记是用 setTimeout() 设置的?

Maps JavaScript Api: How to put a info box on each dynamically created marker with the name of the place, and marker is set with setTimeout()?

我有一个 Google Maps JS Api 项目,它必须 return 从用户位置到附近的药店,半径 2000 米。 returned 药房位置设置为在地图上彼此间隔 200 毫秒,这样这些位置就不会同时掉落。到目前为止,一切都井井有条,但是当我尝试在单击标记时 return 一些位置信息时,只有一个位置与信息一起保存。

<script>
        var marker;
        let iconBase = "https://developers.google.com/maps/documentation/javascript/examples/full/images/";
        var userPosition;

        $(document).ready(function () {
            if ("geolocation" in navigator) {
                navigator.geolocation.getCurrentPosition(function (p) {
                    showUserDetails(p.coords.latitude, p.coords.longitude);
                    initialize();
                }, function (e) {
                    ipLookup();
                });
            } else
                ipLookup();
        });

        function showUserDetails(latitude, longitude, additional) {
            userPosition = {
                lat: latitude,
                lng: longitude
            };
            // userPositionString = latitude + "," + longitude;

            $("#latitude").text(latitude);
            $("#longitude").text(longitude);

            if (typeof additional != "undefined") {
                $("#country").text(additional.country.name);
                $("#city").text(additional.city.name);
                $("#continent").text(additional.continent.name);
            }
        }


        let map;
        let service;
        let infowindow;
        function initialize() {
            infowindow = new google.maps.InfoWindow();
            //Map options
            var options = {
                center: userPosition,
                zoom: 14,
                // disableDefaultUI: true,
            }
            //New map
            map = new
                google.maps.Map(document.getElementById("map"), options);

            var request = {
                location: userPosition,
                radius: '2000',
                query: 'farmacie,spital',
            };

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

            function addUserLocationMarker() {
                marker = new google.maps.Marker({
                    map,
                    draggable: true,
                    animation: google.maps.Animation.DROP,
                    position: userPosition,
                    icon: "http://maps.google.com/mapfiles/kml/pushpin/grn-pushpin.png"
                });

                marker.addListener("click", toggleBounce);
                var infoWindow = new google.maps.InfoWindow({
                    content: "<h3>Locatia mea ! </h3>"
                });
                marker.addListener('click', function () {
                    infoWindow.open(map, marker);
                });
            }
            addUserLocationMarker();
        }

        let neighborhoods = [];

        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]);
                    neighborhoods = results;
                    drop();
                }
            }
        }

        let markers = [];

        function drop() {

            clearMarkers();

            for (let i = 0; i < neighborhoods.length; i++) {
                addMarkerWithTimeout(neighborhoods[i], i * 200);

            }
        }

        function addMarkerWithTimeout(position, timeout) {
            window.setTimeout(() => {
                markers.push(
                   marker = new google.maps.Marker({
                       map,
                        position: position.geometry.location,
                        animation: google.maps.Animation.DROP,

                    }, 
                    ));
                    google.maps.event.addListener(marker, "click", () => {
                    infowindow.setContent('<h2>'+ place.name + '</h2>');
                    infowindow.open(map, marker);
                }),
                    marker.addListener("click", toggleBounce)
            }, timeout);
        }

        function addTextBoxInfo(marker) {

        }

        function clearMarkers() {
            for (let i = 0; i < markers.length; i++) {
                markers[i].setMap(null);
            }
            markers = [];
        }

        function toggleBounce() {
            if (marker.getAnimation() !== null) {
                marker.setAnimation(null);
            } else {
                marker.setAnimation(google.maps.Animation.BOUNCE);
            }
        }

        function ipLookup() {
            $.get('https://api.userinfo.io/userinfos', function (r) {
                showUserDetails(r.position.latitude, r.position.longitude, r);
            });
        }
    </script>
    ```
    ```
     <script defer
        src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=geometry,places&q=farmacie&callback=initMap">
      </script>
    ```

我在发布的代码中遇到 javascript 错误:Uncaught ReferenceError: place is not defined。您的 addMarkerWithTimeout 函数中有错字。 position 真的是 place。最好以有意义的方式命名函数的参数:

function addMarkerWithTimeout(place, timeout) {
  window.setTimeout(() => {
    var marker = new google.maps.Marker({
      map,
      position: place.geometry.location,
      animation: google.maps.Animation.DROP,

    });
    google.maps.event.addListener(marker, "click", () => {
        infowindow.setContent('<h2>' + place.name + '</h2>');
        infowindow.open(map, marker);
      }),
      marker.addListener("click", toggleBounce);
    markers.push(marker);
  }, timeout);
}

这样称呼它:

function drop(neighborhoods) {

  clearMarkers();

  for (let i = 0; i < neighborhoods.length; i++) {
    addMarkerWithTimeout(neighborhoods[i], i * 200);

  }
}

将来自地点服务的响应传递到 drop 函数:

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]);
      drop(results);
    }
  }
}

proof of concept fiddle

代码片段:

let map;
let service;
let infowindow;
let userPosition = {
  lat: 40.7127753,
  lng: -74.0059728
}

function initialize() {
  infowindow = new google.maps.InfoWindow();
  //Map options
  var options = {
    center: userPosition,
    zoom: 15,
    // disableDefaultUI: true,
  }
  //New map
  map = new
  google.maps.Map(document.getElementById("map"), options);

  var request = {
    location: userPosition,
    radius: '2000',
    query: 'pharmacy',
  };

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

  function addUserLocationMarker() {
    marker = new google.maps.Marker({
      map,
      draggable: true,
      animation: google.maps.Animation.DROP,
      position: userPosition,
      icon: "http://maps.google.com/mapfiles/kml/pushpin/grn-pushpin.png"
    });

    marker.addListener("click", toggleBounce);
    var infoWindow = new google.maps.InfoWindow({
      content: "<h3>Locatia mea ! </h3>"
    });
    marker.addListener('click', function() {
      infoWindow.open(map, marker);
    });
  }
  addUserLocationMarker();
}

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]);
      drop(results);
    }
  }
}

let markers = [];

function drop(neighborhoods) {

  clearMarkers();

  for (let i = 0; i < neighborhoods.length; i++) {
    addMarkerWithTimeout(neighborhoods[i], i * 200);

  }
}

function addMarkerWithTimeout(place, timeout) {
  window.setTimeout(() => {
    var marker = new google.maps.Marker({
      map,
      position: place.geometry.location,
      animation: google.maps.Animation.DROP,

    });
    google.maps.event.addListener(marker, "click", () => {
        infowindow.setContent('<h2>' + place.name + '</h2>');
        infowindow.open(map, marker);
      }),
      marker.addListener("click", toggleBounce);
    markers.push(marker);
  }, timeout);
}

function clearMarkers() {
  for (let i = 0; i < markers.length; i++) {
    markers[i].setMap(null);
  }
  markers = [];
}

function toggleBounce() {
  if (marker.getAnimation() !== null) {
    marker.setAnimation(null);
  } else {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}
/* 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;
}
<!DOCTYPE html>
<html>

<head>
  <title>Place Searches</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize&libraries=places&v=weekly" defer></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="map"></div>
</body>

</html>