mapsplugin / cordova-plugin-googlemaps

Google Maps plugin for Cordova
Apache License 2.0
1.66k stars 918 forks source link

Map freeze When navigating between page #2626

Closed gfavour closed 5 years ago

gfavour commented 5 years ago

Please help me out. I need to deliver this project. I am using google map sdk version 5 on ionic 4 to display map with multiple markers. When you search a location which have dropdown on homepage, and there is search result, previous markers are cleared and new ones are display on the map. All this work perfectly. My problem is. When you move from Home page that has the map to another page, and come back to home page, the map will show but freeze. It wouldn't allow you to scroll down or left or right or top.

Please see my code below; is a little complex; am using too account; this.globalUAT = 'u'; but if this.globalUAT = 'v';

map only appear for this.globalUAT = 'u'; so ignore anywhere you see code for this.globalUAT = 'v';

See my home.page.ts code below `import { UserProvider } from '../providers/user-provider'; import { AuthService } from '../providers/authService'; import { LocationTracker } from '../providers/tracker';

import { Component, HostBinding, OnInit, ViewChild, ElementRef} from '@angular/core'; import { trigger, state, style, animate, transition } from '@angular/animations';

import { NavController, LoadingController, Platform } from '@ionic/angular'; import { ActivatedRoute,Router } from '@angular/router'; import { Storage } from '@ionic/storage';

import { Geolocation } from '@ionic-native/geolocation/ngx'; import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderOptions } from '@ionic-native/native-geocoder/ngx'; import {GoogleMaps,GoogleMap,GoogleMapsEvent, GoogleMapOptions, GoogleMapsAnimation, Geocoder, CameraPosition, MarkerOptions, Marker, BaseArrayClass,ILatLng,HtmlInfoWindow } from '@ionic-native/google-maps/ngx'; import { FormControl, FormGroupDirective, FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms'; import { Diagnostic } from '@ionic-native/diagnostic/ngx'; import { CallNumber } from '@ionic-native/call-number/ngx'; import { NativeAudio } from '@ionic-native/native-audio/ngx';

import { DomSanitizer } from "@angular/platform-browser";

declare var google; declare var navigator: any;

@Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], animations: [ trigger('visibilityChanged', [ state('shown', style({ opacity: 1 })), state('hidden', style({ opacity: 0 })), transition(' => ', animate('500ms')) ])] }) export class HomePage implements OnInit {

@ViewChild('map_canvas') map_canvas: ElementRef; map: GoogleMap; myaddress:any=''; posts: any; mylat:any=''; mylng:any=''; noimage = '../../assets/noimage.svg'; initMyMap:any=''; watch:any; catalogs:any; groupArr:any=[]; seaForm: FormGroup; txtservice:any; usersrequests:any; noofrequest:any; mypaid:any; myunpaid:any; mynetincome:any;

public retMarkersData:any; public markers:any=[]; tasktimer:any; isOpen:any=false; choosevendor:any=""; choosevendorid:any=""; isRunning:any=false; isMapping:any=false; isVOLastLoading:any=false; initialMapLoad:boolean; globalUAT:any;

geoencoderOptions: NativeGeocoderOptions = { useLocale: true, maxResults: 5 };

constructor( private nativeAudio: NativeAudio, private apitracker: LocationTracker, public authService: AuthService, private api: UserProvider, private loader: LoadingController, private platform: Platform, private navCtrl: NavController, public router: Router, private storage: Storage, private geolocation: Geolocation, private nativeGeocoder: NativeGeocoder, private diagnostic: Diagnostic, public callno: CallNumber, private formBuilder: FormBuilder, private sanitizer: DomSanitizer){

    this.seaForm = this.formBuilder.group({
        txtservice: [null, Validators.required],
        txtmylat: [this.mylat],
        txtmylng: [this.mylng]
    });

    this.mylat = this.apitracker.GlobalLat;
    this.mylng = this.apitracker.GlobalLng;

    if(this.authService.globaluaccttype == 'u'){
        this.globalUAT = 'u';
    }else{
        this.globalUAT = 'v';
    }

    this.initMyMap = '';
    this.isMapping = false;
    this.FirstMapLoading();

}

async ngOnInit() { await this.platform.ready().then(()=>{ this.markers = []; this.catalogs = {};

    /*
    this.initMyMap = '';
    this.isMapping = false;
    this.FirstMapLoading();
    */

    if(this.authService.globaluaccttype == 'u'){
        this.globalUAT = 'u';
    }else{
        this.globalUAT = 'v';
        this.nativeAudio.preloadSimple('QSound', 'assets/sound/all.ogg').then(r=>{}, e=>{});
    }

    if(this.globalUAT == 'u'){
        this.api.getDetail(this.api.CATEGORIES).then((r)=>{
            this.catalogs = r;
            if(this.catalogs.length > 0){
                this.SortCatalog(this.catalogs);
            }else{
                this.LoadCatalog();
            }
        });
    }
}).catch(err => { console.log("Initializing Error..."); });

}

FirstMapLoading(){ if(this.globalUAT == 'u'){ let elat = 6.555510; let elng = 3.210360; if(this.mylat){ let elat = this.mylat; let elng = this.mylng; } if(!this.map){ console.log('map created'); this.map = GoogleMaps.create('map_canvas', { camera: {target: {lat:elat,lng:elng}, zoom: 15, tilt: 30},preferences:{zoom:{minZoom:0,maxZoom:20}} }); this.initialMapLoad = true; } } }

resetMapContainer(div:any,visible:boolean){ setTimeout(()=>{ if(this.map){ this.map.setDiv(this.map_canvas); this.map.setVisible(visible);console.log('map set and make visible'); } console.log('map timer 10002...'); },1000); }

ionViewWillEnter(){ if (!this.initialMapLoad) { console.log('map initial 2'); this.resetMapContainer('map_canvas',true); } else { this.initialMapLoad = false; console.log('map initial 1, now from true to false'); }

this.isOpen = false;
this.isRunning = false;
this.isVOLastLoading = false;
//this.initMyMap = '';
//this.isMapping = false;

this.mylat = this.apitracker.GlobalLat;
this.mylng = this.apitracker.GlobalLng;

if(this.authService.globaluaccttype == 'u'){
    this.globalUAT = 'u';
}else{
    this.globalUAT = 'v';
    this.api.VLastOrderID = 0;
    this.usersrequests = [];
}

if(this.globalUAT == 'u'){
    this.seaForm.get('txtmylat').setValue(this.mylat);
    this.seaForm.get('txtmylng').setValue(this.mylng);
    if(this.mylat){
        // this.getGeoencoder(this.mylat,this.mylng);
    }else{
        this.isRunning = true;
        this.loadMyLatLng();
    }
    // this.LoadLastNearestSearch();
}else{
    if(!this.mylat){
        this.isRunning = true;
        this.loadMyLatLng();
    }
}

}

ionViewDidEnter(){ this.CheckAllPermissions(); this.tasktimer = setInterval(() => { this.CheckAllPermissions(); }, 10000); }

ionViewWillLeave() { this.isRunning = false; this.isOpen = false; this.isVOLastLoading = false; //this.isMapping = false; this.ClearMarkers(); clearInterval(this.tasktimer);

if (this.map.getDiv()){
  //this.map.setVisible(false);
  this.map.setDiv();
}

}

async GetRecentCustomersOrders(){ let myId = this.authService.globaluid; let myvloid:any = this.api.VLastOrderID;

if(myId){
        this.isVOLastLoading = true;
        await this.api.getRecentVCOrders(myId,myvloid).subscribe((res)=>{ 
            if(res.code == 100){
                this.api.VLastOrderID = res.data[0].id;
                if(this.usersrequests && this.usersrequests.length > 0){
                    this.usersrequests = res.data.concat(this.usersrequests);
                }else{
                    this.usersrequests = res.data;
                }
                this.noofrequest = res.totalrequest;
                this.mynetincome = res.mynetincome;
                this.mypaid = this.authService.globaluwallet;
                this.myunpaid = res.myunpaid;
                this.nativeAudio.play('QSound').then(r=>{},e=>{});
                this.isVOLastLoading = false;
            }else{
                this.mypaid = this.authService.globaluwallet;
                this.isVOLastLoading = false;
                console.log("No more recent order");
            }
        },(err)=>{ console.log("Warning 109.."+err.message); this.isVOLastLoading = false; });
}

}

gotoOrderPage(){ this.router.navigate(['/order', this.choosevendorid]); }

async UpdateMyCoords(){ let gid = this.authService.globaluid; if(gid && this.mylat && this.mylng){
await this.api.SendCoords(gid,this.mylat,this.mylng).subscribe(()=>{ this.isRunning = false; },(err)=>{ this.isRunning = false; });
} }

async LoadLastNearestSearch(){ await this.api.getDetail("Nearest").then((dat)=>{ if(dat){ if(this.mylat && this.mylng){ let itemKm = this.api.getDistanceInKmFast(this.mylat,this.mylng,parseFloat(dat.lat),parseFloat(dat.lng)); this.choosevendor = dat.title+'
Nearest: '+itemKm.toFixed(2)+' km'; }else{ this.choosevendor = dat.title+'
Nearest: ? km'; this.api.ShowNotification("Please wait, still searching for your location...","light"); } this.choosevendorid = dat.id; this.isOpen = true; } }).catch(err => {}); }

async LoadVendorDetails(id,title,lat,lng,npic){ if(id && title && lat && lng){ this.choosevendor = ""; this.choosevendorid = "";

    let pic = npic;
    if(pic == ''){ pic = '../assets/user.svg'; }

    if(this.mylat && this.mylng){
        let itemKm = this.api.getDistanceInKmFast(this.mylat,this.mylng,parseFloat(lat),parseFloat(lng));
        this.choosevendor = this.sanitizer.bypassSecurityTrustHtml('<img src="'+pic+'" style="width:35px;height:35px;margin:0 5px 0 0;border-radius:10px;float:left;">'+title+', Nearest: '+itemKm.toFixed(2)+' km');
    }else{
        this.choosevendor = this.sanitizer.bypassSecurityTrustHtml('<img src="'+pic+'" style="width:35px;height:35px;margin:0 5px 0 0;border-radius:10px;float:left;">'+title+', Nearest: ? km');
        //this.api.ShowNotification("Please wait, still searching for your location...","light");
    }
    this.choosevendorid = id;
    this.isOpen = true;
}

}

async SubmitSearchForm(form:NgForm) { const loading = await this.loader.create({spinner: "dots",message: "Please wait..."}); await loading.present();

this.mylat = this.apitracker.GlobalLat;
this.mylng = this.apitracker.GlobalLng;

await this.api.searchServices4Map(form).subscribe(res => {
  loading.dismiss();
  if(res.code == "100"){ 
  this.api.setDetail(this.api.LASTSEARCH,res.data);

  this.choosevendor = "";
  this.choosevendorid = "";

  let coordArrays = [];
  if(this.mylat != '' && this.mylng != ''){
    // coordArrays = [{title: "You", position: {lat:this.mylat,lng:this.mylng},icon: 'red',animation:GoogleMapsAnimation.BOUNCE,itemid:0}];
  }
  this.retMarkersData = res.data;
    if(this.retMarkersData.length && this.retMarkersData){
        this.retMarkersData.forEach((dat)=>{
            if(!this.choosevendor){
                this.LoadVendorDetails(dat.id,dat.title,dat.lat,dat.lng,dat.pic);
                this.api.setDetail("Nearest",dat);                  
            }
            coordArrays.push({title: dat.title, position: {lat:parseFloat(dat.lat),lng:parseFloat(dat.lng)},icon: 'blue',animation:GoogleMapsAnimation.BOUNCE,itemid:dat.id,itempic:dat.pic});
        });
    }
  this.reloadMarkersOnMap(coordArrays);

  }else{ this.isOpen = false; this.api.ShowToast(res.response,"danger","middle"); }

},(err) => {
    this.isOpen = false;
    loading.dismiss();
});

}

loadSavedCategories(){ this.api.getDetail(this.api.CATEGORIES).then((r)=>{ this.catalogs = r; if(this.catalogs.length){ this.SortCatalog(this.catalogs); } }).catch(err => {}); }

SortCatalog(thecatalogs){ this.groupArr = []; var mgroups = new Set(this.catalogs.map(item => item.cat)); mgroups.forEach(g => this.groupArr.push({ name: g, values: this.catalogs.filter(i => i.cat === g)})); }

async LoadCatalog(){ const loading = await this.loader.create({spinner: "dots",message: "Please wait..."}); await loading.present();
await this.api.getCatalogs().subscribe((res)=>{ if(res.code == 100){ this.catalogs = {}; this.catalogs = res[0].data; this.SortCatalog(this.catalogs);
}else{ this.loadSavedCategories(); } loading.dismiss(); },(err)=>{ console.log("Cant load categories, trying categories after error."); this.loadSavedCategories(); loading.dismiss(); }); }

async CheckAllPermissions(){ await this.platform.ready().then(()=>{ if(this.mylat == ''){ this.api.ShowToast("Loading Coordinates","light","bottom"); } if(!this.isRunning){ this.loadMyLatLng(); } if(this.globalUAT == 'u'){ console.log('initMyMap: '+this.initMyMap); if(this.mylat && this.mylng && this.initMyMap != '1'){ console.log('loadingMyMap..'); if(!this.isMapping){ this.isMapping = true; this.loadMyMap(); } } }else{ if(!this.isVOLastLoading){ this.GetRecentCustomersOrders(); } } }).catch(e => console.error("Timer Permission error...")); }

async CheckAllPermissions2(){ await this.platform.ready().then(()=>{ this.diagnostic.getLocationMode().then((authz) => { if(authz){ this.diagnostic.getLocationMode().then((state) => { if (state == this.diagnostic.locationMode.LOCATION_OFF){ this.api.ShowNotification("Switch on your gps.","danger"); }else{ if(this.mylat == ''){ this.api.ShowToast("Loading Coordinates","light","bottom"); } if(!this.isRunning){ this.loadMyLatLng(); } if(this.globalUAT == 'u'){ if(this.mylat && this.mylng && this.initMyMap != '1'){ if(!this.isMapping){ this.isMapping = true; this.loadMyMap(); } } }else{ if(!this.isVOLastLoading){ this.GetRecentCustomersOrders(); } } } }).catch(e => console.error("Permission error...")); }else{ this.api.ShowNotification("Go to phone settings and authorize this app to use gps.","danger"); } }).catch(e => console.error("Permission error..."));
}).catch(err => {}); }

async loadMyLatLng(){ if(this.mylat != this.apitracker.GlobalLat){ this.mylat = this.apitracker.GlobalLat; this.mylng = this.apitracker.GlobalLng; this.api.GlobalLat = this.mylat; this.api.GlobalLng = this.mylng;

    if(this.globalUAT == 'u'){
        //this.getGeoencoder(this.mylat,this.mylng);
    }

    this.api.setDetail('latlng','{"lat":"'+this.mylat+'","lng":"'+this.mylng+'"}');
    await this.UpdateMyCoords();
}else{
    this.mylat = this.apitracker.GlobalLat;
    this.mylng = this.apitracker.GlobalLng;
    this.api.GlobalLat = this.mylat;
    this.api.GlobalLng = this.mylng;

    if(this.mylat == ''){
        this.api.getDetail('latlng').then((r)=>{
            if(r){
                this.mylat = r.lat;
                this.mylng = r.lng;
                this.apitracker.GlobalLat = r.lat;
                this.apitracker.GlobalLng = r.lng;
                this.api.GlobalLat = r.lat;
                this.api.GlobalLng = r.lng;
            }
            this.isRunning = false;
        }).catch((e)=>{ this.isRunning = false; });
    }else{
        this.isRunning = false;
    }

}

}

StartStopWatchMe(){ //this.getGeoencoder(this.mylat,this.mylng); this.api.ShowAlert(this.myaddress+" Latitude: "+this.mylat+", Longitude: "+this.mylng,"My Location"); }

async loadMyMap(){ if(this.mylat){ this.initMyMap = '1';

    this.choosevendor = "";
    this.choosevendorid = "";

    let coordArrays = [];
    coordArrays = [{title: "You", position: {lat:this.mylat,lng:this.mylng},icon: 'red',animation: GoogleMapsAnimation.BOUNCE,itemid:0}];

    await this.api.getDetail(this.api.LASTSEARCH).then((r)=>{
        if(r){
        this.retMarkersData = r;
        if(this.retMarkersData.length && this.retMarkersData){
            this.retMarkersData.forEach((dat)=>{
                if(!this.choosevendor){
                this.LoadVendorDetails(dat.id,dat.title,dat.lat,dat.lng,dat.pic);
                }
                coordArrays.push({title: dat.title, position: {lat:parseFloat(dat.lat),lng:parseFloat(dat.lng)},icon: 'blue',animation: GoogleMapsAnimation.BOUNCE, itemid:dat.id,itempic:dat.pic});
            });
        }
        }
        this.loadMarkersOnMap(coordArrays);
    }).catch((error) => {
      console.log('Error loading my map: '+error);
      this.loadMarkersOnMap(coordArrays);
    });     
}

}

getGeoencoder2(latitude,longitude){ this.myaddress = "Lagos State, Nigeria."; }

getGeoencoder(latitude,longitude){ / this.nativeGeocoder.reverseGeocode(latitude, longitude, this.geoencoderOptions).then((result: NativeGeocoderReverseResult[]) => { this.myaddress = this.generateAddress(result[0]);
}).catch((error) => { console.log('Error getting address'); });
/ } generateAddress(addressObj){ let address = ""; address = addressObj.thoroughfare + ", " + addressObj.subLocality + ", " + addressObj.locality + ", " + addressObj.countryName; return address; }

loadMarkersOnMap(theArrays:any) { let POINTS: BaseArrayClass = new BaseArrayClass(theArrays); let bounds: ILatLng[] = POINTS.map((data: any, idx: number) => { return data.position; });

if(this.map != undefined){ this.ClearMarkers(); }   

if(this.map == undefined){
    //this.map = GoogleMaps.create('map_canvas', { camera: {target: {lat:this.mylat,lng:this.mylng}, zoom: 15, tilt: 30},preferences:{zoom:{minZoom:0,maxZoom:20}} });
    // resolve();
}
if(this.map != undefined){
    this.map.moveCamera({target: bounds,padding:25});
    POINTS.forEach((data: any) => {
      data.disableAutoPan = true;
      data.draggable = false;
      let marker: Marker = this.map.addMarkerSync(data);          
      marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(()=>{ 
            this.LoadVendorDetails(marker.get("itemid"),marker.get("title"),data.position.lat,data.position.lng,marker.get("itempic"));
      });
      this.markers.push(marker);
    });
}
this.isMapping = false;

}

reloadMarkersOnMap(theArrays:any) { let POINTS: BaseArrayClass = new BaseArrayClass(theArrays); let bounds: ILatLng[] = POINTS.map((data: any, idx: number) => { return data.position; });

if(this.map != undefined){ this.ClearMarkers(); }

if(this.map == undefined){
    //this.map = GoogleMaps.create('map_canvas', { camera: {target: {lat:this.mylat,lng:this.mylng}, zoom: 15, tilt: 30},preferences:{zoom:{minZoom:0,maxZoom:20}} });
}

if(this.map != undefined){
    this.map.moveCamera({target: bounds,padding:25});
    POINTS.forEach((data: any) => {
      data.disableAutoPan = true;
      data.draggable = false;
      let marker: Marker = this.map.addMarkerSync(data);
      marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(()=>{ 
            this.LoadVendorDetails(marker.get("itemid"),marker.get("title"),data.position.lat,data.position.lng,marker.get("itempic"));
      });
      this.markers.push(marker);
    });
}

}

ClearMarkers(){ if(this.markers.length > 0){ this.map.clear(); this.map.off(); this.markers = []; } }

async makecall(phonenum){ if(phonenum != ""){ await this.callno.callNumber(phonenum, true).then(res => console.log('Launched dialer!', res)).catch(err => console.log('Error launching dialer', err)); } } ////////////// } `

see the home.page.html below

`

Beauty Colony {{authService?.globaluwallet | number: '.2' || '0.00'}}

{{noofrequest || '0'}}
Requests
{{mynetincome || '0.00'}}
Net Income
{{mypaid || '0.00'}}
Available Income
{{myunpaid || '0.00'}}
Pending Income
Customer's RequestSee All
No request from customer yet. Always keep the application on.

{{urequest?.title}}

Status: Rendered Declined Pending

Paid: {{urequest?.total | number: '.2'}}

<ng-container *ngIf="globalUAT == 'u'"> <div [@visibilityChanged]="isOpen ? 'shown' : 'hidden'" class="markerInfoContainer"> <div [innerHTML]="choosevendor" class="choosercontainer">

<ion-button color="medium" (click)="isOpen = false;">Cancel <ion-button color="primary" (click)="gotoOrderPage()">Order
`

Please note that above home.page.html contain both html code for vendor and user (i.e. this.globalUAT = 'v' and this.globalUAT = 'u' respectively). The real html part for (user) the map is this below;

`<ng-container *ngIf="globalUAT == 'u'">

`

wf9a5m75 commented 5 years ago

Please create a git repository on Github, and share it.

gfavour commented 5 years ago

Thanks wf9a5m75 for your time, for quick help i discover that if I navigate to another with this.router.navigate(['/order', this.choosevendorid]); and go back to home page with <ion-back-button defaultHref="/"></ion-back-button> back button, map doesn't hang. It works fine.

But if I navigate to another page from side menu through routerLink; example:

<ion-item [routerDirection]="'root'" [routerLink]="['/vwallet']"><ion-icon slot="start" name="wallet"></ion-icon><ion-label>e-Wallet</ion-label></ion-item>

and from this page "e-wallet" for example back to home page by clicking Home link on sidemenu;

<ion-item [routerDirection]="'root'" [routerLink]="['/home']"><ion-icon slot="start" name="ios-home"></ion-icon><ion-label>Home</ion-label></ion-item>

IT HANGS.

Can the problem be navigation method or [routerDirection]="'root'" I use in the sidemenu links

I will love to share the code but its private...and its contains many files

wf9a5m75 commented 5 years ago

I have no time to create a project from scratch. I'm really busy. Sharing your project files on git repository, it reduces my private time a lot, since I just do git clone then build your project. Creating a simple project based on your comments, I have to spend tons of time. Time is money. I can't spend my time for your debugging.

Please share your project files on git repo, otherwise please debug by yourself.