Working with maps, again! But this time with Drupal geofield and leaflet

This time I’ve received a request from a client, he wants to have a series of shapes indicating countries that have registered users from that country, so I need shapes. Then markers that popup info about the members.

I thought it was an easy task, and probably is, but I struggled with the map module because of my server limitations, and Google wanting my credit card to show my maps.

So, after updating composer in my server I solved one of my problems, the out of memory messages I kept getting while trying to install the geofield module.

In other words, my server didn’t like this command, that is what you use to install it in Drupal in 2021:

composer require drupal/geofield
composer require drupal/leaflet

After updating composer:

composer self-update

I finally could install the aforementioned modules.

Onto module testing!

From there on I went on testing the capabilities of those 2 modules:

  • geocode is a field type that store data in a few formats, like lat-lon, WKT and a few more
  • leaflet works in conjunction with geocode field to represent those formats

So, the first thing I wanted to do is to simply show a marker, pretty easy, you set the lat-lon widget for the form visualization, create some content in it, and add the coordinates, it works best with other modules that allow translation of an actual address into coordinates, but I’m not going to mention that part, as I’ve not worked with that yet.

Then I wanted to see if I could create shapes (polygons) that could highlight on hover, and be active only on certain countries. That was a little harder to achieve.

Thing is, I didn’t know how leaflet work, or what WKT is, although it’s the acronym of Well-known text representation of geometry. Of course, as always google comes handy, and allowed me to find the necessary info and examples.

To draw a shape you just add a series of points inside a declaration like:

POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))

Where POLYGON tells leaflet it has to connect each pair of coordinates and fill the area in the middle.

Each pair represents the actual lat-lon coordinates of each one of them, the one above would be something like:

lat 30 lon 10, lat 40 lon 40, lat 20 lon 40, lat 10 lon 20, lat 30 lon 10

Pretty straightforward language.

Then I needed to highlight the area, the country where the mouse hovers on. The cool thing is that leaflet draws using HTML markups (path). So I could just use a CSS directive (:hover), something like:

.leaflet-interactive:hover {
     stroke: #234;
 }

I’d add a live example but huh… I’m lazy. Maybe next time.

Posted in Web Development and tagged , , , , .

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.