Google Maps API V3: Offset panTo() by x pixels

google-maps-api-3

I have a some UI elements on the right of my map (sometimes), and I'd like to offset my panTo() calls (sometimes).

So I figured:

  1. get the original latlng
  2. convert it to screen pixels
  3. add an offset
  4. convert it back to latlng.

But I must misunderstand what Google Maps API refers to as the "Point Plane":
http://code.google.com/apis/maps/documentation/javascript/reference.html#Projection

Here is my code that seems to offset by lat-long:

            function getCentreOffset( alatlng ) {
                    var PIXEL_OFFSET= 100; 
                    var aPoint = me.gmap.getProjection().fromLatLngToPoint(alatlng);
                    aPoint.x=aPoint.x + OFFSET;
                    return me.gmap.getProjection().fromPointToLatLng(aPoint);
            }

Best Answer

Here's a simpler version of Ashley's solution:

google.maps.Map.prototype.panToWithOffset = function(latlng, offsetX, offsetY) {
    var map = this;
    var ov = new google.maps.OverlayView();
    ov.onAdd = function() {
        var proj = this.getProjection();
        var aPoint = proj.fromLatLngToContainerPixel(latlng);
        aPoint.x = aPoint.x+offsetX;
        aPoint.y = aPoint.y+offsetY;
        map.panTo(proj.fromContainerPixelToLatLng(aPoint));
    }; 
    ov.draw = function() {}; 
    ov.setMap(this); 
};

You can then use it like this:

var latlng = new google.maps.LatLng(-34.397, 150.644);
var map = new google.maps.Map(document.getElementById("map_canvas"), {
    zoom: 8,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: latlng
});

setTimeout(function() { map.panToWithOffset(latlng, 0, 150); }, 1000);

Here is a working example.

Let me explain in detail. This extends the Map object itself. So you can use it just like panTo() with extra parameters for offsets. This uses the fromLatLngToContainerPixel() and fromContainerPixelToLatLng() methods of the MapCanvasProjecton class. This object has no contructor and has to be gotten from the getProjection() method of the OverlayView class; the OverlayView class is used for the creation of custom overlays by implementing its interface, but here we just use it directly. Because getProjection() is only available after onAdd() has been called. The draw() method is called after onAdd() and is defined for our instance of OverlayView to be a function that does nothing. Not doing so will otherwise cause an error.