0
votes

I have small problem. I use Leaflet with plugins Control Search and Marker Cluster.

I needed to add a custom icons and I read a tutorial from http://leafletjs.com/examples/custom-icons.html

When I add the code {icon: iconRed} to L.Marker, searching doesnt work anymore.

My code sample:

var markers = L.markerClusterGroup({ disableClusteringAtZoom: 16 });

/////////////

var controlSearch = new L.Control.Search({layer: markers, initial: false});

/////////////

var LeafIcon = L.Icon.extend({
        options: {
            iconSize:     [32, 37],
            iconAnchor:   [16, 37],
            popupAnchor:  [1, -30]
        }
});
/////////////

var iconRed = new LeafIcon({iconUrl: './images/marker_icons/red.png'}),
    iconGreen = new LeafIcon({iconUrl: './images/marker_icons/green.png'});

/////////////

var addressPoints = [
    [0,0, "Item 1"],
    [1,1, "Item 2"],
    [2,2, "Item 3"],
    [3,3, "Item 4"]
];

/////////////

for (var i = 0; i < addressPoints.length; i++) {
    var a = addressPoints[i];   
    var title = a[2];

    marker = new L.Marker(new L.latLng(a[0], a[1]), {icon: iconRed}, {title: title});

    marker.bindPopup(title);

    markers.addLayer(marker);
}

/////////////

map.addLayer(markers);

/////////////

map.addControl(controlSearch);
1

1 Answers

1
votes

Your problem lies with the way you instanciate your markers:

L.Marker(new L.latLng(a[0], a[1]), {icon: iconRed}, {title: title});

What you're doing is adding another object as parameter. That won't work, because L.Marker as per documentation: http://leafletjs.com/reference.html#marker only takes two options, the first is the latLng object or an array with coordinates, the second the options object. You're supposed to add the property and value to the options object like so:

L.Marker(new L.latLng(a[0], a[1]), {
    'icon': iconRed,
    'title': title
});

Now the title property is available in the options object, so your search plugin will fuction again.

Here's a working example on Plunker: http://plnkr.co/edit/46VJcp?p=preview