Upgrade Your Drupal Skills
We trained 1,000+ Drupal Developers over the last decade.
See Advanced Courses NAH, I know EnoughHow 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:
/**
* Generate a simple map with a location pointer.
*
* @param string $location
* Location to use (for example the address).
* @param string $country
* Name of the country to use.
*
* @return string
* The rendered map.
*/
function mysimplemap_map_create($location, $country) {
$map = '';
// Join the address parts to something geocoder / google maps understands.
// Try to create a geographic point out of the given location values.
if ($geo_point = geocoder('google', $address)) {
// Create a JSON equivalent to the point.
$geo_json = $geo_point->out('json');
// Get map implementation provided by http://drupal.org/project/leaflet_googlemaps.
$map = leaflet_map_get_info('google-maps-roadmap');
// Set initial zoom level.
$map['settings']['zoom'] = 16;
// Decode the JSON string.
// Create settings for the map.
'type' => 'point',
'lon' => $geo_data->coordinates[0],
'lat' => $geo_data->coordinates[1],
),
);
// Render the map with a fixed height of 250 pixels.
$map = leaflet_render_map($map, $features, '250px');
}
return $map;
}
?>
Easy, isn't it?
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