You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PHP提取GeoJSON数据实现HTML下拉菜单联动Leaflet地图

解决从GeoJSON提取国家信息并联动Leaflet地图的问题

一、修正PHP脚本(提取ISO代码与国家名称)

你的原脚本存在几处逻辑问题,修正后的代码如下:

<?php
$executionStartTime = microtime(true);

// 读取并解析GeoJSON文件
$json = json_decode(file_get_contents("../geojson/countries_small.geo.json"), true);
$country = []; // 初始化存储国家信息的数组

foreach ($json['features'] as $feature) {
    $temp = [];
    // 从properties中提取ISO3代码和国家名称(可替换为iso_a2)
    $temp['code'] = $feature['properties']['iso_a3'];
    $temp['name'] = $feature['properties']['name'];
    $country[] = $temp;
}

// 构造输出数据
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "数据提取成功";
$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) * 1000 . " ms"; // 转换为毫秒单位
$output['data'] = $country;

header('Content-Type: application/json; charset=UTF-8');
echo json_encode($output);
?>

修正说明:

  • 初始化了$country数组,避免PHP警告
  • 替换原脚本中不存在的$feature["id"],改为读取GeoJSONproperties里的ISO代码
  • 修正输出变量错误,将未定义的$decode改为整理好的$country数组
  • 调整时间计算逻辑,将秒数转换为毫秒,符合常规计时习惯

二、填充HTML下拉菜单

方式1:服务器端直接生成(适合小体积GeoJSON)

直接在HTML中嵌入PHP代码,一次性生成下拉选项:

<nav id="navbar" class="navbar">
  <ul>
    <li class="dropdown">
      <a href="#"><span>Please Select a Country to Learn More!</span> <i class="bi bi-chevron-down"></i></a>
      <!-- 生成下拉菜单选项 -->
      <ul class="dropdown-menu">
        <?php
        $json = json_decode(file_get_contents("../geojson/countries_small.geo.json"), true);
        foreach ($json['features'] as $feature) {
            $countryName = htmlspecialchars($feature['properties']['name']);
            $isoCode = $feature['properties']['iso_a3'];
            echo "<li><a href='#' class='country-option' data-code='$isoCode'>$countryName</a></li>";
        }
        ?>
      </ul>
    </li>
  </ul>
  <i class="bi bi-list mobile-nav-toggle"></i>
</nav>

方式2:AJAX异步加载(适合大体积GeoJSON)

通过前端JS异步请求PHP接口,动态生成选项:

document.addEventListener('DOMContentLoaded', function() {
    const dropdownMenu = document.querySelector('.dropdown-menu');
    
    fetch('path/to/your/php/script.php')
        .then(res => res.json())
        .then(data => {
            if (data.status.code === "200") {
                data.data.forEach(country => {
                    const li = document.createElement('li');
                    const a = document.createElement('a');
                    a.href = '#';
                    a.className = 'country-option';
                    a.dataset.code = country.code;
                    a.textContent = country.name;
                    li.appendChild(a);
                    dropdownMenu.appendChild(li);
                });
            }
        })
        .catch(err => console.error('加载国家列表失败:', err));
});

三、联动Leaflet地图定位

假设你已初始化Leaflet地图实例map,且GeoJSON图层已加载为countryLayer,添加点击事件实现定位:

document.addEventListener('click', function(e) {
    if (e.target.classList.contains('country-option')) {
        e.preventDefault();
        const targetCode = e.target.dataset.code;
        
        // 找到对应国家的图层
        const targetCountry = countryLayer.getLayers().find(layer => {
            return layer.feature.properties.iso_a3 === targetCode;
        });
        
        if (targetCountry) {
            // 定位到国家边界范围
            map.fitBounds(targetCountry.getBounds());
            // 可选:高亮选中国家
            countryLayer.setStyle({fillOpacity: 0.2, color: '#333'});
            targetCountry.setStyle({fillOpacity: 0.6, color: '#ff4444'});
        }
    }
});

内容的提问来源于stack exchange,提问作者user09873920134

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 22:45:32