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

后端 未结 3 1601
感情败类
感情败类 2020-12-08 12:11

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 latl
3条回答
  •  遥遥无期
    2020-12-08 12:20

    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.

提交回复
热议问题