To my good luck, Google had Google Static Maps API which is basically a URL that you put in the src attribute of an img tag. The URL accepts parameters that will define the image you get: The most important parameters are the Longitude/Latitude of the map’s center and the zoom level. The URL looks like the following
Since Google Static Maps API is just an image provider, what if we wanted richer interaction (zooming, panning) with the map?
We’ll have to implement those features on our own.
Here’s the approach we took
- Make a page on your website dedicated to showing the map (http://m.example.com/map)
- Have that page accept URL parameters to indicate the longitude, latitude and zoom level (http://m.example.com/map?lat=30.1037&lng=31.3366&zoom=14)
The map’s page will use the given parameters to construct the Google Static Maps API’s image url
- On the map’s page, create 6 links (2 for zooming, 2 for panning east and west, 2 for panning north and south)
This is the easy part. The 2 links, one just increments the zoom level, the other just decrements. For example:
Current URL: http://m.example.com/map?lat=30.1037&lng=31.3366&zoom=14
Zoom in URL: http://m.example.com/map?lat=30.1037&lng=31.3366&zoom=15
Zoom out URL: http://m.example.com/map?lat=30.1037&lng=31.3366&zoom=13
This is a bit more difficult. If we want to pan east or west, we’ll have to move the map’s center a little bit right or left. How much exactly is that little bit?
To answer that question, we need a little more info on how Google Maps work. Google Maps provide the map in the form of 256×256 pixels tiles. At zoom level 0, the whole world is represented by a single tile. at zoom level 1, the whole world is represented in a 2×2 tiles. At zoom level 2, it’s 4×4 tiles.
There’s a projection that maps the earth to 2D. That is the Mercator Projection. Using that projection we can
- Convert the Latitude/Longitude and Zoom to Pixels (X,Y)
- Add some value (pixels) to (X,Y) that would allow us to pan east/west, north/south
- Convert the new (X,Y) to Latitude/Longitude
I got the previous 3 steps form here. For example if we have the Latitude/Longitude and Zoom and width/height of the image in pixels:
# get the x,y of the image’s center
x = Mercator.lng_to_x(longitude, zoom)
y = Mercator.lat_to_y(latitude, zoom)
# To pan east or west we add/subtract half the image’s width (not necessarily half of course) and convert it back to longitude
x = x + 0.5 * width
longitude = Mercator.x_to_lng(x, zoom)
# To pan north or south we modify latitude similarly
y = y + 0.5 * height
latitude = Mercator.y_to_lat(y, zoom)
In the Google Maps API there’s a converter that allows converting between Latitude/Longitude and Pixels (X,Y) at different zoom levels.
There’s an issue with the code I implemented but I noted it in the gist. That issue would prevent you from using zoom levels greater than 17.
Hopefully these were enough info to get you started on using Zooming/Panning on Google Static Maps API.