RA19
RA19

Reputation: 809

Leaflet JS draw circles instead of images with different colours

I have a leaflet map which is using the default icon and works fine. I want to change my icon to draw a small circle/dot rather than use an actual image to represent my data. I also want to have different colours for the circles/dots based on the attribute 'type' in my array. For example type A = red dot, type B = blue dot. Please note I want the circles to be small dots bit like how a scatter chart looks rather than huge circles on the map. My data sits in a variable called 'Markers' How can I achieve this?

        Example data:
        
        id          latitude        longitude           type
         1008619    25.773031666666 -80.142953333333    A
          7302031   -31.236713333333    37.829590000000 B
    
JSON example:

    {
         "id": "1008619",
         "lat": 25.773031666666,
         "lng": -80.142953333333
         "type": "A"
    
       },

leaflet.js

var map = L.map( 'map', {
  center: [20.0, 5.0],
  minZoom: 2,
  zoom: 2
})

L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
  subdomains: ['a', 'b', 'c']
}).addTo( map )

var myURL = jQuery( 'script[src$="leaf-demo.js"]' ).attr( 'src' ).replace( 'leaf-demo.js', '' )

var myIcon = L.icon({
  iconUrl: myURL + 'images/pin24.png',
  iconRetinaUrl: myURL + 'images/pin48.png',
  iconSize: [29, 24],
  iconAnchor: [9, 21],
  popupAnchor: [0, -14]
})

for ( var i=0; i < markers.length; ++i )
{
 L.marker( [markers[i].lat, markers[i].lng], {icon: myIcon} )
  .bindPopup( '<a href="' + markers[i].url + '" target="_blank">' + markers[i].id+ '</a>' )
  .addTo( map );
}

Created this function:

function getColor(d) {
    return d === 'A' ? "#de2d26" :
        d === 'B' ? "#377eb8" :
            d === 'C' ? "#4daf4a" :
                d === 'D' ? "#984ea3" :
                    "#ff7f00";
}

Upvotes: 0

Views: 1387

Answers (1)

Falke Design
Falke Design

Reputation: 11338

You can use L.circleMarker Doc

 L.circleMarker( [markers[i].lat, markers[i].lng], {radius: 10, color: 'red'} )
  .bindPopup( '<a href="' + markers[i].url + '" target="_blank">' + markers[i].id+ '</a>' )
  .addTo( map );

The radius is in pixel

Upvotes: 1

Related Questions