19 Dec

GoogleMap Helper for CakePHP

CakePHP, Latest Developments

I found CakePHP to be helpful with a lot of things and I loved the fact that anyone can reuse any classes made in PHP using 'vendors' in CakePHP. We recently wrote a CakePHP helper for generating map in CakePHP application.

The helper uses Google Maps API V2 class from phpinsider.com.

To begin with, just download the class and place them inside 'vendors' folder.

Here's the code for the helper: map.php

PHP:
  1. <?php
  2. class MapHelper extends Helper
  3. {
  4.  
  5.     var $helpers = array('Html');
  6.  
  7.     function displaymap($locations=false,$width=500,$height=500)
  8.     {
  9.         vendor('GoogleMapAPI.class');
  10.         $map = new GoogleMapAPI('map');
  11.         if($locations)
  12.         foreach($locations as $location)
  13.         {
  14.             $map->addMarkerByAddress( $location['address'],strip_tags($location['title']), $location['title'])//adds address to showup in Map
  15.         }
  16.         else
  17.         {
  18.             $map->setCenterCoords(-96.67,40.8279);   // if no locations are passed in function, then focus on US
  19.             $map->setZoomLevel(3);
  20.         }
  21.  
  22.         $map->setWidth($width);
  23.         $map->setHeight($height);
  24.         $map_content=$map->getHeaderJS().$map->getMapJS().$map->getMap();
  25.         return $this->output($map_content);
  26.     }
  27. }
  28. ?>

Here's the code for the view (index.thtml in my case): index.thtml

PHP:
  1. <? php
  2. // initialization of $my_locations array to show in map
  3. $my_locations=array();
  4. $my_locations[1]['address']='621 N 48th St # 6 Lincoln NE 68502';
  5. $my_locations[1]['title']='PJ Pizza';
  6.  
  7. $my_locations[2]['address']='826 P St Lincoln NE 68502';
  8. $my_locations[2]['title']='<b>PJ Pizza</b>';
  9.  
  10. echo $map->displaymap($my_locations,500,500); ?>
  11. <script type="text/javascript">onLoad();</script>

One Response to “GoogleMap Helper for CakePHP”

Subscribe to comments with RSS Feed or TrackBack from your own site.

  1. Killer said,

    on Sun, 28 January, 2007 at 10:49 pm

    onload() function produces javascript error sometimes… I think you should display the map automatically without onload() trigger.

    I think helper is useful though… :)

Leave A Reply







Hire us

Contact us to get a free quote on your project.