My current project involves retrieving weather information from the openweathermap API and displaying it in an infowindow on Google Maps. However, there seems to be an issue where I am getting data from the previous marker instead of the current one.
var map;
var markers = [];
var s = "";
function initMap() {
var currentLat;
var currentLng;
var coords;
var contentString;
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 40.295308, lng: 62.164714 },
zoom: 4
});
// get lng and lat
google.maps.event.addListener(map, 'click', function (event) {
currentLat = event.latLng.lat();
currentLng = event.latLng.lng();
coords = { lat: currentLat, lng: currentLng };
getWeather(coords);
addMarker(coords);
s = "";
});
function addMarker(coords) {
var marker = new google.maps.Marker({
position: coords,
map: map
});
var infoWindow = new google.maps.InfoWindow({
content: s
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
});
///
}
}
function getWeather(coords) {
fetch('https://api.openweathermap.org/data/2.5/weather?lat=' + coords.lat + '&lon=' + coords.lng + '&units=metric&appid=MYAPI')
.then((response) => {
return response.json();
})
.then((myJson) => {
console.log(myJson);
s += myJson.name;
}).catch((err) => {
console.log("Error: " + err);
});
}
I have attempted to use a global string variable and also experimented with using setTimeOut on the getWeather function multiple times, but I cannot seem to retrieve the information before sending the point to the map.