Adding a location with map in Drupal 8

Display Date
Drupal 8

Drupal 8 has a lot of great features in core, but the contrib landscape is still evolving. Some features you may expect to be trivial to implement on Drupal 7 can take a little effort on Drupal 8.

For one of our clients we needed to add a location with a Google Map to our event nodes. We found the Simple Google Maps module was available was available, offering a lightweight field formatter to display an address as a Google Map. However it only works on plain text fields. We wanted the structured input of an Address Field.

While it would be nice to extend Simple Google Maps to format address fields directly, we decided to use Computed Field as a bit of glue. Here are the steps to get this set up:

  1. Install Addressfield, Simple Google Maps, and Computed Field.
  2. Add an Addressfield to your contact type, we named it field_location.
  3. Add a computed field, field_map, to the content type. Set the PHP code to compute the text value to:

    $value = implode(" ", array_reverse($fields['field_location'][0]));

    This will combine all components of the address into a text value to feed to Google Maps.

  4. Under Manage Display, set the field formatter for the Map field to Google Map from one-line address. Configure any other settings you would like for the map output.

If all went well, you should have a page with a map looking something like this:

Address with Google Map