当前位置: 代码迷 >> 综合 >> ionic+cordova定位插件的使用
  详细解决方案

ionic+cordova定位插件的使用

热度:85   发布时间:2023-11-05 00:18:40.0

网上可以搜到好多,不过能直接用的没几个,可能是新手的锅吧,折腾了几天才做出来,梳理一下吧。

ios的直接用官网的定位插件就行,只有ios的能使用,Android不能定位,并且坐标为Google坐标。命令如下:

ionic cordova plugin add cordova-plugin-geolocation
npm install --save @ionic-native/geolocation

 获取位置信息的调用方法:

/*ios定位插件,GPS定位,需要手机测试效果*/
getLocation() {this.geolocation.getCurrentPosition().then((resp) => {console.log('GPS定位:您的位置是 ' + resp.coords.longitude + ',' + resp.coords.latitude);let x = resp.coords.longitude;let y = resp.coords.latitude;this.transBd(x, y);//获取数据,并将Google坐标转成百度坐标使用。}).catch(e => {console.log("获取定位失败" + e);});
}

android定位就比较麻烦一些了,我用的百度地图的定位插件,同样先进行插件引入。 这里的key申请的时候要是web端的key,不能是android的key。也可以用我的先试一下。

定位插件,百度地图定位插件:

cordova plugin add https://github.com/liangzhenghui/cordova-qdc-baidu-location -variable API_KEY="7wPXnti8wNvttfVpEeWI3h9Ej4Vksx7X"

或者用文件的方式:

cordova plugin add F:\cordova-qdc-baidu-location-master -variable API_KEY="7wPXnti8wNvttfVpEeWI3h9Ej4Vksx7X" 

 调用方法如下:

getBaidulocation() {this.httpService.getGpsModule().then(resp => {console.log(resp);//获取的位置信息let data = JSON.parse(resp + "");alert(data);}).catch(error => {console.log("未获取位置信息");});
}

 其中httpService是我自己定义的一个公共ts,代码如下:

getGpsModule() {return new Promise(function (resolve, reject) {baidu_location.getCurrentPosition(function (data) {let resp = JSON.stringify(data);console.log(resp);resolve(resp);}, function (error) {console.log('Error getting location', error);reject("定位失败");});});
}

 其中baidu_location要在import下面声明一下:

declare let baidu_location: any;//定位插件

 

  相关解决方案