AutoGetLocationInfoJob.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\Http\Models\ArticleLog;
  5. use Log;
  6. class AutoGetLocationInfoJob extends Command
  7. {
  8. protected $signature = 'command:autoGetLocationInfoJob';
  9. protected $description = '自动获取经纬度对应的地址信息';
  10. public function __construct()
  11. {
  12. parent::__construct();
  13. }
  14. public function handle()
  15. {
  16. $articleLogList = ArticleLog::query()->where('is_pull', 0)->get();
  17. foreach ($articleLogList as $articleLog) {
  18. $url = $this->makeUrl($articleLog->lat, $articleLog->lng);
  19. $ret = file_get_contents($url);
  20. $result = json_decode($ret, true);
  21. Log::info(var_export($result, true));
  22. if ($result['status']) {
  23. Log::error('文章日志通过API获取坐标对应的地址信息失败.');
  24. continue;
  25. }
  26. // 更新日志信息
  27. $data = [
  28. 'nation' => $result['result']['address_component']['nation'],
  29. 'province' => $result['result']['address_component']['province'],
  30. 'city' => $result['result']['address_component']['city'],
  31. 'district' => $result['result']['address_component']['district'],
  32. 'street' => $result['result']['address_component']['street'],
  33. 'street_number' => $result['result']['address_component']['street_number'],
  34. 'address' => $result['result']['address'],
  35. 'full' => $ret,
  36. 'is_pull' => 1
  37. ];
  38. ArticleLog::query()->where('id', $articleLog->id)->update($data);
  39. // 休眠0.2秒,防止QPS超限导致返回错误
  40. usleep(200000);
  41. }
  42. Log::info('定时任务:' . $this->description);
  43. }
  44. // 生成坐标查询URL
  45. private function makeUrl($lat, $lng)
  46. {
  47. $coordinate = $this->translate($lat, $lng);
  48. $url = "http://apis.map.qq.com/ws/geocoder/v1/?location={$coordinate['lat']},{$coordinate['lng']}&key=XXXX";
  49. return $url;
  50. }
  51. /**
  52. * 地图坐标系转换
  53. * 百度地图(BD09)转腾讯地图(GCJ02)坐标系
  54. * @param double $lat 纬度
  55. * @param double $lng 经度
  56. * @return array
  57. **/
  58. private function translate($lat, $lng)
  59. {
  60. $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
  61. $x = $lng - 0.0065;
  62. $y = $lat - 0.006;
  63. $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
  64. $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
  65. $lng = $z * cos($theta);
  66. $lat = $z * sin($theta);
  67. return ['lat' => $lat, 'lng' => $lng];
  68. }
  69. }