0
\$\begingroup\$

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);
 }
 });
});
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Aug 10, 2018 at 3:43
\$\endgroup\$
1
  • \$\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\$ Commented Aug 10, 2018 at 5:49

1 Answer 1

1
\$\begingroup\$

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)
answered Aug 13, 2018 at 2:06
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.