Home > Back-end >  How do I make this function object-oriented so that I can just add a new location to my object and i
How do I make this function object-oriented so that I can just add a new location to my object and i

Time:07-22

This is my js:

var animalAgeValue;
var animalHabitatValue;

var latLong = {
    Berlin: {lat:52.5159, lng:13.3777},
    SanFrancisco: {lat:37.773972, lng:-122.431297},
    Beijing: {lat:39.916668, lng:116.383331}
}


function goToPage(page) {
  if(page == "p1") {
    document.getElementById("p1").hidden = false
    document.getElementById("map").hidden = true
    document.getElementById("p2").hidden = true
    document.getElementById("newAnimal").hidden = true

  } else if(page == "p2") {
    document.getElementById("p1").hidden = true
    document.getElementById("map").hidden = false
    document.getElementById("p2").hidden = false
    document.getElementById("newAnimal").hidden = false

    document.getElementById("animalNameD").innerHTML = animalNameValue;
    document.getElementById("animalAgeD").innerHTML = animalAgeValue;
    document.getElementById("animalHabitatD").innerHTML = animalHabitatValue
  }
  
  
  }

 
 function submitted() {
  animalNameValue = document.getElementById("animalName").value;
  console.log(animalNameValue);
  animalAgeValue = document.getElementById("animalAge").value;
  console.log(animalAgeValue);
  const habitats = document.querySelectorAll('input[name="habitat"]');
        for (const habitat of habitats) {
            if (habitat.checked) {
                animalHabitatValue = habitat.value;
                console.log(animalHabitatValue);
                if(habitat.value == "Berlin") {
                  map.setCenter(latLong.Berlin);
                  map.setZoom(9)
                } else if(habitat.value == "San-Francisco") {
                  map.setCenter(latLong.SanFrancisco);
                  map.setZoom(9)
                } else if(habitat.value == "Beijing") {
                  map.setCenter(latLong.Beijing);
                  map.setZoom(9)
                }
                break;
            }
        }

        

        goToPage("p2")
    

 }

var submit = document.querySelector('#submit')
submit.onclick = function() {submitted()};

I want to reformat my submitted function so that it would work if I added a new location into my latLong object and I added the element into my HTML and I selected it in my webpage, it would center my map around the locations latitude and longitude. In other words I want to pass new lat and long to map.setCenter from the latLong object without having to add an extra if function every time.

CodePudding user response:

you can access object properties through bracket syntax using a variable as the property name.

map.setCenter(latLong[habitat.value]);

  • Related