Skip to content

Instantly share code, notes, and snippets.

@msherstobitow
Created September 23, 2014 13:43
Show Gist options
  • Select an option

  • Save msherstobitow/524412b3c8555166ca25 to your computer and use it in GitHub Desktop.

Select an option

Save msherstobitow/524412b3c8555166ca25 to your computer and use it in GitHub Desktop.
How to offset the center of a Google maps (API v3) in pixels?
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);
};
// Using
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);
@AbeCole
Copy link
Copy Markdown

AbeCole commented Mar 3, 2016

Nice solution, cheers for sharing

@mkormendy
Copy link
Copy Markdown

A very particular/specific/critical thinking question: If I trigger a zoom (in or out, not by mouse click)... will it zoom from the relative middle of the container, or zoom in relative to the new offset center?

@weilinzung
Copy link
Copy Markdown

map.panBy(0,-30) when zoom will offset the new center... I also want to know if this one could fix that~

@pixxelfactory
Copy link
Copy Markdown

This code makes Firefox and Chrome on my Computer take 90-100% of cpu-power (until they stop responding)... =/
Any idea why?

@flpPaiva
Copy link
Copy Markdown

Very helpful! congrats!

@klapec
Copy link
Copy Markdown

klapec commented Apr 3, 2020

Works great, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment