Google maps v3 polyline tooltip

前端 未结 4 2440
我在风中等你
我在风中等你 2021-02-20 15:08

A google maps marker object (google.maps.Marker) has a title property, so when a user moves their mouse over the marker a simple tooltip is displayed.

There isn\'t a tit

4条回答
  •  伪装坚强ぢ
    2021-02-20 15:48

    I combined @samshull's answer above (duly upvoted!) with info from here to make the InfoWindow appear where the user's cursor mouses over the line:

    // Open the InfoWindow on mouseover:
    google.maps.event.addListener(line, 'mouseover', function(e) {
       infoWindow.setPosition(e.latLng);
       infoWindow.setContent("You are at " + e.latLng);
       infoWindow.open(map);
    });
    
    // Close the InfoWindow on mouseout:
    google.maps.event.addListener(line, 'mouseout', function() {
       infoWindow.close();
    });
    

    Here, line is your PolyLine object; map is your Map object; and infoWindow is your InfoWindow object, which I just create with:

    var infoWindow = new google.maps.InfoWindow();
    

    I also follow this advice by re-using the same InfoWindow object for all my polylines rather than creating a new one for each line:

    Best practices: For the best user experience, only one info window should be open on the map at any one time. Multiple info windows make the map appear cluttered. If you only need one info window at a time, you can create just one InfoWindow object and open it at different locations or markers upon map events, such as user clicks. If you do need more than one info window, you can display multiple InfoWindow objects at the same time.

    Note that infoWindow.setContent() takes a string. So call toString() on a number variable if you want to display a number in the InfoWindow.

    I view all of this as an imperfect workaround until Google Maps hopefully one day add a title property to PolylineOptions, just like they've already done for MarkerOptions.

提交回复
热议问题