简体   繁体   English

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

[英]ionic app google maps displaying - mobile device location issue

I am developing an android app with Ionic Cordova and Angular .我正在使用Ionic Cordova 和 Angular开发一个 android 应用程序。 in one of the page my requirement is to display google map with current location.在其中一个页面中,我的要求是显示带有当前位置的谷歌地图。

So by installing ionic Cordova google map and geolocation plugins and with the google maps API key and iam able to display google map in one of page with current location.因此,通过安装ionic Cordova 谷歌地图和地理定位插件并使用谷歌地图 API 密钥,我能够在具有当前位置的页面之一中显示谷歌地图。 This is working fine if the mobile device location is ON.如果移动设备位置处于开启状态,这将正常工作。 Incase of mobile device is off and we opened this map page (having location in the mobile off), it continuously loading with the message Fetching your Location and strucking there itself.万一移动设备关闭并且我们打开了这个地图页面(在移动设备中关闭了位置),它会不断加载消息获取您的位置并自行到达那里。

加载截图

I want Mobile App should display alert message to user that location in Mobile is OFF when opened the map page with mobile device location off.我希望移动应用程序应该移动设备位置关闭的情况下打开地图页面时向用户显示移动中的位置关闭的警报消息

below is the code i tried:下面是我试过的代码:

Plugins imported in app.module.ts page在 app.module.ts 页面中导入的插件

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

In page.ts file在 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
    }
  }




  }

In HTML :在 HTML 中:

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

 </div>

 </ion-content>

please help me on this, how can i show message to the user to turn on his mobile location.请帮我解决这个问题,我如何向用户显示消息以打开他的移动位置。

thanks a lot多谢

Try this尝试这个

  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);
            }
          );
      });
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM