JavaScript-如何从另一个函数访问变量?

时间:2020-08-08 20:55:41

标签: javascript scope

我需要从CountryAPI()的变量latlng中获取结果,并将其作为下面的代码传递给myMap(),但是我一直在获取Uncaught ReferenceError:未定义latlng:

const selectCountry = document.getElementById('country');
var latlng;
function countryAPI() {
    const countrySelected = selectCountry.options[selectCountry.selectedIndex].text;
    fetch(`https://restcountries.eu/rest/v2/name/${countrySelected}`)
    .then(res => res.json()) //convert to JSON
    .then(data => { //access the data from the JSON
      latlng = data[0].latlng;  
      document.querySelector('.results').innerHTML = `<ul>
      <li><img src=${data[0].flag} width="150px" align="center" alt="${data[0].name}"</li>
      <li><b>Capital:</b> ${data[0].capital}</li>
      <li><b>Population:</b> ${data[0].population}</li>
      </ul>`
     });
}
countryAPI();
selectCountry.addEventListener('change', countryAPI);

function myMap() {
      var mapProp= {
        center:new google.maps.LatLng(latlng),
        zoom:5,
      };
    var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
}

2 个答案:

答案 0 :(得分:1)

我找到了解决方案!

const selectCountry = document.getElementById("country");

async function countryAPI() {
   const countrySelected = selectCountry.options[selectCountry.selectedIndex].text;
   const res = await fetch(`https://restcountries.eu/rest/v2/name/${countrySelected}`);
   const data = await res.json();
   let latlng = data[0].latlng;
   myMap(latlng);
   document.querySelector(".results").innerHTML = `<ul>
     <li><b>Capital:</b> ${data[0].capital}</li>
     <li><b>Population:</b> ${formatNum(data[0].population)}</li>
   </ul>`;
}

selectCountry.addEventListener("change", countryAPI);

countryAPI();

function myMap(latlng) {
   if(latlng){
    var mapProp = {
      center: new google.maps.LatLng(latlng[0],latlng[1]),
      zoom: 6,
    };
    var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
  }
}

答案 1 :(得分:0)

您需要调用MyMap()函数并包含参数MyMap(latlng)

此行代码之后 latlng = data [0] .latlng

包含 MyMap(latlng);