Phonegap Geolocation连接到Server API

时间:2016-02-24 01:39:37

标签: javascript php cordova phonegap-plugins phonegap-build

在移动应用中,我为连接到网络服务器API的搜索结果添加了GeoLocation,但它总是返回"不可用"。

的Javascript

function getCurrentLocation()
{   
    navigator.geolocation.getCurrentPosition(geolocationSuccess,geolocationError, 
    { enableHighAccuracy: true } ); 
}

function geolocationSuccess(position)
{
    var params="lat="+position.coords.latitude;
    params+="&lng="+position.coords.longitude;
    callAjax("reverseGeoCoding",params);
}

function geolocationError(error)
{
    alert('code: '    + error.code    + '\n' +
          'message: ' + error.message + '\n');
}

PHP(API方面)

public function actionReverseGeoCoding()
{       
    if (isset($this->data['lat']) && !empty($this->data['lng'])){
        $latlng=$this->data['lat'].",".$this->data['lng'];
        $file="https://maps.googleapis.com/maps/api/geocode/json?latlng=$latlng&sensor=true";
        if ($res=file_get_contents($file)){
            $res=json_decode($res,true);
            if (AddonMobileApp::isArray($res)){
                $this->code=1; $this->msg="OK";
                $this->details=$res['results'][0]['formatted_address'];
            } else  $this->msg=$this->t("not available");
        } else $this->msg=$this->t("not available");
    } else $this->msg=$this->t("missing coordinates");
    $this->output();
}

我已经在config.xml中定义了权限

<gap:plugin name="cordova-plugin-geolocation" />

请问任何建议?

@Banik的编辑示例

public function actionReverseGeoCoding()
{       
    if (isset($this->data['lat']) && !empty($this->data['lng'])){
        $latlng=$this->data['lat'].",".$this->data['lng'];
        $file="https://maps.googleapis.com/maps/api/geocode/json?latlng=".$latlng."&sensor=true";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $file);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
        curl_setopt($ch, CURLOPT_HEADER, 0); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
        $data = curl_exec($ch);
        if ($res==$data){
            $res=json_decode($res,true);
            if (AddonMobileApp::isArray($res)){
                $this->code=1; $this->msg="OK";
                $this->details=$res['results'][0]['formatted_address'];
            } else  $this->msg=$this->t("not available");
        } else $this->msg=$this->t("not available");
    } else $this->msg=$this->t("missing coordinates");
    $this->output();
}

0 个答案:

没有答案