1

How can I check if a custom tooltip's upper left fits within the map bounds? I am using the code below but something is not right because 'myLatLng' is never within the map bounds. Thank you for your help in advance.

var scale = Math.pow(2, map.getZoom());
var nw = new google.maps.LatLng(
    map.getBounds().getNorthEast().lat(),
    map.getBounds().getSouthWest().lng()
);
var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw);
var worldCoordinate = map.getProjection().fromLatLngToPoint(marker.getPosition());
var pixelOffset = new google.maps.Point(
    Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale),
    Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale)
);

var myLatLng = map.getProjection().fromPointToLatLng(pixelOffset);

if (map.getBounds().contains(myLatLng)) {
 // it's within bounds
}
4

2 回答 2

1

You have a syntax error and typo in your code:

if (map.getBounds().countains(myLatLng) {
 // it's within bounds
}

Should be

if (map.getBounds().contains(myLatLng)) {
 // it's within bounds
} 
于 2013-09-25T12:52:07.230 回答
0

我解决了,这就是我使用的解决方案。

var proj = map.getProjection();
var bounds = map.getBounds();
var scale = Math.pow(2, map.getZoom());             

var anchorPoint = proj.fromLatLngToPoint(marker.getPosition());
// tlc == top left corner (of tooltip)
var tlcPoint = new google.maps.Point(
  (anchorPoint.x * scale) / scale,  
  ((anchorPoint.y * scale) - marker.getIcon().size.height - tooltip.getHeight()) / scale
);
var tlcLatLng = proj.fromPointToLatLng(tlcPoint);

if ( ! bounds.contains(tlcLatLng) ) {
 bounds.extend(tlcLatLng);
 map.fitBounds(bounds);
}
于 2013-10-12T09:58:22.793 回答