Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

How to add a map with leaflet programmatically

Parent Feed: 

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. /**

  2.  * Generate a simple map with a location pointer.

  3.  *

  4.  * @param string $location

  5.  *   Location to use (for example the address).

  6.  * @param string $country

  7.  *   Name of the country to use.

  8.  *

  9.  * @return string

  10.  *   The rendered map.

  11.  */

  12. function mysimplemap_map_create($location, $country) {

  13.   $map = '';

  14.   // Join the address parts to something geocoder / google maps understands.

  15.   $address = sprintf('%s, %s', $location, $country);
  16.   // Try to create a geographic point out of the given location values.

  17.   if ($geo_point = geocoder('google', $address)) {

  18.     // Create a JSON equivalent to the point.

  19.     $geo_json = $geo_point->out('json');

  20.     // Get map implementation provided by http://drupal.org/project/leaflet_googlemaps.

  21.     $map = leaflet_map_get_info('google-maps-roadmap');

  22.     // Set initial zoom level.

  23.     $map['settings']['zoom'] = 16;

  24.    

  25.     // Decode the JSON string.

  26.     // Create settings for the map.

  27.     $map_features = array(
  28.         'type' => 'point',

  29.         'lon' => $geo_data->coordinates[0],

  30.         'lat' => $geo_data->coordinates[1],

  31.       ),

  32.     );

  33.     // Render the map with a fixed height of 250 pixels.

  34.     $map = leaflet_render_map($map, $features, '250px');

  35.   }

  36.   return $map;

  37. }

  38. ?>

Easy, isn't it?

Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web