So I am trying to make a weather app, using openWeatherAPI, and I need the lattitude and longitude of a location
First off, the desired location (city) is put into the geocode class, so that it can be converted into an object with the city name, lon, and lat.
The thing is, when I use the lon and lat values, they appear as undefined, but when you call the whole object itself, it shows all the values as they should be.
This is my index.js:
import Search from "./models/search";
import GeoCode from "./models/geocode";
const geocode = new GeoCode("toronto");
const weather = new Search(geocode.lat, geocode.lon);
console.log(geocode);
console.log(weather);
This is my geocode converter API module (geocode.js):
import axios from "axios";
export default class Geocode{
constructor(city){
this.city = city;
this.getLatLong();
}
async getLatLong(){
try{
const res = await axios(`https://us1.locationiq.com/v1/search.php?key=${key}&q=${this.city}&format=json`);
this.lat = JSON.parse(res.data[0].lat);
this.lon = JSON.parse(res.data[0].lon);
}catch(err){
console.log(err)
}
}
}
and this is my search module, where it contacts the api to search using lon and lat (search.js):
import axios from "axios";
export default class Search{
constructor(lat, lon){
this.lat = lat;
this.lon = lon;
this.getResults();
}
async getResults() {
try {
const res = await axios(`https://api.openweathermap.org/data/2.5/onecall?lat=${this.lat}&lon=${this.lon}&%20exclude=daily&appid=${key}&units=metric`);
this.result = res;
}catch(error){
alert(error);
}
}
}
This is also what I get in the console:
Geocode {city: "toronto"}
Search {lat: undefined, lon: undefined}
Change this:
import Search from "./models/search";
import GeoCode from "./models/geocode";
const geocode = new GeoCode("toronto");
const weather = new Search(geocode.lat, geocode.lon);
console.log(geocode);
console.log(weather);
To this:
import Search from "./models/search";
import GeoCode from "./models/geocode";
(async () => {
const geocode = new GeoCode("toronto");
await geocode.getLatLong();
const weather = new Search(geocode.lat, geocode.lon);
await weather.getResults();
console.log(geocode);
console.log(weather);
})();
Also remove this.getLatLong();
from geocode.js
, and remove this.getResults();
from search.js
.