高德

    //计算两地之间的距离$origin = 开始距离,$destination=结束距离
    function calculateDistance($origin = '', $destination = '') {
        if($origin == '' || $destination == ''){
            return false;
        }
       
        //高德的web端key
        $key = 'c9a53fff9e2c9c1fda3bad038a9c6f8e';
        $url = "http://restapi.amap.com/v5/direction/driving?key=$key&origin=$origin&destination=$destination";
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            return false;
        }
        curl_close($ch);
        $responseData = json_decode($response,true);
       
        if ($responseData['status'] === '1' && $responseData['info'] === 'OK') {
            // 输出距离,单位为米
            $info = $responseData['route']['paths'][0]['distance'];
            //转换单位
            if ($info >= 1000) {
                $res = number_format($info / 1000, 2, '.', '') . ' km';
            }else{
                $res = $info . ' m';
            }
            return $res;
        } else {
            return false;
        }
    }

 

posted @ 2024-07-09 20:26  祈愿仙帝  阅读(12)  评论(0编辑  收藏  举报