首页 > 解决方案 > Google 地图 API:如何在使用 javascript 将鼠标悬停到地点/标记时显示悬停卡片

问题描述

我是谷歌地图 API 的新手。在我的 javascript 项目中,当我有地点的纬度/经度并将鼠标悬停在它们或标记上,如下图所示,我需要显示从谷歌地图 API 返回的图像、地名和地点地址的悬停卡

放置悬停 放置悬停

        map = new google.maps.Map(mapContainer, {
            center: {lat: -34.397, lng: 150.644},
            zoom: 13
        });
        let infowindow = new google.maps.InfoWindow();
        const request = {
            placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4',
            fields: ['name', 'formatted_address', 'place_id', 'geometry']
        };
        const service = new google.maps.places.PlacesService(map);

        navigator.geolocation.getCurrentPosition(function (position) {
            const currentPos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };

            marker = new google.maps.Marker({
                position: currentPos,
                map: map
            });

            service.getDetails(request, function(place, status) {
                if (status === google.maps.places.PlacesServiceStatus.OK) {
                    marker.addListener('click', function() {
                        infowindow.open(map, marker);
                        // I want to show the info window here with image from google map
                        console.log(place);
                    });
                }
            });
            map.setCenter(currentPos);
        }

标签: javascriptgoogle-maps

解决方案


要获取查询地点的图像,您可以使用photo包含PlacePhoto对象的数组字段。您还可以在信息窗口的内容中显示该地点nameratinguser_ratings_total。查看Google 的文档以了解更多信息。

此外,如果您想在将鼠标悬停在标记上时显示信息窗口,那么您需要在事件侦听器中使用“鼠标悬停”而不是“点击”。

尝试以下 jsfiddle 以查看可用于指导的工作示例:https ://jsfiddle.net/rnLm3wd4/

完整代码如下。

<!DOCTYPE html>
<html>

<head>
  <title>Map</title>
  <meta name="viewport" content="initial-scale=1.0">
  <meta charset="utf-8">
  <style>
    #map {
      height: 100%;
    }

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

    .infowindow-container {
      width: 330px;
    }

    .inner {
      display: inline-block;
      position: absolute;
      top: 0;
      padding: 10px;
    }
  </style>
</head>

<body>
  <div id="map"></div>
  <script>
    let map;
    let marker;

    function initMap() {
      map = new google.maps.Map(document.getElementById("map"), {
        zoom: 13
      });
      let infowindow = new google.maps.InfoWindow();
      const request = {
        placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4',
        fields: ['name', 'formatted_address', 'place_id', 'geometry', 'photo', 'rating', 'user_ratings_total']
      };
      const service = new google.maps.places.PlacesService(map);
      service.getDetails(request, function(place, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
          map.setCenter(place.geometry.location)
          marker = new google.maps.Marker({
            position: place.geometry.location,
            map: map
          });
          marker.addListener('mouseover', function() {
            infowindow.open(map, marker);
            infowindow.setContent("<div class='infowindow-container'>" +
              "<img src='" + place.photos[0].getUrl({ maxWidth: 200, maxHeight: 150 }) +
              "'></img><div class='inner'><h4>" + place.name +
              "</h4><p>Rating: " + place.rating + "</p><p>Total reviews: " + place.user_ratings_total + "</p></div></div>");

          });
          marker.addListener("mouseout", function() {
            infowindow.close();
          });
        }
      });
    }
  </script>
  <script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap&libraries=places" async defer></script>
</body>

</html>

希望这可以帮助!


推荐阅读