Ionic集成Google地图与地理定位报错:Object(...) is not a function
问题描述
我正在开发一个类似Runastic的运动课程项目,原本计划基于Ionic 4 + Angular开发,但实际使用的是Ionic 3.9.5版本。我按照教程集成了Google地图功能,目前地图运行正常,但在实现地理定位功能时遇到了以下错误:
Error: Uncaught (in promise): TypeError: Object(...) is not a function
TypeError: Object(...) is not a function
at Geolocation.Array.concat.Geolocation.getCurrentPosition (http://localhost:8100/build/0.js:9874:143)
at GeolocationPage.Array.concat.GeolocationPage.ngAfterViewInit
我的系统配置:
- Ionic Framework: 3.9.5
- Ionic App Scripts: 3.2.2
- Angular Core: 5.2.11
- Angular Compiler CLI: ^7.2.15
- Node: 10.15.2
解决方案
这个错误的核心原因是你使用了为Ionic 4/Angular 6+设计的依赖包版本,与当前Ionic 3+Angular 5的环境不兼容,以下是具体修复步骤:
1. 降级Geolocation插件到兼容版本
Ionic 3对应的@ionic-native/geolocation需要使用4.x版本,而非适配Ionic 4的5.x+版本:
# 卸载当前不兼容版本 npm uninstall @ionic-native/geolocation # 安装适配Ionic 3的版本 npm install @ionic-native/geolocation@4.20.0 --save
2. 确保正确的导入与使用方式
在Ionic 3中,Geolocation的使用逻辑和Ionic 4略有差异,检查你的代码是否符合以下规范:
在app.module.ts中注册服务:
import { Geolocation } from '@ionic-native/geolocation'; @NgModule({ declarations: [...], imports: [...], bootstrap: [...], entryComponents: [...], providers: [ ..., Geolocation // 将Geolocation添加到全局服务列表 ] }) export class AppModule {}
在地图页面组件中调用定位:
import { Geolocation } from '@ionic-native/geolocation'; constructor(private geolocation: Geolocation) {} ngAfterViewInit() { this.geolocation.getCurrentPosition() .then((resp) => { // 处理定位成功的结果 console.log('当前纬度:', resp.coords.latitude); console.log('当前经度:', resp.coords.longitude); }) .catch((error) => { console.error('获取位置失败:', error); }); }
3. 修复Angular Compiler版本冲突
你的Angular Core是5.2.11,但Compiler CLI是7.2.15,版本不匹配可能导致编译和运行时错误,建议降级Compiler CLI到对应版本:
npm install @angular/compiler-cli@5.2.11 --save-dev
4. 确认原生插件已正确安装
Ionic 3依赖Cordova原生插件实现地理定位,确保你已安装对应的插件:
ionic cordova plugin add cordova-plugin-geolocation
内容的提问来源于stack exchange,提问作者Rapishiny

