根据城市查询经纬度 php,Laravel+Swoole+PHP-ml 实现根据经纬度返回对应城市
时间: 2023-09-19 14:07:02 浏览: 51
实现这个功能需要用到两个接口,一个是根据经纬度查询城市的接口,另一个是根据城市名查询经纬度的接口。
首先,我们需要获取用户的经纬度信息。可以使用浏览器的 Geolocation API 或者通过 IP 地址查询服务来获取。获取到经纬度后,可以调用根据经纬度查询城市的接口。
以下是使用 Laravel+Swoole 实现的代码示例:
```php
use Swoole\Coroutine\Http\Client;
function getCityByLatLng($lat, $lng)
{
// 调用根据经纬度查询城市的接口
$client = new Client('api.map.baidu.com', 443, true);
$client->set(['timeout' => 10]);
$client->get('/geocoder/v2/', [
'location' => "$lat,$lng",
'output' => 'json',
'ak' => 'your_ak', // 填写你的百度地图开发者密钥
]);
$response = json_decode($client->body, true);
if ($response['status'] == 0) {
return $response['result']['addressComponent']['city'];
}
return null;
}
function getLatLngByCity($city)
{
// 调用根据城市名查询经纬度的接口
$client = new Client('api.map.baidu.com', 443, true);
$client->set(['timeout' => 10]);
$client->get('/geocoder/v2/', [
'address' => $city,
'output' => 'json',
'ak' => 'your_ak', // 填写你的百度地图开发者密钥
]);
$response = json_decode($client->body, true);
if ($response['status'] == 0) {
$location = $response['result']['location'];
return [$location['lat'], $location['lng']];
}
return null;
}
// 示例:根据经纬度返回对应城市
$lat = 39.915168;
$lng = 116.403875;
$city = getCityByLatLng($lat, $lng);
echo $city; // 北京市
// 示例:根据城市返回对应经纬度
$city = '北京市';
$latLng = getLatLngByCity($city);
print_r($latLng); // Array ( [0] => 39.90469 [1] => 116.40717 )
```
另外,如果你需要根据城市查询经纬度的功能,推荐使用第三方库如 `geocoder-php` 或 `googlemaps/google-maps-services-php`,这些库已经封装好了各种地图服务的 API,使用起来更加方便。