Keith D Kaiser
Keith D Kaiser

Reputation: 1036

How do I use my leaflet icon definition in my marker definition?

I have a leaflet marker defined like this:

    var W0KCN3 = new L.marker(new L.LatLng(39.2859182,-94.667236),{
     opacity: 0.5,
     contextmenu: true, 
     contextmenuWidth: 140,
     contextmenuItems: [{ text: 'Click here to add mileage circles',
     callback: circleKoords}], 
icon:  firstaidicon,
title:`marker_1 ` }).addTo(fg).bindPopup(`1<br>Northland ARES Platte Co. Resource Center<br>Kansas City, MO<br><br>39.2859182, -94.667236<br>EM29PG`).openPopup(); 

And I have an icon defined like this:

    // Define a PoiIcon class
var PoiIcon = L.Icon.extend({
    options: {
        iconSize: [32, 37]
    }
});

// Create five icons from the above PoiIcon class
var firstaidicon = new PoiIcon({iconUrl: 'images/markers/firstaid.png'}),
    eocicon = new PoiIcon({iconUrl: 'images/markers/eoc.png'}),
    policeicon = new PoiIcon({iconUrl: 'images/markers/police.png'}),
    skywarnicon = new PoiIcon({iconUrl: 'images/markers/skywarn.png'}),
    repeatericon = new PoiIcon({iconUrl: 'markers/repeater.png'});

I want to use the firstaidicon in the marker definition but I'm struggling to make it work. I've tried:

icon:  firstaidicon,

But now I'm getting;

Uncaught TypeError: Cannot read property 'createIcon' of undefined 

from all kinds of locations in leaflet.js:5 What am I doing wrong?

Upvotes: 1

Views: 719

Answers (2)

Keith D Kaiser
Keith D Kaiser

Reputation: 1036

Because each marker was being built by Ajax from a DB I think the timing of when thing happened led to the errors. By putting the icon definition inside the marker definition it all worked. So the new icon call is;

icon: L.icon({iconUrl: `images/markers/skywarn.png`, iconSize: [32, 34]}),

One line closer to being done.

Upvotes: 0

ghybs
ghybs

Reputation: 53225

As shown in the Leaflet Markers With Custom Icons tutorial, you simply pass your custom icon variable to the icon option of your Marker:

var firstaidicon = L.icon();

L.marker(latLng, {
  icon: firstaidicon // instead of new L.firstaidicon
});

Note: make sure to create a different icon instance (even with identical options) for each Marker. An easy way to do so is also shown in the tutorial, by extending the Leaflet Icon class:

var firstaidiconClass = L.Icon.extend({
  options: {
    iconUrl: 'images/markers/firstaid.png',
    iconSize: [32, 37]
  }
});

L.marker(latLng, {
  icon: new firstaidiconClass
});

Upvotes: 1

Related Questions