I have code like below. By default the location is myloc
. When user clicks btn-a
it selects myloc
and when btn-b
is clicked it select myloc1
. In my code I repeat the code L.circle
three times, which is bad practice. So can anybody help me? How can I optimize this code, DRY it up and improve the quality as well?
var myloc = new L.LatLng(13.7433242, 100.5421583);
var myloc1 = new L.LatLng(14.979900, 102.097771);
$(function () {
var circle;
var slider = document.getElementById('myRange');
var output = document.getElementById('demo');
output.innerHTML = slider.value + scale;
slider.oninput = function (val) {
output.innerHTML = this.value + scale;
circle.setRadius(this.value);
}
circle = L.circle(myloc, {
color: '#7a7777',
weight: 0.1,
fillColor: '#7a7777',
fillOpacity: 0.2,
radius: 0
}).addTo(map);
$('.btn-a').on('click', function(e){
if ($(this).val() == 'First') {
circle = L.circle(myloc, {
color: '#7a7777',
weight: 0.1,
fillColor: '#7a7777',
fillOpacity: 0.2,
radius: 0
}).addTo(map);
} else if($(this).val() == 'Second') {
circle = L.circle(myloc1, {
color: '#7a7777',
weight: 0.1,
fillColor: '#7a7777',
fillOpacity: 0.2,
radius: 0
}).addTo(map);
}
});
});
-
\$\begingroup\$ I don't know who proposed the edit, but I rejected it since it didn't solve the issue. The current title is more along the lines of what we're looking for. If it's inaccurate in any way, please feel free to improve it. \$\endgroup\$Mast– Mast ♦2018年08月10日 05:49:23 +00:00Commented Aug 10, 2018 at 5:49
1 Answer 1
To DRY up your code, you need to use a variable to call the same code with different input.s It seems like if you had something like this:
const circles = {
First: myloc,
Second: myloc1
}
Then you'd be able to dry up the click
code:
L.circle(circles[$(this).val()], {
color: '#7a7777',
weight: 0.1,
fillColor: '#7a7777',
fillOpacity: 0.2,
radius: 0
}).addTo(map)