🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 1.首先简单封装一个发送curl的方法 ```php /** * 发送curl网络请求 * @param $url string 请求地址 * @param $type int 0:get 1:post * @param $data array post方式提交的数据 * @return array|json */ function doCurl($url, $type=0, $data=[]){ //初始化curl $ch = curl_init(); //curl参数设置 curl_setopt($ch, CURLOPT_URL, $url);//curl请求的url curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置放回值,不输出结果 curl_setopt($ch, CURLOPT_HEADER, 0);//不缓存响应头 //如果是post请求 if($type==1){ curl_setopt($ch, CURLOPT_POST, 1);//设置post方式 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//post方式提交的数组 } //执行curl发送请求 $output = curl_exec($ch); //释放当前curl句柄 curl_close($ch); //放回请求到的数据 return $output; } ``` ## 2.extend中新建Map.php类,封装百度地图api接口 ```php <?php /** * 百度地图api接口封装 */ use think\Config; class Map{ //通过地址获取经纬度信息(地理编码) public static function getLngLat($address) { if($address == ""){ return ""; } //http://api.map.baidu.com/geocoding/v3/?address=北京市海淀区上地十街10号&output=json&ak=您的ak&callback=showLocation //GET请求 $data = [ 'address' => $address, 'output' => 'json', 'ak' => Config::get('map.ak'), 'callback' => 'showLocation' ]; $query = http_build_query($data);//转化为url后的参数 $url = Config::get('map.baidu_map_url').Config::get('map.geocoding').'?'.$query; //发送网络请求: 1.file_get_content 2.curl //$result = file_get_contents($url); $result = doCurl($url); return $result; } /**通过经纬度或地址 去生成静态地图 (静态图) * http://api.map.baidu.com/staticimage/v2?ak=你的ak&mcode=666666&center=116.403874,39.914888&width=300&height=200&zoom=11 **/ public static function staticImage($center) { if($center == ""){ return ""; } $data = [ 'ak' => Config::get('map.ak'), 'width' => config('map.width'), 'height' => config('map.height'), 'center' => $center, 'markers' => $center, 'staticimage' => config('map.staticimage') ]; $query = http_build_query($data); $url = Config::get('map.baidu_map_url').Config::get('map.staticimage').'?'.$query; $result = doCurl($url); return $result; } } ``` ## 3.配置map的信息写在了extra下的map.php中 ```php <?php //百度地图api配置 return [ 'ak' => '你的百度ak', 'baidu_map_url' => 'http://api.map.baidu.com/', 'geocoding' => 'geocoding/v3/', 'width' => 400, 'height' => 300, 'staticimage' => 'staticimage/v2' ]; ``` ## 4.控制器中调用 已admin/index控制器为例 ```php <?php namespace app\admin\controller; use think\Controller; class Index extends Controller { .... //测试静态图生成 public function map() { return \Map::staticImage('广州市天河区车陂大塘后街10号'); } //测试路由 public function test() { return \Map::getLngLat('广州市天河区车陂地铁C出口'); } } ``` html中展示静态图 ```html <img style="margin:20px" width="280" height="140" src="{:url('/admin/index/map')}"/> ```