通过经纬度获取所属城市信息

复制代码
<?php
class test{
public static $test_key = 'dfgfdgfh3c8ttrr1774gfdgfdgfd9rgqw1'; //这里是申请的百度appkey
$url = 'http://api.map.baidu.com/geocoder/v2/';
//37.863036
$longitude = number_format(doubleval($longitude), 6); 
//113.598909
$latitude = number_format(doubleval($latitude), 6); 
$gps = $latitude . ',' . $longitude;
 $params = array(
     'location' => $gps,
      'pois' => 0,
  );
$info = test2::get_contents($url, $params);
print_r($info);
}

class test2{

private static function get_contents($url, $param)
    {
        $baidu_key = test::test_key ;
        $param['ak'] = $baidu_key;
        $param['output'] = 'json';
        $url = $url . '?' . http_build_query($param, '', '&');
//echo $url;
        $retry = 2;
        $result = array();

        while ($retry > 0) {
            $result = json_decode(self::curl_get($url), true);

            if (!empty($result) && isset($result['status']) && $result['status'] == 0) {
                return $result;
            }
            if (!empty($result) && isset($result['status'])) {
                $status = $result['status'];
            } else {
                $status = ' http_error:';
            }
            EdjLog::info("baidu_response retry status is" . $status.'params'.json_encode($param));
            $retry--;
        }
        EdjLog::warning('request to baidu lbs api failed after retries');

        return $result;
    }


private static function curl_get($url, $milliseconds = 300)
    {
        $start_time = microtime(true);

        $ch = curl_init();
        //这个参数很重要,设置这个才可以支持毫秒级的超时设置
        curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_USERAGENT, self::$useragent);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_FAILONERROR, 0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, self::$connecttimeout);
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, $milliseconds);


        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_URL, $url);
        $response = curl_exec($ch);
        $http_error_code = curl_errno($ch);
        curl_close($ch);

        EdjLog::info("request to baidu lbs api, url is $url, cost time:" . (microtime(true) - $start_time));
        EdjLog::info("baidu http_error:$http_error_code response is " . str_replace(PHP_EOL, '', $response));
        return $response;
    }
复制代码

 

posted @   穷帅哥依然纵横一方  阅读(488)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示