简体   繁体   中英

Google map API: How to show hover card when hover to a place/marker by using javascript

I'm new to google map API. In my javascript project, I need to show the hover card of places with image, place name and place address that return from google map API when I have lat/lng of places and hover on them or on the markers like the image below

Place hover放置悬停

        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);
        }

To get images of the queried place, you can use the photo field which is an array that contains PlacePhoto objects. You may also show the place's name , rating and user_ratings_total in the content of the infowindow. Take a look at Google's documentation to learn more.

Also, if you want to display the infowindow when you hover on a marker then you need to use "mouseover" not "click" in your event listener.

Try the following jsfiddle to see a working example you can use for guidance: https://jsfiddle.net/rnLm3wd4/

Full code below.

<!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>

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM