How to add a map with leaflet programmatically

Sometimes you would like to add a map to a node or block without the need for detailled configuration options. You simply want to display a map and be done with it.
Fortunately this is an easy task using Leaflet.

Say you have a value for the location and one for the country and would like to print this "address" in a map.
So you need to first install Leaflet and Geocoder and then use this function to generate the map:

  1. <?php
  2. /**
  3.  * Generate a simple map with a location pointer.
  4.  *
  5.  * @param string $location
  6.  *   Location to use (for example the address).
  7.  * @param string $country
  8.  *   Name of the country to use.
  9.  *
  10.  * @return string
  11.  *   The rendered map.
  12.  */
  13. function mysimplemap_map_create($location, $country) {
  14.   $map = '';
  15.   // Join the address parts to something geocoder / google maps understands.
  16.   $address = sprintf('%s, %s', $location, $country);
  17.  
  18.   // Try to create a geographic point out of the given location values.
  19.   if ($geo_point = geocoder('google', $address)) {
  20.     // Create a JSON equivalent to the point.
  21.     $geo_json = $geo_point->out('json');
  22.     // Get map implementation provided by http://drupal.org/project/leaflet_googlemaps.
  23.     $map = leaflet_map_get_info('google-maps-roadmap');
  24.     // Set initial zoom level.
  25.     $map['settings']['zoom'] = 16;
  26.    
  27.     // Decode the JSON string.
  28.     $geo_data = json_decode($geo_json);
  29.     // Create settings for the map.
  30.     $map_features = array(
  31.       array(
  32.         'type' => 'point',
  33.         'lon' => $geo_data->coordinates[0],
  34.         'lat' => $geo_data->coordinates[1],
  35.       ),
  36.     );
  37.     // Render the map with a fixed height of 250 pixels.
  38.     $map = leaflet_render_map($map, $features, '250px');
  39.   }
  40.  
  41.   return $map;
  42. }
  43. ?>

Easy, isn't it?

 

Stefan Borchert
  • CEO

Stefan maintains several Drupal contributed modules, has been working on Drupal core since the early days, and is author of Drupal 8 Configuration Management (Packt Publishing).