Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps: scroll map programmatically of x pixels

scroll gmaps

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.

fit markers


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.

like image 438
Robin Avatar asked Mar 06 '12 02:03

Robin


People also ask

How do I scroll a map on Google Maps?

You can tilt the map in any direction. Press and hold the scroll button. Then, move the mouse forward or backward.

Is Google static map API free?

The Maps Static API uses a pay-as-you-go pricing model. Requests for the Maps Static API are billed under the SKU for Static Maps. Along with the overall Google Terms of Use, there are usage limits specific to the Maps Static API.


1 Answers

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.

like image 101
Shane Best Avatar answered Sep 30 '22 17:09

Shane Best