我这里的使用场景是校验所选经纬度是否所属于规定的省市区下面
获取区域code码进行比对
- 封装的查询类
<?php
namespace app\common\library;
/**
* @name: 经纬度查询类
* @author: Turbo
* @Date: 2022-09-20 10:44:36
*/
class SelectLngLatData
{
protected static $instance;
/**
* @var array 配置
*/
protected $option = [];
/**
* @var int 当前时间
*/
protected $time = 0;
/**
* @var string 错误信息
*/
protected $errorMessage = '';
public function __construct($lng = 0, $lat = 0)
{
$this->time = time();
$this->option['lng'] = $lng;
$this->option['lat'] = $lat;
}
private function __clone()
{
// TODO: Implement __clone() method.
}
/**
* 初始化
* @param str $lng 经度
* @param str $lat 纬度
* @return SelectLngLatData
*/
public static function instance($lng = 0, $lat = 0)
{
if (is_null(self::$instance)) {
self::$instance = new static($lng, $lat);
}
return self::$instance;
}
public function getLongLatInfo()
{
if (!empty($this->option['lng'])) {
$longitude = $this->option['lng'];
} else {
$this->setError('请传输经度');
return false;
}
if (!empty($this->option['lat'])) {
$latitude = $this->option['lat'];
} else {
$this->setError('请传输纬度');
return false;
}
$longitude = number_format(doubleval($longitude), 6);
$latitude = number_format(doubleval($latitude), 6);
$key = '这里填KeyKey'; // 腾讯地图key值
$url = 'https://apis.map.qq.com/ws/geocoder/v1?key=' . $key . '&location=' . $latitude . ',' . $longitude;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
$content = curl_exec($ch);
curl_close($ch);
if (!empty($content)) {
$result = json_decode($content, true);
if ($result['status'] == 0) {
return $result['result'];
} else {
$this->setError($result['message']);
return false;
}
} else {
$this->setError('经纬度不合法,请重新尝试');
return false;
}
}
/**
* 设置错误信息
* @param string $msg 错误信息
*/
protected function setError($msg)
{
$this->errorMessage = $msg;
}
/**
* 设置错误信息
* @return string 错误信息
*/
public function getError()
{
return $this->errorMessage;
}
}
- 进行调用(举个例子)
$params = $this->request->post();
$SelectLngLatDataLib = SelectLngLatData::instance($params['lng'], $params['lat']);
if(!$res = $SelectLngLatDataLib->getLongLatInfo()){
$this->error($SelectLngLatDataLib->getError()); // 抛出异常
}else{
$district = ''; // 指定的区县范围
if ($res['ad_info']['adcode'] != $district) {
$this->error('选中的坐标不在片区的省市区范围内,请选择正确的坐标'); // 抛出异常
}
}
// 通过检验.........
版权声明:本文为qq_15957557原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。