调用百度地图获取地理位置

  • 在模型里创建类文件Baidumapphp
<?php


namespace appcommonmodel;


class Baidumap{
    public static function get_city_by_Longitude_latitude($longitude,$latitude){
        $gps = round($latitude,6) . ',' . round($longitude,6);
        $params=array(
            'location' => $gps,
            'coordtype' => 'wgs84ll',
        );
        $local_info=Baidumap::get_contents($params);
        $city=$local_info['result']['addressComponent']['city'];
        return $city;
    }
    public static function get_contents($param) {
            $url = 'http://api.map.baidu.com/reverse_geocoding/v3/' ;
            $baidu_key = '去官网申请' ;
            $param['ak'] = $baidu_key;
            $param['output'] = 'json';
            $url = $url . '?' . http_build_query($param, '', '&');
            $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:';
                }
                $retry--;
            }
            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, 30);
            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);
            return $response;
        }

}
原文地址:https://www.cnblogs.com/bufeetu/p/13898373.html