1.ionic项目打包apk,通过apk查看对应的sha1签名(可以通过androstudio,或者解压apk,cmd命令行进入\META-INF文件夹,执行keytool -printcert -file CERT.RSA可查看),在高德地图获取key中 ,发布版安全sha1和调试版安全码都用这个,这样就可以获取正确的key(之前不懂在这个key上花了好久时间)
2给ionic项目搭建高德地图环境
cordova plugin add https://github.com/DaiHuaXieHuaKai/GaoDeLocation.git --variable API_KEY=xxxxx(高德地图申请的key)
npm install @ionic-native/gao-de-location
然后就是引用了
app.module.ts
import { GaoDeLocation } from '@ionic-native/gao-de-location/ngx';
@NgModule({
...
providers: [
GaoDeLocation,
.....
],
...
})
在需要的组件或者页面
xxx.ts
import { GaoDeLocation,PositionOptions,LocationProtocolEnum,LocationModeEnum,DesiredAccuracyEnum,PositionRes } from '@ionic-native/gao-de-location/ngx';
constructor( public gaoDeLocation: GaoDeLocation) {}
//await this.gaoDeLocation.getCurrentPosition.... 需要放在async 类型的方法里面
async loc1(){
//引用高德插件获取定位
//可以参考该链接 https://ionicframework.com/docs/native/gao-de-location
//我这边的cordova 安装插件方法不一样 之前用文档这个好像生成的插件有问题 就换成上面git获取那种方法
let positionOptions: PositionOptions = {
androidOption: {
locationMode: LocationModeEnum.Hight_Accuracy,
gpsFirst: false,
HttpTimeOut: 30000,
interval: 2000,
needAddress: true,
onceLocation: false,
onceLocationLatest: false,
locationProtocol: LocationProtocolEnum.HTTP,
sensorEnable: false,
wifiScan: true,
locationCacheEnable: true
}, iosOption: {
desiredAccuracy: DesiredAccuracyEnum.kCLLocationAccuracyBest,
pausesLocationUpdatesAutomatically: 'YES',
allowsBackgroundLocationUpdates: 'NO',
locationTimeout: 10,
reGeocodeTimeout: 5,
}
};
let positionRes: PositionRes = await this.gaoDeLocation.getCurrentPosition(positionOptions).catch((e: any) => {
console.log(e);
}) || null;
alert(JSON.stringify(positionRes))
// this.gaoDeLocation.getCurrentPosition(positionOptions).catch((e: any) => {
// console.log(e);
// }) || null;
}
调用代码里面的loc1()就可以获取当前定位,这是要在手机上才可以,浏览器上打印出null,(模拟器没试过)
以上可以打出内容
有一个需要注意的是(如果不需要修改高德插件的key以下内容就无所谓):如果一开始
cordova plugin add https://github.com/DaiHuaXieHuaKai/GaoDeLocation.git --variable API_KEY=xxxxx(高德地图申请的key)
高德key错了 要重新修改,需要移除这个插件,细节就是移除的时候要带上之前的 高德key,不然就相当于卸载失败(虽然 cordova plugn ls 已经没有该插件(com.zhaoying.GaoDeLocation)了,但实际上没有删除干净),哪怕可以重新添加新key的插件(cordova plugin add https://github.com/DaiHuaXieHuaKai/GaoDeLocation.git --variable API_KEY=新key),这个新key也会不起作用,我在这里坑了好久(因为直接移除,cordova plugin rm com.zhaoying.GaoDeLocation,没带旧key,打包apk的时候会在生成的android项目的AndroidManifest.xml里面, <meta-data android:name="com.amap.api.v2.apikey" android:value="5xxxxxbb" />自动生成value是之前的key而不是新的,这表明原本的key信息没被移除)
正确移除方法如下:
cordova plugin rm com.zhaoying.GaoDeLocation -variable API_KEY=旧keyxxxxx(之前安装的高德key)
然后再重新装
cordova plugin add https://github.com/DaiHuaXieHuaKai/GaoDeLocation.git --variable API_KEY=新keyxxxxx