Refactoring a Leaflet / Javascript page

I have some markers that I want to add to a Leaflet map:

var bluestone = new L.Icon({
  iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-blue.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.8.0/images/marker-shadow.png', 
  iconSize: [12, 20], 
  iconAnchor: [6, 20], 
  popupAnchor: [1, -22], 
  shadowSize: [20, 20]
});

var greenstone = new L.Icon({
  iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.8.0/images/marker-shadow.png', 
  iconSize: [12, 20], 
  iconAnchor: [6, 20], 
  popupAnchor: [1, -22], 
  shadowSize: [20, 20]
});

However, I prefer a refactoring along the following lines by defining a construct provisionally called 'options' that I can use throughout:

var options = {
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.8.0/images/marker-shadow.png', 
  iconSize: [12, 20], 
  iconAnchor: [6, 20], 
  popupAnchor: [1, -22], 
  shadowSize: [20, 20]
}

var bluestone = new L.Icon({
  iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-blue.png',
  options: {options}
});

var greenstone = new L.Icon({
  iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png',
  options: {options}
});

Does anybody know what syntax I should follow for this or whether it is even possible to do it this way?

Something OO like Javascript, Ruby or Python?

Yes, all in Javascript.

See Markers With Custom Icons - Leaflet - a JavaScript library for interactive maps, section "Defining an icon class":

var LeafIcon = L.Icon.extend({
    options: {
        shadowUrl: 'leaf-shadow.png',
        iconSize:     [38, 95],
        shadowSize:   [50, 64],
        iconAnchor:   [22, 94],
        shadowAnchor: [4, 62],
        popupAnchor:  [-3, -76]
    }
});

var greenIcon = new LeafIcon({iconUrl: 'leaf-green.png'}),
    redIcon = new LeafIcon({iconUrl: 'leaf-red.png'}),
    orangeIcon = new LeafIcon({iconUrl: 'leaf-orange.png'});

Note that it's new LeafIcon, not new L.LeafIcon.

1 Like

This topic was automatically closed after 2 days. New replies are no longer allowed.