Is it possible to get and show details from a poi with Google Maps API?

时间:2018-03-08 22:11:41

标签: google-maps-api-3

Is it possible to get and show the details (from image 2) directly in the map (picture 1) without that the user must click the link and open a new page?

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

是的,您可以向google.maps.Map()对象添加“click”侦听器以侦听POI上的点击。如果单击一个,则可以通过调用event.stop()来禁止默认行为。点击的结果将是lat / lng和Place ID。

然后,您可以使用google.maps.places.PlacesService()将该地点ID的详细信息作为google.maps.places.PlacesResult()获取,其中包含有关maps.google.com地方信息页的大部分信息。此信息可用于在google.maps.InfoWindow()

中显示

这是very simple proof of concept JSBin。请注意InfoWindow非常简单且未格式化,并且PlacesResult对象中并不总是存在一些细节,但是通过一些不错的CSS和数据检查,您可以创建一个非常丰富和详细的InfoWindow。

<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
      /* 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;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 37.421959, lng: -122.084269},
          zoom: 14
        });

        var placesService = new google.maps.places.PlacesService(map);

        map.addListener('click', function(event) {
            if (event.placeId) {
              event.stop();
              placesService.getDetails({placeId: event.placeId}, function(place, status) {
                  var content = '<div>'+
                    '<div >'+
                    '</div>'+
                    '<h1 class="firstHeading">' + place.name + '</h1>'+
                    '<div">'+
                    '<p>' + place.formatted_address + '</p>'+
                    '<p>' + place.formatted_phone_number + '</p>'+
                    '<p><a href="' + place.website + '">' + place.website + '</a></p>';
                    for (var i = 0; i < place.photos.length; i++) {
                      content += '<img src="' + place.photos[i].getUrl({maxHeight: 50}) + '">';
                    }
                    content += '</div></div>';

                  var infoWindow = new google.maps.InfoWindow({
                      maxWidth: 300,
                      content: content,
                      position: event.latLng
                  });
                  infoWindow.open(map);
              });
            }
        });
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?callback=initMap&libraries=places&key=YOUR_KEY"
    async defer></script>
  </body>
</html>