This is not particularly difficult once you find the relevant previous answer.
You need to convert the centre of the map to its world co-ordinates, find where the map needs to be centered to put the apparent centre where you want it, and re-centre the map using the real centre.
The API will always centre the map on the centre of the viewport, so you need to be careful if you use map.getCenter()
as it will return the real centre, not the apparent centre. I suppose it would be possible to overload the API so that its getCenter()
and setCenter()
methods are replaced, but I haven't done that.
Code below. Example online. In the example, clicking the button shifts the centre of the map (there's a road junction there) down 100px and left 200px.
function offsetCenter(latlng, offsetx, offsety) {
// latlng is the apparent centre-point
// offsetx is the distance you want that point to move to the right, in pixels
// offsety is the distance you want that point to move upwards, in pixels
// offset can be negative
// offsetx and offsety are both optional
var scale = Math.pow(2, map.getZoom());
var worldCoordinateCenter = map.getProjection().fromLatLngToPoint(latlng);
var pixelOffset = new google.maps.Point((offsetx/scale) || 0,(offsety/scale) ||0);
var worldCoordinateNewCenter = new google.maps.Point(
worldCoordinateCenter.x - pixelOffset.x,
worldCoordinateCenter.y + pixelOffset.y
);
var newCenter = map.getProjection().fromPointToLatLng(worldCoordinateNewCenter);
map.setCenter(newCenter);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…