离子应用谷歌地图显示 - 移动设备位置问题

Posted

技术标签:

【中文标题】离子应用谷歌地图显示 - 移动设备位置问题【英文标题】:ionic app google maps displaying - mobile device location issue 【发布时间】:2021-01-24 12:39:34 【问题描述】:

我正在使用 Ionic Cordova 和 Angular 开发一个 android 应用程序。在其中一个页面中,我的要求是显示带有当前位置的谷歌地图。

因此,通过安装 ionic Cordova 谷歌地图和地理定位插件 并使用 谷歌地图 API 密钥,我可以在具有当前位置的页面之一中显示谷歌地图。如果移动设备位置处于打开状态,则此功能可以正常工作。如果移动设备处于关闭状态并且我们打开此地图页面(在移动设备中关闭位置),它会不断加载消息 Fetching your Location 并自行触发。

我希望移动应用程序在移动设备位置关闭的情况下打开地图页面时向用户显示移动设备中的位置已关闭的警告消息

下面是我试过的代码:

app.module.ts 页面中导入的插件

import  GoogleMaps  from '@ionic-native/google-maps/ngx';
import  Geolocation  from '@ionic-native/geolocation/ngx';

在 page.ts 文件中

import  Component, OnInit, NgZone, ViewChild, OnDestroy  from '@angular/core';
   declare var google;

import 
 ToastController,
 Platform,
 LoadingController,
 AlertController
 from '@ionic/angular';
import 
 GoogleMaps,
GoogleMap,
GoogleMapsEvent,
Marker,
GoogleMapsAnimation,
LocationService,
MyLocation,
GoogleMapOptions,
LatLng,
Environment
  from '@ionic-native/google-maps/ngx';
 import  NativeGeocoder, NativeGeocoderOptions, NativeGeocoderResult  from 
 '@ionic-native/native-geocoder/ngx';

import  Router  from '@angular/router';
import  SelectedPickupPoint  from 'src/app/models/map.model';
 import  HelperService  from 'src/app/services/helper.service';
 import  ApiService  from 'src/app/services/api/api.service';
 import  PickupPoint  from 'src/app/models/pickupPoint.model';
 import  Subscription  from 'rxjs';

  @Component(
selector: 'app-pickup-map',
  templateUrl: './pickup-map.page.html',
  styleUrls: ['./pickup-map.page.scss'],
    )
    export class PickupMapPage implements OnInit, OnDestroy 

   @ViewChild('map_canvas',  static: true ) mapElement: any;
private myLocation: MyLocation;
private loading: any;
private map: GoogleMap;
public search: string = '';
private googleAutocomplete = new google.maps.places.AutocompleteService();
pickupPointsData: Array<PickupPoint>;
public searchResults = new Array<any>();
private pickUpPointsSubscription: Subscription;

constructor(
public toastCtrl: ToastController,
private platform: Platform,
private loadingCtrl: LoadingController,
private ngZone: NgZone,
private nativeGeocoder: NativeGeocoder,
public router: Router,
private helperService: HelperService,
private apiService: ApiService,
private alertController: AlertController

)

 ngOnInit() 
this.helperService.showLoader('Fetching your location');
this.mapElement = this.mapElement.nativeElement;
this.getUserLocation().then(
  res => 
    
    this.myLocation = res;
    this.helperService.hideLoader();
    return this.myLocation;
  
).then(
  res => 
    this.apiService.pickupList(this.apiService.loggedInUser.value.id, this.myLocation.latLng.lat, this.myLocation.latLng.lng, this.selectedRadius)
      .then(
        res => 
          // alert('ONINITRESP' + JSON.stringify(res));
          this.pickUpPointsSubscription = this.apiService.castpickUpPointsList.subscribe(
            data => 
              // alert('uppper' + JSON.stringify(data));
              if (data.length === 0) 
                this.pickupPointsData = data;
                this.loadMapWithoutMarkers(this.myLocation.latLng.lat, this.myLocation.latLng.lng).then(
                  res => 
                    alert('There are no pickup points in this location, Please try with a different one or change the Radius');
                  
                );
               else if (data.length !== 0) 
                this.nearestCenter = data[0];
                this.pickupPointsData = data;
                try 
                  this.loadMap(this.myLocation.latLng.lat, this.myLocation.latLng.lng);
                 catch (err) 
                  alert(err);
                 finally 
                  this.loading.dismiss();
                
              
            ,
            error => 
               alert(JSON.stringify(error));
            );
        ,
        err => 
           alert(err);
          
        )
    
  )






  async getUserLocation(): Promise<MyLocation> 
   let myLocation: MyLocation = await LocationService.getMyLocation();
   return myLocation;
  

 async loadMapWithoutMarkers(latitude, longitude) 
  this.loading = await this.loadingCtrl.create(
  message: 'Loading Map. Please wait...'
   )
    await this.loading.present();

   try 
  const mapOptions: GoogleMapOptions = 
    controls: 
      zoom: false
    
  
  if (!this.map) 
    this.map = GoogleMaps.create(this.mapElement, mapOptions);
  
  this.addOriginMarker(latitude, longitude);
  this.loading.dismiss();
 catch (error) 
  alert(error);
  this.loading.dismiss();
 
 

 async loadMap(latitude, longitude) 
 this.loading = await this.loadingCtrl.create(
  message: 'Loading Map. Please wait...'
  )
  await this.loading.present();
   const mapOptions: GoogleMapOptions = 
    controls: 
    zoom: false
    
  




  

在 HTML 中:

<ion-content>
<div #map_canvas id="map_canvas">

 </div>

 </ion-content>

请帮助我,我如何向用户显示消息以打开他的移动位置。

非常感谢

【问题讨论】:

请添加完整的 page.ts 代码,您获得该地图代码的来源是什么? 我会用谷歌地图标记当前位置 请在此处分享链接 嗨 @ Janitha Rasanga,我正在通过构建 android apk 进行检查,没有测试链接。 请添加page.ts完整代码 【参考方案1】:

试试这个

  ngOnInit() 
    this.helperService.showLoader("Fetching your location");
    this.mapElement = this.mapElement.nativeElement;
    this.getUserLocation()
      .then((res) => 
        this.myLocation = res;
        this.helperService.hideLoader();
        return this.myLocation;
      )
      .catch((error) => 
          console.log('Error getting location', error);
          this.helperService.hideLoader();

          //alert message code goes here

      )
      .then((res) => 
        this.apiService
          .pickupList(
            this.apiService.loggedInUser.value.id,
            this.myLocation.latLng.lat,
            this.myLocation.latLng.lng,
            this.selectedRadius
          )
          .then(
            (res) => 
              // alert('ONINITRESP' + JSON.stringify(res));
              this.pickUpPointsSubscription = this.apiService.castpickUpPointsList.subscribe(
                (data) => 
                  // alert('uppper' + JSON.stringify(data));
                  if (data.length === 0) 
                    this.pickupPointsData = data;
                    this.loadMapWithoutMarkers(
                      this.myLocation.latLng.lat,
                      this.myLocation.latLng.lng
                    ).then((res) => 
                      alert(
                        "There are no pickup points in this location, Please try with a different one or change the Radius"
                      );
                    );
                   else if (data.length !== 0) 
                    this.nearestCenter = data[0];
                    this.pickupPointsData = data;
                    try 
                      this.loadMap(
                        this.myLocation.latLng.lat,
                        this.myLocation.latLng.lng
                      );
                     catch (err) 
                      alert(err);
                     finally 
                      this.loading.dismiss();
                    
                  
                ,
                (error) => 
                  alert(JSON.stringify(error));
                
              );
            ,
            (err) => 
              alert(err);
            
          );
      );
  

【讨论】:

嗨@Janitha Rasanga,非常感谢您抽出宝贵时间帮助我。它工作完美,但出现错误无法读取属性 unsubscribe of undefined 时返回后页 看看..给我时间 非常感谢@Janitha Rasanga,当我们解除位置警报并单击确定时,是否可以返回其他页面 yaa 那也可以..在那之前试试这个。调用 this.apiService.castpickUpPointsList.unsubscribe();在 ngOnDestroy() 中 是的,我已经尝试添加 pointlist.unsubscribe() 错误已得到纠正。现在我想在我们确定位置警报消息关闭时重定向到主页(home.page.html)。

以上是关于离子应用谷歌地图显示 - 移动设备位置问题的主要内容,如果未能解决你的问题,请参考以下文章

离子混合移动应用程序获取设备位置

谷歌地图应用无法在移动设备上打开网页链接

谷歌地图移动视图

离子框架:不在设备上加载谷歌地图库

如何在移动设备的混合应用程序中使用谷歌地图 API

移动设备:获取位置