如何调用公共地址API获取经纬度填充PHP数组及vectorMap标记
PHP填充经纬度实现方案
1. 编写API调用函数
首先实现一个通用的城市经纬度查询函数,内置缓存避免重复请求:
function getFrenchCityLatLng(string $cityName): array { // 静态缓存,避免同一个城市重复调用API static $cache = []; if (isset($cache[$cityName])) { return $cache[$cityName]; } // 拼接请求URL,城市名做URL编码 $apiUrl = "https://api-adresse.data.gouv.fr/search/?q=" . urlencode($cityName) . "&limit=1"; // 发起请求,加错误抑制符避免请求失败时报错 $response = @file_get_contents($apiUrl); if (!$response) { // 请求失败返回默认值,可根据需求调整 $result = [0, 0]; $cache[$cityName] = $result; return $result; } $data = json_decode($response, true); // 校验返回结果是否有效 if (json_last_error() !== JSON_ERROR_NONE || empty($data['features'][0]['geometry']['coordinates'])) { $result = [0, 0]; $cache[$cityName] = $result; return $result; } // 接口返回coordinates顺序为[经度, 纬度],latLng需要[纬度, 经度] $coordinates = $data['features'][0]['geometry']['coordinates']; $result = [$coordinates[1], $coordinates[0]]; $cache[$cityName] = $result; return $result; }
2. 遍历原数组填充latLng字段
注意你提供的原数组存在语法错误,repartition下第一个子项多了一个闭合括号,修正后处理逻辑如下:
// 你的原数组(已修正语法错误) $lab = array( "repartition" => array ( array( "latLng" => array( 0, 0 ), "name" => "Paris", "code" => "FR-75" ), array ( "latLng" => array( 0, 0 ), "name" => "Grenoble", "code" => "FR-38" ) ) ); // 遍历填充经纬度 foreach ($lab['repartition'] as &$item) { $item['latLng'] = getFrenchCityLatLng($item['name']); } // 解除引用避免后续逻辑异常 unset($item); // 后续直接把$lab['repartition']赋值给前端markers配置即可
兼容方案(CURL版本请求)
如果服务器关闭了allow_url_fopen配置导致file_get_contents无法请求远程地址,可以把函数中的请求部分替换为以下CURL实现:
// 替换getFrenchCityLatLng函数中$response = @file_get_contents($apiUrl);部分 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $apiUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 3); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($ch); curl_close($ch);
内容的提问来源于stack exchange,提问作者made leod
相关产品推荐
相关产品推荐

