Search code examples
javascriptdictionaryleafletmarkers

Is there a cleaner way to code multiple markers on a leaflet map in Javascript?


I currently have 6 individually coded markers on my leaflet map in javascript. I was wondering if there was a cleaner way to code all these and just change the coordinates? (Below is an example of 2 of the markers I have in my Javascript code)

var circle = L.circle([20, 20], {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5,
radius: 100

}).addTo(map).bindPopup('House');

var circle = L.circle([30, 30], {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5,
radius: 100

}).addTo(map).bindPopup('House');


Solution

  • Of Course, you can make simple function and use it.

    function addHouse(x, y, map) {
      return L.circle([x, y], {
               color: 'red',
               fillColor: '#f03',
               fillOpacity: 0.5,
               radius: 100
             }).addTo(map).bindPopup('House');
    }
    
    const circle1 = addHouse(20, 20, map);
    const circle2 = addHouse(30, 30, map);