Can't show googlemaps cordova twice


#1

Hi everyone,

I’ve got my homePage where I display a native googlemaps with some markers properly, and as soon as tap any marker It takes you to other page with other map which is not working at all.

To go from homePage to the otherPage I use this.navCtrl.push(…), but the maps doesn’t display, it seems that is gonna do it but finnaly the page gets blank.

I tried using setRoot instead of navCtrl and it works, but of course I can’t go back so it is not a solution here.

This is how I do it to show maps and markers, and it is more or less the same in both pages:

importrs....

@Component({
  selector: 'page-mapa-general',
  templateUrl: 'mapa-general.html',
  providers: [ LocalidadesService ]
})
export class MapaGeneralPage {

    localidades:any;
    pits:any;
    toast:any;

    map: GoogleMap;
    latLng: any;

    @ViewChild('map') mapElement: ElementRef;
    @ViewChild('pleaseConnect') pleaseConnect: ElementRef;
 
    constructor(
        public platform: Platform,
        public navCtrl: NavController,
        public navParams: NavParams,
        public localidadesService:LocalidadesService,
        public toastCtrl: ToastController,
        public queVerLocalidadService:QueVerLocalidadService
    ) {
    }

    ionViewDidEnter():void{
        this.platform.ready().then(() => {
            console.log('entra en mapa general');
            if( this.toast == undefined ){
                 this.toast = this.toastCtrl.create({
                message: 'El mapa tarda unos segundos en cargarse dependiendo de tu conexión.',
                duration: 3000
                });
                this.toast.present();
            }

            if( this.localidades == undefined ){
                this.getCurrentPosition();                  
            }           
                       
        });
    }

    getCurrentPosition(){
         console.log('getCurrentPos Mapa General');
        Geolocation.getCurrentPosition()
        .then(position => {

            let lat = position.coords.latitude;
            let lng = position.coords.longitude;

            this.latLng = new GoogleMapsLatLng(lat, lng);

            this.cargarMarkers();
        });
    }

    cargarMarkers(){
         console.log('Cargar Markers MapaGeneral');
        this.localidades = this.loadLocalidades();
        this.queVerLocalidadService.obtenerPits()
        .then(pits =>{
            this.pits = pits;
            this.loadMap();
        })
        .catch(error=>{
        console.log(error);
        })
    }

    loadMap(){
         console.log('loadMap mapa general');
        let points = new Array();

        this.localidades.forEach((item, index) => {
            points.push( new GoogleMapsLatLng(item.latitud,item.longitud));
        });
        this.pits.forEach((item, index) => {
            points.push( new GoogleMapsLatLng(item.latitud,item.longitud));
        });

        let latLngBounds = new GoogleMapsLatLngBounds(points);
        let centroBounds = new GoogleMapsLatLng(latLngBounds.getCenter().lat,latLngBounds.getCenter().lng);

        let mapDimensions = { 
            height: this.mapElement.nativeElement.offsetHeight,
            width: this.mapElement.nativeElement.offsetWidth
        };
        let zoom = this.getBoundsZoomLevel( latLngBounds, mapDimensions);

        this.map = new GoogleMap('map', {
            'backgroundColor': 'white',
            'controls': {
            'compass': true,
            'myLocationButton': true,
            'indoorPicker': true,
            'zoom': true,
            },
            'gestures': {
                'scroll': true,
                'tilt': true,
                'rotate': true,
                'zoom': true
            },
            'camera': {
                'latLng': centroBounds,
                'tilt': 30,
                'zoom': zoom,
                'bearing': 50
            }
        });
       
        this.map.one(GoogleMapsEvent.MAP_READY).then(() => {
            console.log('MAP READY , limpio mapa Mapa General');
             this.map.clear();
             this.setMarkers();
           });
    }

    getBoundsZoomLevel(bounds, mapDim) {
        let WORLD_DIM = { height: 256, width: 256 };
        let ZOOM_MAX = 21;

        function latRad(lat) {
            let sin = Math.sin(lat * Math.PI / 180);
            let radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
            return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
        }

        function zoom(mapPx, worldPx, fraction) {
            return Math.floor(Math.log(mapPx / worldPx / fraction) / Math.LN2);
        }

        let ne = bounds.northeast;
        let sw = bounds.southwest;

        let latFraction = (latRad(ne.lat) - latRad(sw.lat)) / Math.PI;

        let lngDiff = ne.lng - sw.lng;
        let lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;

        let latZoom = zoom(mapDim.height, WORLD_DIM.height, latFraction);
        let lngZoom = zoom(mapDim.width, WORLD_DIM.width, lngFraction);

        return Math.min(latZoom, lngZoom, ZOOM_MAX);
    } 

    ionViewDidLeave():void{
        console.log('salgo borro markers general');
        this.map.clear();
       /* this.map.setVisible(false);
        this.map.setDiv(null);   
        this.map.remove(); */
        
        console.log('mapa general eliminado.');     
    }

    setMarkers(){
        console.log('añado marcadores mapa general');
        this.localidades.forEach((item, index) => {
            
            let a = new GoogleMapsLatLng(item.latitud, item.longitud);
            let am: GoogleMapsMarkerOptions = {
                position: a,
                icon:"www/assets/images/markers/map-marker-localidad.png"
            };

            this.map.addMarker(am)
            .then((marker: GoogleMapsMarker) => {
                marker.addEventListener(GoogleMapsEvent.MARKER_CLICK)
                .subscribe(e => {
                    this.openPageLocalidad(item);
                });
            });

        });

        this.pits.forEach((item, index) => {
            let a = new GoogleMapsLatLng(item.latitud, item.longitud);
            let am: GoogleMapsMarkerOptions = {
                position: a,
                icon:"www/assets/images/markers/map-marker-pit.png",
            };
            this.map.addMarker(am)
            .then((marker: GoogleMapsMarker) => {
                marker.addEventListener(GoogleMapsEvent.MARKER_CLICK)
            .subscribe(e => {
               this.openPageContenido(item);
            });

            });

        });
    }

    loadLocalidades():any{
      return this.localidadesService.loadLocalidades();
    }

    openPageLocalidad(localidad:any){
        this.navCtrl.push( LocalidadGeneralPage, {"localidad": localidad });
    }

    openPageContenido(pit:any){
        let cl= new ContenidoList(pit.id,pit.nombre,"");
        this.navCtrl.push( ContenidoPage, {"contenidoList": cl});
    }
    
}

Any idea? I tried to remove the map, to remove the map element, and even use different names for the instances but nothing works, the second map doesn’t work after show the first :confused:

thank you so much.


#2

Not sure if it’s yours, but I remember I had that kind of problem too, where a map was displayed on a page and not on another one when I was using the same components.

Finally I found out that my problem was linked with using the same ID. After having set a different ID for my map on each pages it worked out…if that could help


#3

Let me try…


#4

@reedrichards if I change the id of de div element from id=“map” to id=“whateverMap” it doesnt work, I can only change the nativeElement ref for the viewchild.

Something else?


#5

Sh*t sorry :frowning:

Mmmmmh ts and html looks good? Does the scss too? I guess you have to set an height for the map div, do the scss apply on both maps?


#6

@reedrichards OMG I can’t believe that I forgot to change the css id reference, now it shows the map properly.
Thank you so much :wink:


#7

Coolio!

The css thing with the map happened to me a couple of time too :wink: