TxMapServer.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * 腾讯地图模块
  4. */
  5. namespace App\Servers;
  6. class TxMapServer
  7. {
  8. private $key = '6MABZ-FUWKJ-XB2FT-FOT46-HDXU5-HHBLO';
  9. static private $server = null;
  10. function __construct()
  11. {
  12. }
  13. /**
  14. * 创建对象
  15. * @return TxMapServer
  16. */
  17. static function creatServer()
  18. {
  19. if (empty(self::$server)) self::$server = new TxMapServer();
  20. return self::$server;
  21. }
  22. /**
  23. * 获取定位信息
  24. * @param $ip
  25. * @return mixed
  26. */
  27. function getLocation($ip)
  28. {
  29. $url = 'https://apis.map.qq.com/ws/location/v1/ip';
  30. $data = $this->sendRequest($url, 'get', ['ip' => $ip]);
  31. return $data;
  32. }
  33. /**
  34. * 根据经纬度获取地理位置信息
  35. * @param $lat
  36. * @param $lng
  37. * @return mixed
  38. */
  39. function getLocationAddress($lat, $lng)
  40. {
  41. $url = 'https://apis.map.qq.com/ws/geocoder/v1/';
  42. $data = $this->sendRequest($url, 'get', ['location' => "{$lat},{$lng}"]);
  43. return $data;
  44. }
  45. /**
  46. * @param $url
  47. * @param string $type 请求方式
  48. * @param string $data 数据 数组格式
  49. * @return mixed
  50. */
  51. protected function sendRequest($url, $type = 'get', $data = [])
  52. {
  53. $data['key'] = $this->key;
  54. $ch = curl_init();
  55. if ($type == 'get' && $data) {
  56. $url = $url . '?' . http_build_query($data);
  57. }
  58. curl_setopt($ch, CURLOPT_URL, $url); //设置访问路径
  59. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //设置可以返回字符串
  60. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  61. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  62. $head = array('User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36');
  63. curl_setopt($ch, CURLOPT_HTTPHEADER, $head);
  64. if ($type == 'post') {
  65. curl_setopt($ch, CURLOPT_POST, TRUE);//post请求
  66. $data = json_encode($data, JSON_UNESCAPED_UNICODE);
  67. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置传递的参数
  68. }
  69. $request = curl_exec($ch);
  70. curl_close($ch);
  71. $request = json_decode($request, true);
  72. return $request;
  73. }
  74. }