Ionic7 capacitor Geolocation插件无法得到GPS信息问题
kelvin 发布于 2024-03-28

记得以前在Ionic3或者Ionic4中使用Cordova框架,安装Geolocation插件,获取GPS位置是正常的,最近使用Ionic7,使用Capacitor框架,安装了Geolocation插件之后却发现无法得到GPS位置信息,上一篇文章还嫌打包的时候打开Android Studio,不过这下调试反而方便了。

启动Android Studio直接运行到设备,然后运行Example代码

import { Geolocation } from '@capacitor/geolocation';

const printCurrentPosition = async () => {
  const coordinates = await Geolocation.getCurrentPosition();

  console.log('Current position:', coordinates);
};

在Android Studio  Logcat下看了日志,终于发现了问题

io.ionic.starter                     D  Sending plugin error: {"save":false,"callbackId":"120511265","pluginId":"Geolocation","methodName":"getCurrentPosition","success":false,"error":{"message":"Google Play Services not available"}}

Capacitor/Console       io.ionic.starter                     E  File: https://localhost/main.9541f285b9f93bc1.js - Line 1 - Msg: ERROR Error: Google Play Services not available

查了说Google Play Services开启就可以,但在红米手机上已经开启谷歌基础服务,再运行还是无法获取到。

而如果用原生的Android开发,直接使用Android SDK对应的API,却可以正常获取到GPS位置,

在node_modules/@capacitor/geolocation下的build.gradle文件里面的dependencies的implementation中可以看到使用com.google.android.gms:play-services-location,

dependencies {

    implementation fileTree(dir: 'libs', include: ['*.jar'])



    if (System.getenv("CAP_PLUGIN_PUBLISH") == "true") {

        implementation "com.capacitorjs:core:$capacitorVersion"

    } else {

        implementation project(':capacitor-android')

    }



    implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"

    implementation "com.google.android.gms:play-services-location:$playServicesLocationVersion"

    testImplementation "junit:junit:$junitVersion"

    androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"

    androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"

}

原生的Android SDK获取GPS应该不是使用google服务,而Capacitor框架的Geolocation用的是google play service,暂时还不知道google play service应该怎么在国产手机真正可以用到,还是根本就无法用到,或许实在不行直接自己写个Capacitor插件可能还简单,因为Capacitor据说比Cordova访问原生api更容易编写。

kelvin
关注 私信
文章
92
关注
0
粉丝
0