开发者

How to offset the center of a Google maps (API v3) in pixels?

I was wondering if it is possible to offset the center of a map in Google maps api v3. I would like to control this offset in pixels, since by lat and lng seem开发者_运维知识库s wrong and very difficult to predict.

I just need to place a marker, and then offset the center by 250px so I can place some other content in the middle of the map.

Hope someone can help!


Found this question when researching and thought I should provide an answer:

function map_recenter(latlng,offsetx,offsety) {
    var point1 = map.getProjection().fromLatLngToPoint(
        (latlng instanceof google.maps.LatLng) ? latlng : map.getCenter()
    );
    var point2 = new google.maps.Point(
        ( (typeof(offsetx) == 'number' ? offsetx : 0) / Math.pow(2, map.getZoom()) ) || 0,
        ( (typeof(offsety) == 'number' ? offsety : 0) / Math.pow(2, map.getZoom()) ) || 0
    );  
    map.setCenter(map.getProjection().fromPointToLatLng(new google.maps.Point(
        point1.x - point2.x,
        point1.y + point2.y
    )));
}

If your Google maps variable isn't map use the following call function reference:

function map_recenter(map,latlng,offsetx,offsety) { ...


Refer to this question: How to offset the center of a Google maps (API v3) in pixels?

This is a modification of an answer I provided here.

google.maps.Map.prototype.setCenterWithOffset= 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.setCenter(proj.fromContainerPixelToLatLng(aPoint));
    }; 
    ov.draw = function() {}; 
    ov.setMap(this); 
};

You can then just use it like so:

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

map.setCenterWithOffset(latlng, 0, 250);

Here is a working example.


there's also the panBy method of the map object... you can offset by a specified number of pixels. However, you'll get a smooth transition animation, which may not be what you wanted. I'm looking for the same thing myself, will let you know what I find.


Have a look at the MapCanvasProjection object - http://code.google.com/apis/maps/documentation/javascript/reference.html#MapCanvasProjection

You can get the map center latLng (map.getCenter()) then convert that to the container pixel coordinates with fromContainerPixeltoLatLng()


Example for latitude offset to pan a bit lower (on a negative lat, idk if positive lat will give the same result)

map.setZoom(15);
let latV = e.latLng.lat()+0.0135;
let lngV = e.latLng.lng();
map.panTo({lat: latV, lng: lngV});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜