1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > php地图封装 百度地图应用封装——静态图api

php地图封装 百度地图应用封装——静态图api

时间:2020-02-23 15:50:35

相关推荐

php地图封装 百度地图应用封装——静态图api

将百度地图封装成一个扩展类,可以随便调用, map类包含2个方法,获取经纬度和获取通过经纬度获取静态地图 在前台页面直接写入img地址 最后前台展示

Map.php类

/**

* Created by PhpStorm.

* User: 麦可叔叔

* Date: /9/24

* Time: 22:48

*/

/*

* 百度地图业务封装

*/

class Map

{

/*

* 根据地址来获取经纬度

*/

public static function getLngLat($address){

//第三方接口地址示例

//http://api./geocoder/v2/?address=北京市海淀区上地十街10号&output=json&ak=你的ak&callback=showLocation

$data=[

'address' => $address,

'output' => 'json',

'ak' => config('map.ak')

];

// 转换成上面形式

$url = config('map.baidu_map_url').config('map.geocoder').'?'.http_build_query($data);

//获取url的内容有2种方法,

// 第一种:直接使用file_get_contents($url)。

// 第二种:封装curl的处理方法。

$result = file_get_contents($url); //$result = doCurl($url)

if($result){

return json_decode($result,true);

}else{

return [];

}

}

/** http://api./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);

$result = file_get_contents($url); //$result = doCurl($url)

return $result;

}

}

控制器: 基于TP5

public function map()

{

return \Map::staticimage('南昌火车站');

}

前台直接调用

最后补充一下封装好的doCurl方法

/*

* 百度地图所用的curl方法

* int $type 0 get 1 post

*/

function doCurl($url, $type=0, $data=[]) {

$ch = curl_init(); // 初始化

// 设置选项

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);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

}

//执行并获取内容

$output = curl_exec($ch);

// 释放curl句柄

curl_close($ch);

return $output;

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。