0

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:

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);
}
3
  • 1
    Where, how, and most importantly when, are you calling myMap()? Commented Aug 8, 2020 at 21:01
  • I'm calling it in the beginning of the body tag: <div id="googleMap"></div> Commented Aug 9, 2020 at 14:53
  • Well, don't. Call it from the .then() callback instead, after the json is fetched and the variable is initialised. Commented Aug 9, 2020 at 14:55

2 Answers 2

1

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);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need to call the MyMap() function and include the parameter MyMap(latlng)

After this line of code latlng = data[0].latlng

Include MyMap(latlng);

2 Comments

…and one needs to change the MyMap function to accept that argument, and one should avoid the global var latlng declaration.
Hi DavidGD, I'm sorry, but didn't understand. Could you write the code to show your point? Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.