Google Static Maps Zend View Helper

From time to time I’ve needed to add static Google maps to my website. The reason to use static maps may vary from accessibility concerns to usage on mobile devices that don’t support JavaScript. Since I’m a lazy programmer I like to create re-usable objects so that I don’t have to rewrite the code over and over. That’s why I like the Zend Framework and more generally object orientated programming. In this particular instance I’ve created a Zend_View_Helper object for outputting Google Static Maps.

Html View helpers are RAD … and awesome too. I have to say that along with action helpers they are some of the most powerful parts of the Zend Framework. This particular helper isn’t particularly complicated but it allows you to embed a call to it in your application. It will return the entire Html image tag with any optional attributes that you decide to pass into it.

The Google Static Maps Helper supports adding as many markers as you would like as well as a zoom level and any other options that you want to send to Google that the Google Maps Api v3 supports. It has some default values such as being a road map and at a zoom level of 12, but these are all configurable via the options array that you pass into it.

Sample usage

The Google Static Map helpers signature is as follows:

 
$this->googleMapStatic(array $markers, array $mapOptions, array $imageAttributes);

At its most basic you just need to pass in the latitude and longitude. You can call the Google Maps Helper from your view script like so (with a few example options):

 
// single latitude and longitude example
 
// set the marker
$marker = array(        
   'latitude' => 40.702147,
   'longitude' => -74.015794
);
// setup some options for the map      
$options = array(
   'zoom' => '15',   
);
// output the image tag
echo $this->googleMapStatic($marker, $options, array('alt' => 'My alt text')); 
 
 
// multiple latitude and longitude example
 
 
// set the markers
$markers = array( 
   array(
      'latitude' => 40.702147,
      'longitude' => -74.015794
   ),
   array(
      'latitude' => 40.702147,
      'longitude' => -74.015794
   ),
   array(
      'latitude' => 40.702147,
      'longitude' => -74.015794
   ),   
);
// output the image tag
echo $this->googleMapStatic($markers, $options, array('alt' => 'My alt text'));

As you can see this makes things very easy, especially if you want to display a list of late and long locations from a database. All that you need to do is to put them into a single or multidimensional array and have them appear on your page!

Source code

The final helper code looks like the below:

<?php
/**
 * A helper for the Google maps API - static maps 
 * @see http://code.google.com/apis/maps/documentation/staticmaps/
 */
class Swink_View_Helper_GoogleMapStatic extends Zend_View_Helper_HtmlElement {
   /**
    * mapping options
    * @var array
    */
   protected $_options = array();
   /**
    * The default options
    * @var array
    */
   protected static $_defaults = array(
      'size'      => '200x200',
      'maptype'   => 'roadmap',      
      'zoom'      => '12',
      'sensor'    => 'false'        
   );
   /**
    * The set of markers and related info
    * @var array
    */
   protected $_markers = array();
 
   /**
     * Generates a 'Goole static map' through an image tag.
     *
     * @param array   $markers   An array of the map markers
     * @param array    $options The general options for the map
     * @param array   $attribs Attributes for the html tag
     * @return string The IMG tag as XHTML.
     */  
    public function googleMapStatic(array $markers, array $options = array(), array $attribs = array()) {
      // set the options and markers   
      $this->_setMarkers($markers);
      $this->_setOptions($options);          
      // build up the image to use     
      $htmlTag = '<img ' . $this->_htmlAttribs($attribs);
      return $htmlTag . ' src="http://maps.google.com/maps/api/staticmap?' . $this->getMapQueryString() . '" />';
    }
 
    /**
     * Get the query string to use for this image
     * @return string
     */
    public function getMapQueryString() {       
      // remove any empty options
      $options = $this->_options;
      foreach ($options as $key => $value) {
         if (empty($value) || $value == '') {
            unset($options[$key]);
         }
      }
      // build up the options as a query string
      return http_build_query($options) . '&' . implode('&', $this->getMarkers());     
    }
 
    /**
     * Build the markers for the query string
     * @return array
     */
    protected function getMarkers() {
      $markers = array();
      foreach ($this->_markers as $marker) {
         $markerPieces = array();         
         foreach ($marker as $key => $value) {
            if (in_array($key, array('size', 'label', 'color'))) {               
               $markerPieces[] = "$key:$value"; 
            }
            else if (in_array($key, array('latitude', 'longitude'))) {
               $markerPieces['coords'][] = $value;
            }
         }
         $markerPieces['coords'] = implode(',', $markerPieces['coords']);        
         $markers[] = 'markers=' . implode('|', $markerPieces);
      }
      return $markers;
    }
 
    /**
     * Set the markers for the map
     * @param $markers
     * @return Swink_View_Helper_GoogleMapStatic
     */
    protected function _setMarkers(array $markers) {
      // prep     
      reset($markers);
      $this->_markers = array();
      if (!is_numeric(key($markers))) {
         // only one marker has been sent in
         $this->_markers[] = $markers; 
      }  
      else {
         // multi dimenstional array
         $this->_markers = $markers;
      }     
      return $this;
    }
 
    /**
     * Merge in the options for the static map with the default options
     * @param $options
     * @return Swink_View_Helper_GoogleMapStatic
     */
    protected function _setOptions(array $options) {
      // init the options
      $this->_options = self::$_defaults;
      // merge the rest of the options in       
      $this->_options = array_merge($this->_options, $options);
      return $this;
    }
}

Code download

I hope that this has been helpful. If it has then let me know. The source code for the above example can be downloaded here.

Comments are closed.