I'm trying to get weather information from openweathermap api and display it in infowindow on google map per click point,i get the data from the previous marker and not from 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 tried to work with a global string and I also tried several times to work with setTimeOut on the getWeather function but I can not get the information before sending the point to the map