>/D_
Published on

A better way to add google maps to SilverStripe pages

Authors
  • avatar
    Name
    Frank
    Twitter

Previously I had written a post about the method used to add a Google maps button to tinyMCE in SilverStripe. Its a fairly long winded process, a much better way is the neat little SilverStripe Addressable module.

Created by the same team behind the memberships module, Addressable is similarly nicely written and straight forward to use. If you wanted to add a google map to your contact page which might happen to be a UserDefinedForm its pretty easy:

  • Download the Adressable module and put the folder in the root of your SilverStripe install

  • Run a /dev/build/ to install

  • Add adressable to any object, in my case I needed to add it to UserDefinedForm but it could as easily be Page or ContactPage etc. So I added the following line to my /mysite/_config.php.

    Object::add_extension('UserDefinedForm', 'Addressable');
    
    
  • I think this step may be optional for our purposes but enable geocoding of objects so that each time an address is saved the lat/lng values are updated for that Addressable object, again in /mysite/_config.php:

    Object::add_extension('Object', 'Geocodable');
    
    
  • Run another /dev/build/ for these last two changes.

  • Refresh the CMS and fill in the address details on your UserDefinedForm page (I just put City into the 'State' field in case that confuses you).

  • Lastly, display the map in you template, in my case the /themes/mytheme/templates/Layout/UserDefinedForm.ss file looked like:

    $Content
    $Form
    $FullAddressHTML
    $AddressMap(650,300)
    
    

The full address will be rendered into an HTML address tag and the map will be a static image 650 wide, 300 tall with a link to google maps (You can add a target="_blank" to the html in the AddressMap.ss template found in this module's template folder to open the google map in a new window).

If you want to limit the available countries like I did set the countries in an array in /mysite/_config.php:

Addressable::set_allowed_countries(array(
  'NZ' => "New Zealand",
  'AU' => "Australia"
));

You can do a similar trick with the State field but I didn't have to. Another neat, simple and super useful module that we'll be using on clients' sites from now on.

Update:
I didn't realist this but the size of the image for the Map is restricted to 640px wide and 640px high as mentioned here.