Google Maps: scroll map programmatically of x pixe

2019-03-15 09:29发布

问题:

Is there a simple way to scroll a google map programmatically of x pixels?

I can only think of using setCenter, but the problem is that I would have to compute the new location (lat/lng) depending on the zoom level...

Can you think of something else? Telling me that it's not possible with the Google Map API is a valid answer if you're pretty sure about it.

ps: I'm using Gmaps4rails, so if you can think of a way to do that with the gem, it'd be cool. (like adjusting the bounds to a subset of the map.) Because in the end my goal is to prevent the menu from hidding some markers. I would need to change the viewport of the map, if that makes sense, so that it fits the markers into the orange area, not the full map.


Solution:

@Shane Best, great, the idea works perfectly, but I think your solution was for Google API v2, right? Here's how I did it for V3:

var point = map.getCenter();

var overlay = new google.maps.OverlayView();
overlay.draw = function() {};
overlay.setMap(map);

var projection = overlay.getProjection();

var pixelpoint = projection.fromLatLngToDivPixel(point);
pixelpoint.x += my_value; # or .y

point = projection.fromDivPixelToLatLng(pixelpoint);

map.setCenter(point);

If anybody knows about a better solution with API v3, tell us about it.

回答1:

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

First you would need to get the center of the map.

var point = map.getCenter();

Convert the latlng to a point value.

var pixelpoint = projection.fromLatLngToPoint(point);

Add yourvalue to the point values.

pixelpoint.x = pixelpoint.x + yourvalue;
//or
pixelpoint.y = pixelpoint.y + yourvalue;

Convert it back to a latLng.

var newpoint = projection.fromPointToLatLng(pixelpoint);

Set the new center with the new value.

map.setCenter(newpoint);

I haven't tested the above but it should work.



回答2:

I believe you are looking for this:

var panListener = google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
                    map.panBy(0,-90);
                });

setTimeout(function() {
    google.maps.event.removeListener(panListener)
}, 2000);

In this case, it moves the map south by 90px.