这里以百度静态图api,为例,百度静态图文档地址http://lbsyun.baidu.com/index.php?title=static
将百度地图封装成一个扩展类,可以随便调用, map类包含2个方法,获取经纬度和获取通过经纬度获取静态地图 在前台页面直接写入img地址 最后前台展示
Map.php类
<?php
/**
* Created by PhpStorm.
* User: 麦可叔叔
* Date: 2017/9/24
* Time: 22:48
*/
/*
* 百度地图业务封装
*/
class Map
{
/*
* 根据地址来获取经纬度
*/
public static function getLngLat($address){
//第三方接口地址示例
//http://api.map.baidu.com/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.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);
$result = file_get_contents($url); //$result = doCurl($url)
return $result;
}
}
控制器: 基于TP5
public function map()
{
return \Map::staticimage('南昌火车站');
}
前台直接调用
<img style="margin:20px" width="280" height="140" src='{:url('index/map')}'><img style="margin:20px" width="280" height="140" src='{:url('index/map')}'>
最后补充一下封装好的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;
}