DemandingBoyfriend
DemandingBoyfriend

Reputation: 61

Get leaflet marker from a layer

I'm new to leaflet and am trying to implement a set of markers with different CSS-styles.

So, I am aware that after adding a marker to a map I can access different CSS-attributes by calling getElement() on my marker for example:

    marker.addTo(map);
    marker.getElement().style.borderColor = '#000';

This works just fine, but when adding a marker to a layer, this can no longer be used since a TypeError occurs (getElement() is undefined). Here is the example code where the error occurs:

    myLayer.addLayer(marker);
    marker.getElement().style.borderColor = '#000';

Am I overlooking a simpler way to set CSS-Attributes for markers and divicons that are added to layers or is there a similar way to access layer-added markers and divicons in JavaScript?

Upvotes: 4

Views: 2822

Answers (2)

DemandingBoyfriend
DemandingBoyfriend

Reputation: 61

So I found a solution that is working for me. The idea is to extend the function that is used to create the icon. Last answer here github.com/Leaflet/Leaflet/issues/5231 helped a lot.

    var borderSize = ...;
    L.DivIcon.Custom = L.DivIcon.extend({
        createIcon: function(oldIcon) {
               var icon = L.DivIcon.prototype.createIcon.call(this, oldIcon);
               icon.style.borderSize = borderSize;
               ...
               return icon;
        }
    })
    var icon = new L.DivIcon.Custom({
        ...
    });        
    var ll = L.latLng(entry.Longitude, entry.Latitude);
    var marker = L.marker(ll, {
      icon: icon
    })
    this.myLayer.addLayer(marker);

Upvotes: 1

ghybs
ghybs

Reputation: 53215

Welcome to SO!

When not added onto a map (since your parent myLayer may not be added to the map itself), a marker does not have any element.

If you do not need to change too many styles individually and dynamically, you might rather use the className option of your Icon / DivIcon.

Upvotes: 0

Related Questions