Cojones Cojones - 7 months ago 23
Javascript Question

How can I avoid code duplication?

I got following JQuery code that I'd love to get DRY. At the moment there's only 2 markers but 30+ to follow so I need a clean solution for this:

L.mapbox.accessToken = 'secret_token';
var map = L.mapbox.map('map', 'mapbox.streets')
.setView([-12.260355, 29.927956], 11);

var geoJson01 = {
features: [{
type: 'Feature',
properties: {
'marker-size': 'large',
'marker-symbol': 'embassy',
video: '<iframe src="http://www.example.com/test1.html" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>',
},
geometry: {
type: 'Point',
coordinates: [29.91, -12.28]
}
}]
};
var geoJson02 = {
features: [{
type: 'Feature',
properties: {
'marker-size': 'large',
'marker-symbol': 'embassy',
video: '<iframe src="http://www.example.com/test2.html" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>',
},
geometry: {
type: 'Point',
coordinates: [29.81, -12.18]
}
}]
};

var myLayer01 = L.mapbox.featureLayer().addTo(map);
var myLayer02 = L.mapbox.featureLayer().addTo(map);

myLayer01.on('layeradd', function(e) {
var marker = e.layer,
feature = marker.feature;
var popupContent = feature.properties.video;
marker.bindPopup(popupContent,{
closeButton: false,
minWidth: 300,
maxWidth: 810
});
});
myLayer02.on('layeradd', function(e) {
var marker = e.layer,
feature = marker.feature;
var popupContent = feature.properties.video;
marker.bindPopup(popupContent,{
closeButton: false,
minWidth: 300,
maxWidth: 810
});
});

myLayer01.setGeoJSON(geoJson01);
myLayer02.setGeoJSON(geoJson02);


How can I achieve this?

Answer

extract out the differences into objects in an array then forEach over it:-

var markers = [

  {
    coordinates: [29.91, -12.28],
    video: '"http://www.example.com/test1.html"'
  }, {
    coordinates: [29.81, -12.18],
    video: '"http://www.example.com/test2.html"'
  }

];

L.mapbox.accessToken = 'secret_token';
var map = L.mapbox.map('map', 'mapbox.streets')
  .setView([-12.260355, 29.927956], 11);

function setMarker(obj) {

  var geoJson01 = {
    features: [{
      type: 'Feature',
      properties: {
        'marker-size': 'large',
        'marker-symbol': 'embassy',
        video: '<iframe src=' + obj.video + ' frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>',
      },
      geometry: {
        type: 'Point',
        coordinates: obj.coordinates
      }
    }]
  };

  var myLayer01 = L.mapbox.featureLayer().addTo(map);

  myLayer01.on('layeradd', function(e) {
    var marker = e.layer,
      feature = marker.feature;
    var popupContent = feature.properties.video;
    marker.bindPopup(popupContent, {
      closeButton: false,
      minWidth: 300,
      maxWidth: 810
    });
  });

  myLayer01.setGeoJSON(geoJson01);
}

markers.forEach(function(m) {

  setMarker(m);

})
Comments