在单独的AJAX函数/ API调用中使用现有的lat/lng传单标记



我有一张传单地图,上面有标记,显示了选定国家的顶级城市。当单击一个标记时,将在AJAX调用中使用该城市的lat/lng,并通过使用天气API的PHP cURL例程弹出显示该城市天气信息的模态。在此单击事件触发后,将出现一对easybutton。

我现在想添加另一个模态,包含同一城市的不同信息,当用户单击这些easybutton之一时,将弹出,通过使用另一个API,利用相同的lat/lng值在天气呼叫中使用。

我很谨慎,因为我的main函数现在变得非常长和复杂。此外,我知道$cityMarker点击功能不适用于这个新的模式/简单按钮,因为它需要一个新的点击。因此,我认为最好创建一个单独的函数。

是否有一种简单的方法可以访问AJAX调用中的lat/lng值,以便在函数范围之外使用-即当用户单击新的easyButton时,可以使用当前标记的lat/lng数据?或者有其他的建议,我如何才能实现这个功能?

任何帮助都是非常感激的-谢谢!

JS:

var locationList = [];
citiesArray.forEach(city => {
locationList.push({
lat: city.lat,
lng: city.lng,
cityName: city.toponymName
});
});

console.log(locationList)
for (var i=0; i < locationList.length; i++) {
$cityMarker = L.marker(new L.latLng([locationList[i]['lat'], locationList[i]['lng']]))
.addTo($layers)
.bindPopup(locationList[i]['cityName'])


$($cityMarker).on('click', (event) => {
var marker = event.target;
$.ajax({
url: "getLatLngInfo.php",
type: 'POST',
data: {
lat: marker.getLatLng().lat,
lng: marker.getLatLng().lng
},
success: function(result) {

console.log(result);
$weatherButton.enable();
$wikiButton.enable();
$('#weather').modal('show');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
console.log(textStatus);
console.log(jqXHR);

}
});
});
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
console.log(textStatus);
console.log(jqXHR);
}
});
});
$($wikiButton).on('click'.............

您可以将单击的Marker保存在变量clickedMarker:

var locationList = [];
var clickedMarker;
citiesArray.forEach(city => {
locationList.push({
lat: city.lat,
lng: city.lng,
cityName: city.toponymName
});
});

console.log(locationList)
for (var i=0; i < locationList.length; i++) {
$cityMarker = L.marker(new L.latLng([locationList[i]['lat'], locationList[i]['lng']]))
.addTo($layers)
.bindPopup(locationList[i]['cityName'])


$($cityMarker).on('click', (event) => {
var marker = event.target;
clickedMarker = marker;
$.ajax({
url: "getLatLngInfo.php",
type: 'POST',
data: {
lat: marker.getLatLng().lat,
lng: marker.getLatLng().lng
},
success: function(result) {

console.log(result);
$weatherButton.enable();
$wikiButton.enable();
$('#weather').modal('show');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
console.log(textStatus);
console.log(jqXHR);

}
});
});
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
console.log(textStatus);
console.log(jqXHR);
}
});
});
$($wikiButton).on('click',()=>{
var marker = clickedMarker;
$.ajax({
url: "getLatLngInfo.php",
type: 'POST',
data: {
lat: marker.getLatLng().lat,
lng: marker.getLatLng().lng
},
success: function(result) {
console.log(result);
$weatherButton.enable();
$wikiButton.enable();
$('#weather').modal('show');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
console.log(textStatus);
console.log(jqXHR);
}
});
});

最新更新