简体   繁体   English

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

[英]JavaScript - How to access a variable from another function?

I need to get the result from the variable latlng from CountryAPI() an pass it to myMap() as the code below, but I keep getting Uncaught ReferenceError: latlng is not defined:我需要从 CountryAPI() 中的变量 latlng 中获取结果,并将其传递给 myMap(),如下所示,但我不断收到 Uncaught ReferenceError: latlng is not defined:

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);
}

I've found the solution!我找到了解决方案!

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);
  }
}

You need to call the MyMap() function and include the parameter MyMap(latlng)您需要调用 MyMap() function 并包含参数 MyMap(latlng)

After this line of code latlng = data[0].latlng这行代码之后 latlng = data[0].latlng

Include MyMap(latlng);包括我的地图(latlng);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM