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:
- <?php
- /**
- * 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?