<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/7 0007
 * Time: 11:27
 */

namespace app\modules\third\map;

class Baidu
{
    private $ak = 'qDOgsklMfHrvGZRs7ZXDlG0UlKaqEnga';

    private $url = 'http://api.map.baidu.com/geocoder/v2/';
    private $url2 = 'http://api.map.baidu.com/geoconv/v1/';

    /**
     * location
     * 38.76623,116.43213 lat<纬度>,lng<经度>
     * 根据经纬度坐标获取地址
     * http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=39.983424,116.322987&output=json&pois=1&ak=您的ak
     *
     * */
    public function renderReverse($lat, $lng)
    {
        try {
            $data = [
                'coordtype' => '',
                'callback' => 'renderReverse',
                'location' => $lat . ',' . $lng,
                'output' => 'json',
                'ak' => $this->ak
            ];

            return json_decode($this->curlPost($this->url, $data), true);
        } catch (\Exception $e) {
            \Yii::warning('百度获取地址错误' . $e->getMessage());
            return ['status' => 1];
        }
    }

    /**
     *坐标转换
     * http://api.map.baidu.com/geoconv/v2/?coords=114.21892734521,29.575429778924;114.21892734521,29.575429778924&from=1&to=5&ak=你的密钥
     *
     * */
    public function geoChange($lng, $lat)
    {
        $data = [
            'coords' => $lng . ',' . $lat,
            'output' => 'json',
            'from' => '1',
            'to' => '5',
            'ak' => $this->ak
        ];

        return json_decode($this->curlPost($this->url2, $data), true);
    }

    public function curlPost($url, $postFields)
    {

        $postFields = http_build_query($postFields);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);
        $result = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if ($error) {
            \Yii::warning('百度地图经纬度转换出错:' . $error.' 参数:'.json_encode($postFields));
        }
        return $result;
    }
}
