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

I was wondering if it is possible to shift the center of the map in Google maps api v3. I would like to control this pixel offset, since lat and lng seem to be wrong and very difficult to predict.

I just need to place a marker and then shift the center by 250 pixels so that I can place other content in the middle of the map.

Hope someone can help!

+37
google-maps google-maps-api-3
Aug 13 2018-10-10T00:
source share
4 answers

Found this question, exploring and thinking, I must give 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 does not match map , use the following call function link:

 function map_recenter(map,latlng,offsetx,offsety) { ... 
+57
May 23 '12 at 15:18
source share

Refer to this question: How do I compensate for the center of the Google Maps (API v3) in pixels?

This is a modification of the 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 simply 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 }); map.setCenterWithOffset(latlng, 0, 250); 

Here is a working example .

+22
Sep 26 '12 at 19:06
source share

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

You can get the center of the map latLng (map.getCenter ()), and then convert it to the container pixel coordinates using theContainerPixeltoLatLng () method

+4
Aug 13 '10 at 4:11
source share

There is also a panBy method of the map object ... you can compensate for the specified number of pixels. However, you will get smooth transition animations, which may not be what you wanted. I am also looking for the same, letting you know what I find.

+3
Mar 23 2018-11-23T00:
source share



All Articles