Laravel 9 高德根据坐标获得定位

发布时间 2023-06-12 16:52:12作者: 一个退伍PHPsir
<?php

namespace App\Services;

use Illuminate\Http\Request;

class LocationService
{

    public function __construct()
    {
        $this->key = '********';
    }


    public function setLocation($longitude)
    {
        $longitude = $longitude ?? '113.571,34.81248';
        # 请求地址
        $url = 'https://restapi.amap.com/v3/geocode/regeo?key=' . $this->key . '&location=' . $longitude . '&radius=0';
        try {
            # 发送请求
            $data_location = json_decode(file_get_contents($url), true);
            # 返回数据状态1 为成功 0 为失败
            $local_status = $data_location['status'];
            //返回状态码 10000 为正确 其他为错误
            $code = $data_location['infocode'];
            $address = [];
            if ($local_status == 1 && $code == 10000) {
                $addressComponent = $data_location['regeocode']['addressComponent'];
                $address = [
                    'province' => $addressComponent['province'],
                    'city' => $addressComponent['city'],
                    'district' => $addressComponent['district'],
                    'township' => $addressComponent['township']
                ];
                return $address;
            } else {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }

}