javascriptgoogle-maps-api-3

How to offset the center point in Google Maps API v3


I have a Google map with a semi transparent panel covering a portion of the area. I would like to adjust the center point of the map to take into account the portion of the map that is partially obscured. See the image below. Ideally, where the crosshairs and pin are placed would be the center point of the map.

I hope that makes sense.

The reason is simple: When you zoom it needs to center the map over the crosshair rather than at 50% 50%. Also, I will be plotting markers on the map and moving through them in sequence. When the map centers on them, they also need to be at the offset position.

Mockup of the map I am building


Solution

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