Suresh Man Shrestha
Suresh Man Shrestha

Reputation: 123

How to draw markers of different sizes

The following html script draws specified map tiles and markers as planned. But, the size of markers are same. How can I draw the markers with size as specified in items 3 and 4 in the list 'planes'? This way I can differentiate different markers as per certain properties.

<!DOCTYPE html>
<html>
<head>
<title>Simple Leaflet Map</title>
<meta charset="utf-8" />
<link 
    rel="stylesheet" 
    href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css"
/>
</head>
<body>

<div id="map" style="width: 600px; height: 400px"></div>

<script
    src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js">
</script>

<script>

var planes = [
    ["7C6B07",-40.99497,174.50808, 5, 5],
    ["7C6B38",-41.30269,173.63696, 10, 10],
    ["7C6CA1",-41.49413,173.5421, 15, 5],
    ["7C6CA2",-40.98585,174.50659, 15, 15],
    ["C81D9D",-40.93163,173.81726, 20, 5],
    ["C82009",-41.5183,174.78081, 20, 10],
    ["C82081",-41.42079,173.5783, 5, 15],
    ["C820AB",-42.08414,173.96632, 5, 9],
    ["C820B6",-41.51285,173.53274, 7, 12]
    ];

    var map = L.map('map').setView([-41.3058, 174.82082], 8);
    mapLink = 
        '<a href="http://openstreetmap.org">OpenStreetMap</a>';
    L.tileLayer(
        'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; ' + mapLink + ' Contributors',
        maxZoom: 18,
        }).addTo(map);

    for (var i = 0; i < planes.length; i++) {
        marker = new L.marker([planes[i][1],planes[i][2]], {iconSize: [planes[i][3], planes[i][4]]})
            .bindPopup(planes[i][0])
            .addTo(map);
    }

</script>
</body>
</html>

Upvotes: 0

Views: 285

Answers (2)

Jacobo
Jacobo

Reputation: 19

Leaflet doesn't seem to allow users to modify a default marker's size. However you can create you own custom ICON and extend the regular marker class, modify its size and other properties.

Check the documentation here:

http://leafletjs.com/reference.html#icon

Upvotes: 1

muzaffar
muzaffar

Reputation: 1736

You're assigning iconSize as an option to marker object. This is not the appropriate way.

Actually, you need to create an icon object, set the iconSize value there, then use this icon object in the options of map object.

Here is the code snippet

for (var i = 0; i < planes.length; i++) {

    //create an icon object for each marker
    var myIcon = L.icon({
        iconUrl: 'http://leafletjs.com/dist/images/marker-icon.png',
        iconSize: [planes[i][3], planes[i][4]] //set icon size here
    });

    marker = new L.marker([planes[i][1],planes[i][2]], {icon: myIcon})// use the above icon object here
        .bindPopup(planes[i][0])
        .addTo(map);
}

Even though the icons are not looking good. Here is working fiddle

Upvotes: 0

Related Questions