如何将来自 for 循环的多个位置的数据用作在点击事件中使用的传单标记



我有一张传单地图,上面有标记,显示了选定国家的顶级城市。

locationList是一个对象数组,每个对象包含每个城市(lat, lng, cityName)的信息。这些值被用于在地图上添加标记,并且还被字符串化以用于对天气API cURL例程的PHP调用。

我已经添加了弹出窗口,通过for循环成功地将每个城市名称显示在地图上,但是我希望能够为每个标记添加功能,以便当您单击任何$cityMarker时,该特定位置的天气数据会在模态中弹出(AJAX调用后)。

目前,这只适用于locationList数组中的最后一个对象,因为click事件和随后的AJAX调用仅在click事件处理程序之前从循环的最后一项触发。

是否有一种简单的方法来解决这个问题,以便点击事件触发所有位置,取决于哪个被点击?我不知道如何从循环中获取所有数据,以便在$cityMarker中单独使用。

谢谢你!

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++) {
console.log(locationList[i])
$cityMarker = L.marker(new L.latLng([locationList[i]['lat'], locationList[i]['lng']]))
.addTo($layers)
.bindPopup('Name: ' + locationList[i]['cityName'])
}

$($cityMarker).on('click', () => {
$.ajax({
url: "getInfo.php",
type: 'POST',
data: {
locationList: JSON.stringify(locationList)
},
success: function(result) {

console.log(result);
for (let i=0; i < result.data.length; i++) {
$('.modal').modal('show');
$('#openWeatherResult').html(result['data'][i]['openWeather']['weather'][0]['description'])
}                                       
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
console.log(textStatus);
console.log(jqXHR);
}
});
});

PHP:

<?php

ini_set('display_errors', 'On');
error_reporting(E_ALL);
$executionStartTime = microtime(true) / 1000;

$locationList = json_decode($_POST['locationList'], true);
$locationArray = [];

foreach ($locationList as $location){
$data['lat'] = $location['lat'];
$data['lng'] = $location['lng'];
array_push($locationArray, $data);
}
// openweather routine
foreach ($locationArray as $location){
$lat = $location['lat'];
$lng = $location['lng'];

$openWeatherUrl='api.openweathermap.org/data/2.5/weather?lat=' . $lat . '&lon='  . $lng  . '&units=metric&appid=demo';

$openWeatherch = curl_init();
curl_setopt($openWeatherch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($openWeatherch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($openWeatherch, CURLOPT_URL,$openWeatherUrl);

$openWeatherResult = curl_exec($openWeatherch);

curl_close($openWeatherch);

$openWeather = json_decode($openWeatherResult, true);

$output['data'][] = ['location' => $location, 'openWeather' => $openWeather];
}

$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "mission saved";
$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";

header('Content-Type: application/json; charset=UTF-8');

echo json_encode($output);
?>

click监听器移动到循环中:

for (var i = 0; i < locationList.length; i++) {
console.log(locationList[i])
const $cityMarker = L.marker(new L.latLng([locationList[i]['lat'], locationList[i]['lng']]))
.addTo($layers)
.bindPopup('Name: ' + locationList[i]['cityName'])
$($cityMarker).on('click', () => {
$.ajax({
url: "getInfo.php",
type: 'POST',
data: {
locationList: JSON.stringify(locationList)
},
success: function(result) {
console.log(result);
for (let i = 0; i < result.data.length; i++) {
$('.modal').modal('show');
$('#openWeatherResult').html(result['data'][i]['openWeather']['weather'][0]['description'])
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
console.log(textStatus);
console.log(jqXHR);
}
});
});
}

编辑您的问题是,您总是加载所有天气数据,并通过数据进行循环。在下一步中,您更改$('#openWeatherResult')的html/文本,但它不能有多个html/文本,所以它总是覆盖之前的文本…因此,它将始终显示循环的最后一项。

我建议您覆盖/创建新的php文件来加载单个条目的数据:getSingleInfo.php

<?php

ini_set('display_errors', 'On');
error_reporting(E_ALL);
$executionStartTime = microtime(true) / 1000;


$lat = $_POST['lat'];
$lng = $_POST['lng'];

$openWeatherUrl='api.openweathermap.org/data/2.5/weather?lat=' . $lat . '&lon='  . $lng  . '&units=metric&appid=demo';

$openWeatherch = curl_init();
curl_setopt($openWeatherch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($openWeatherch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($openWeatherch, CURLOPT_URL,$openWeatherUrl);

$openWeatherResult = curl_exec($openWeatherch);

curl_close($openWeatherch);

$openWeather = json_decode($openWeatherResult, true);

$output['data'][] = ['location' => $location, 'openWeather' => $openWeather];


$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "mission saved";
$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";

header('Content-Type: application/json; charset=UTF-8');

echo json_encode($output);
?>
然后将ajax调用更改为:
$($cityMarker).on('click', (e) => {
var marker = e.target;
$.ajax({
url: "getSingleInfo.php",
type: 'POST',
data: {
lat: marker.getLatLng().lat,
lng: marker.getLatLng().lng,
},
success: function(result) {

最新更新