不显示地点详情的信息窗口(Google Places API)。

问题描述 投票:-1回答:1

我创建了一个特定城市的电影制作公司定位器。我正在使用附近的搜索服务和所有地方的分页。现在我试图添加getDetails服务来在信息窗口中显示公司信息。不幸的是,我没有弄清楚如何用getDetails服务的数据为每个标记显示一个信息窗口。如果有人能帮我解决这个问题,我将非常感激。我把代码放在下面

      var map;
      var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
      var labelIndex = 0;


      function initMap() {
        // Create the map.
        var duesseldorf = {lat: 51.2277, lng: 6.7735};
        map = new google.maps.Map(document.getElementById('map'), {
          center: duesseldorf,
          zoom: 12
        });


        // Create the places service.
        var service = new google.maps.places.PlacesService(map);
        var getNextPage = null;
        var moreButton = document.getElementById('more');
        moreButton.onclick = function() {
          moreButton.disabled = true;
          if (getNextPage) getNextPage();
        };
        

        // Perform a nearby search.
        service.nearbySearch(
            {location: duesseldorf, radius: 14000, keyword: ['filmproduktion']},
            function(results, status, pagination) {
              if (status !== 'OK') return;

              createMarkers(results);
              moreButton.disabled = !pagination.hasNextPage;
              getNextPage = pagination.hasNextPage && function() {
                pagination.nextPage();
              };
            });
        }


        //display place details in info window
        var request = {
            placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4',
            fields: ['name', 'formatted_address', 'place_id', 'geometry']
          };
  
          var infowindow = new google.maps.InfoWindow();
          var service = new google.maps.places.PlacesService(map);
  
          service.getDetails(request, function(place, status) {
            if (status === google.maps.places.PlacesServiceStatus.OK) {
              var marker = new google.maps.Marker({
                map: map,
                position: place.geometry.location
              });
              google.maps.event.addListener(marker, 'click', function() {
                infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
                  'Place ID: ' + place.place_id + '<br>' +
                  place.formatted_address + '</div>');
                infowindow.open(map, this);
              });
            }
          });
          


      function createMarkers(places) {
        var bounds = new google.maps.LatLngBounds();
        var placesList = document.getElementById('places');


        for (var i = 0, place; place = places[i]; i++) {

          var image = {
            url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(25, 25)
          };

          var marker = new google.maps.Marker({
            label: labels[labelIndex++ % labels.length],
            map: map,
            title: place.name,
            position: place.geometry.location
          });



          var li = document.createElement('li');
          li.textContent = place.name;
          placesList.appendChild(li);


          bounds.extend(place.geometry.location);
        }
        map.fitBounds(bounds);
      }

      google.maps.event.addDomListener(window, 'load', initialize);
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
       #map {
        height: 620px;
        width: 75%;
        margin-left: 3%;
        display: inline-block;
        vertical-align: top;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

      h1 {
          text-align: center;
          margin-top: 60px;
          margin-bottom: 60px;
          font-family: 'Roboto','sans-serif';
          font-size: 40px;
      }


      #right-panel {
        font-family: 'Roboto','sans-serif';
        line-height: 30px;
        padding: 10px;
      }

      #right-panel select, #right-panel input {
        font-size: 15px;
      }

      #right-panel select {
        width: 100%;
      }

      #right-panel i {
        font-size: 12px;
      }
      #right-panel {
        font-family: Arial, Helvetica, sans-serif;
        position: absolute;
        right: 3%;
        height: 600px;
        width: 300px;
        z-index: 5;
        border: 1px solid #999;
        background: #fff;
        display: inline-block;
        vertical-align: top;
      }
      h2 {
        font-size: 22px;
        margin: 0 0 5px 0;
      }
      ul {
        list-style-type: none;
        padding: 0;
        margin: 0;
        height: 500px;
        width: 300px;
        overflow-y: scroll;
      }
      li {
        background-color: #f1f1f1;
        padding: 10px;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
      }
      li:nth-child(odd) {
        background-color: #fcfcfc;
      }
      #more {
        width: 100%;
        margin: 5px 0 0 0;
      }

      /* Media Queries */

      @media(max-width: 768px){
          #map{
              display: block;
              width: 90%;
              margin: auto;
              height: 300px;
          }

          #right-panel{
              display: block;
              margin: auto;
              position: relative;
              right: 0;
              margin-top: 15px;
              height: 400px;
          }

          ul{
              height: 300px;
          }

          h1{
              font-size: 30px;
              margin-top: 40px;
              margin-bottom: 40px;
          }
      }
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <link rel="stylesheet" href="./css/style.css">
    <title>Place Search Pagination</title>
    <script src="map.js"></script>
  </head>
  <header>
    <h1>Die besten Filmproduktionen in Düsseldorf und Umgebung!</h1>
  </header>
  <body>
      <div id="map"></div>
      <div id="right-panel">
        <h2>Filmproduktionen in Düsseldorf</h2>
        <ul id="places"></ul>
        <button id="more">Mehr Ergebnisse</button>
      </div>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>
  </body>
</html>
javascript api google-maps-api-3 google-maps-markers google-places-api
1个回答
0
投票

我在发布的代码中得到一个javascript错误。Uncaught ReferenceError: google is not defined 在这一行, var infowindow = new google.maps.InfoWindow();,因为这是在 initMap 所以在API被加载之前执行。 让它成为全局的(var infowindow;),然后在 initMap.

var infowindow;
function initMap() {
  infowindow = new google.maps.InfoWindow();

然后打开详情中的 infowindow呼叫 getDetails 请求,当点击标记时,打开了 infowindow 当回复回来时,跟踪引用到 marker 从点击事件中(该 var that=this; 行,让你在 that 所以当响应返回到 getDetails 请求)。)

google.maps.event.addListener(marker, 'click', function(e) {
  //display place details in info window
  var request = {
    placeId: this.place_id,
    fields: ['name', 'formatted_address', 'place_id', 'geometry']
  };

  var service = new google.maps.places.PlacesService(map);
  var that = this;
  service.getDetails(request, function(place, status) {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
      });
      infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
        'Place ID: ' + place.place_id + '<br>' +
        place.formatted_address + '</div>');
      infowindow.open(map, that);
    }
  });
});

var map;
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
var labelIndex = 0;
var infowindow;


function initMap() {
  // Create the map.
  var duesseldorf = {
    lat: 51.2277,
    lng: 6.7735
  };
  map = new google.maps.Map(document.getElementById('map'), {
    center: duesseldorf,
    zoom: 12
  });
  infowindow = new google.maps.InfoWindow();

  // Create the places service.
  var service = new google.maps.places.PlacesService(map);
  var getNextPage = null;
  var moreButton = document.getElementById('more');
  moreButton.onclick = function() {
    moreButton.disabled = true;
    if (getNextPage) getNextPage();
  };


  // Perform a nearby search.
  service.nearbySearch({
      location: duesseldorf,
      radius: 14000,
      keyword: ['filmproduktion']
    },
    function(results, status, pagination) {
      if (status !== 'OK') return;

      createMarkers(results);
      moreButton.disabled = !pagination.hasNextPage;
      getNextPage = pagination.hasNextPage && function() {
        pagination.nextPage();
      };
    });
}





function createMarkers(places) {
  var bounds = new google.maps.LatLngBounds();
  var placesList = document.getElementById('places');


  for (var i = 0, place; place = places[i]; i++) {

    var image = {
      url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
      size: new google.maps.Size(71, 71),
      origin: new google.maps.Point(0, 0),
      anchor: new google.maps.Point(17, 34),
      scaledSize: new google.maps.Size(25, 25)
    };

    var marker = new google.maps.Marker({
      label: labels[labelIndex++ % labels.length],
      map: map,
      place_id: place.place_id,
      title: place.name,
      position: place.geometry.location
    });
    google.maps.event.addListener(marker, 'click', function(e) {
      //display place details in info window
      var request = {
        placeId: this.place_id,
        fields: ['name', 'formatted_address', 'place_id', 'geometry']
      };


      var service = new google.maps.places.PlacesService(map);
      var that = this;
      service.getDetails(request, function(place, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
          var marker = new google.maps.Marker({
            map: map,
            position: place.geometry.location
          });
          infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
            'Place ID: ' + place.place_id + '<br>' +
            place.formatted_address + '</div>');
          infowindow.open(map, that);
        }
      });
    });


    var li = document.createElement('li');
    li.textContent = place.name;
    placesList.appendChild(li);


    bounds.extend(place.geometry.location);
  }
  map.fitBounds(bounds);
}

google.maps.event.addDomListener(window, 'load', initialize);
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 620px;
  width: 75%;
  margin-left: 3%;
  display: inline-block;
  vertical-align: top;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

h1 {
  text-align: center;
  margin-top: 60px;
  margin-bottom: 60px;
  font-family: 'Roboto', 'sans-serif';
  font-size: 40px;
}

#right-panel {
  font-family: 'Roboto', 'sans-serif';
  line-height: 30px;
  padding: 10px;
}

#right-panel select,
#right-panel input {
  font-size: 15px;
}

#right-panel select {
  width: 100%;
}

#right-panel i {
  font-size: 12px;
}

#right-panel {
  font-family: Arial, Helvetica, sans-serif;
  position: absolute;
  right: 3%;
  height: 600px;
  width: 300px;
  z-index: 5;
  border: 1px solid #999;
  background: #fff;
  display: inline-block;
  vertical-align: top;
}

h2 {
  font-size: 22px;
  margin: 0 0 5px 0;
}

ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
  height: 500px;
  width: 300px;
  overflow-y: scroll;
}

li {
  background-color: #f1f1f1;
  padding: 10px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

li:nth-child(odd) {
  background-color: #fcfcfc;
}

#more {
  width: 100%;
  margin: 5px 0 0 0;
}


/* Media Queries */

@media(max-width: 768px) {
  #map {
    display: block;
    width: 90%;
    margin: auto;
    height: 300px;
  }
  #right-panel {
    display: block;
    margin: auto;
    position: relative;
    right: 0;
    margin-top: 15px;
    height: 400px;
  }
  ul {
    height: 300px;
  }
  h1 {
    font-size: 30px;
    margin-top: 40px;
    margin-bottom: 40px;
  }
}
<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">
  <link rel="stylesheet" href="./css/style.css">
  <title>Place Search Pagination</title>
  <script src="map.js"></script>
</head>
<header>
  <h1>Die besten Filmproduktionen in Düsseldorf und Umgebung!</h1>
</header>

<body>
  <div id="map"></div>
  <div id="right-panel">
    <h2>Filmproduktionen in Düsseldorf</h2>
    <ul id="places"></ul>
    <button id="more">Mehr Ergebnisse</button>
  </div>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>
</body>

</html>
© www.soinside.com 2019 - 2024. All rights reserved.