您的位置:首页 > 其它

百度地图应用封装 根据地址来获取经纬度 根据经纬度或者地址来获取百度地图

2018-07-11 15:52 302 查看

http://lbsyun.baidu.com/    ->  开发文档   ->   web服务API  ->  获取秘钥  -> 创建应用成功后  ->  查看应用得到ak

1.百度地图相关业务封装

<?php
/**
 * 百度地图相关业务封装
 */
class Map {

    /**
     * 根据地址来获取经纬度
     * @param $address
     * @return array
     */
    public static function  getLngLat($address) {
        if(!$address) {
            return '';
        }
        //http://api.map.baidu.com/geocoder/v2/?callback=renderOption&output=json&address=百度大厦&city=北京市&ak=您的ak
        $data = [
            'address' => $address,
            'ak' => config('map.ak'),
            'output' => 'json',
        ];
        $url = config('map.baidu_map_url').config('map.geocoder').'?'.http_build_query($data);
        // 1 file_get_contents($url);
        // 2 curl
        $result = doCurl($url);
        if($result) {
            return json_decode($result, true);//对 JSON 格式的字符串进行解码,当该参数为 TRUE 时,将返回 array 而非 object
        }else {
            return [];
        }
        //return $result;

    }
    //http://api.map.baidu.com/staticimage/v2
    /**
     * 根据经纬度或者地址来获取百度地图
     * @param $center
     */
    public static function staticimage($center) {
        if(!$center) {
            return '';
        }
        $data = [
            'ak' => config('map.ak'),
            'width' => config('map.width'),
            'height' => config('map.height'),
            'center' => $center,
            'markers' => $center,
        ];
        $url = config('map.baidu_map_url').config('map.staticimage').'?'.http_build_query($data);
        // 1 file_get_contents($url);
        // 2 curl
        $result = doCurl($url);
        return $result;

    }

}


2.公共文件

    /**
 * @param $url
 * @param int $type 0 get  1 post
 * @param array $data
 */
function doCurl($url, $type=0, $data=[]) {
    $ch = curl_init(); // 初始化  初始化一个cURL会话
    // 设置选项
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//获取页面内容,但不输出
    curl_setopt($ch, CURLOPT_HEADER,0);//设置不需要头信息

    if($type == 1) {
        // post
        curl_setopt($ch, CURLOPT_POST, 1);//设置请求是post方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置post请求数据
    }

    //执行并获取内容  抓取URL并把它传递给浏览器
    $output = curl_exec($ch);
    // 释放curl句柄  关闭cURL资源,并且释放系统资源
    curl_close($ch);
    return $output;
}

3.配置文件

<?php
/**
 * 地图相关配置文件
 */
return [
    'ak' => 'ak',
    'baidu_map_url' => 'http://api.map.baidu.com/',
    'geocoder' => 'geocoder/v2/',
    'width' => 400,
    'height' => 300,
    'staticimage' => 'staticimage/v2',
];




阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: