Simple Static Maps With PHP

Fri, Oct 10, 2008

Heads up! This article was written in 2008 and it exists mostly for historical purposes.

Lately I have been playing with Google Static Maps API a lot. Writing the same things again and again is tedious job. I decided to put the code together as one clean extendable package. Writing object oriented interface for generating URL is trivial. Real meat is having working zoom and pan controls on static map with just 9 lines of code (demo now includes also clickable markers and infowindows).

Code is still alpha quality. API might change any time. But here is a quick walkthrough of current features. We will build the map you see above step by step.

Create a Map Object

Map object is created using Google_Maps::create('static') factory method. If no markers are set you also need to set the center of the map.

Add some markers

Location on map can be in two ways. Latitude and longitude represented by Google_Maps_Coordinate object. Or pixel x and pixel y location represented by Google_Maps_Point object. You can use both when creating a marker.

Automatically Calculate Zoom and Center

Google Static Maps API can automatically calculate zoom and center for you. However there is no way to know what zoom level it chose. If you need to know automatically calculated zoom and center use $map->zoomToFit() method.

Here we also add new marker using pixel coordinates. Note that we also clear the center of the map we set in the beginning. This allows map to recenter the map according to markers on the map.