arjun_web
arjun_web

Reputation: 131

why google map crashes after map canavs is loaded

i'm getting the below error on android device and my app crashes.

enter image description here

here is my complete code:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Geolocation ,GeolocationOptions } from '@ionic-native/geolocation';


import {
 GoogleMaps,
 GoogleMap,
 GoogleMapsEvent,
 LatLng,
 CameraPosition,
 MarkerOptions,
 Marker
} from '@ionic-native/google-maps';      


@IonicPage()
@Component({
  selector: 'page-google-map-test',
  templateUrl: 'google-map-test.html',
})

export class GoogleMapTestPage {

  constructor(...,public googleMaps: GoogleMaps,private geolocation : Geolocation) {
  }

 ionViewDidLoad() {
    this.mapHandler2();       
  }


  mapHandler2(){

    // create a new map by passing HTMLElement
     let element: HTMLElement = document.getElementById('map');

     let map: GoogleMap = this.googleMaps.create(element);

     let LatLang: LatLng = new LatLng(43.0741904,-89.3809802); 


          // create CameraPosition 
       let position: any = {
          target: LatLang,    
          zoom: 18,
          tilt: 30
       };     


        map.one(GoogleMapsEvent.MAP_READY).then(() => {
         console.log('Map is ready!');
         // Now you can add elements to the map like the marker
          map.moveCamera(position);

         // create new marker
        let markerOptions:any = {
            position: LatLng,
            title: 'Ionic'
        };

        const marker:any = map.addMarker(markerOptions)
            .then((marker: Marker) => {
                marker.showInfoWindow();
            });


         this.geolocation.getCurrentPosition().then((position) => {

             let LatLang: LatLng = new LatLng(position.coords.latitude,position.coords.longitude);


              map.setCameraTarget(LatLang);
              map.setCameraZoom(18);


                 // create new marker
                  let markerOptions:any = {
                      position: LatLng,
                      title: 'You Are Here'
                  };

                const marker:any = map.addMarker(markerOptions)
                      .then((marker: Marker) => {
                          marker.showInfoWindow();
                  });       


          }, (err) => {
            console.log(err); 
            alert('location error');            
          }); 



        });  // End of GoogleMapsEvent.MAP_READY

  }

}    

Initially the map canvas loads but crashes Showing the above screen.

Please help me to solve this issue, i'm very new to ionic 3.

Upvotes: 0

Views: 685

Answers (1)

Daniel
Daniel

Reputation: 11

I was facing the same issue over here. After trying in several ways of plotting markers I just figured out that application happens to crash when I was adding markers out of the visible area. Then I've changed the configuration of the initial map to a distant zoom setting (in my case I set from zoom=13 to zoom=4) and only after all markers were plot, I set the zoom to approximate to the desired marker. I guess you can also set in the initial configuration the latLng array of all your markers prior to plot them, so the camera will be adjusted to those markers and they all be in the visible area. Here is my final code:

    async loadMap(): Promise<void> {
        try {
            if (this.map && this.mapReady) {
                await this.map.clear();
                await this.plotMarkers();
            } else {
                this.map = GoogleMaps.create('map_canvas', {
                    controls: { compass: true, myLocationButton: false, myLocation: false, zoom: false, mapToolbar: false},
                    camera: { target: {
                        lat: currentLatitude, //I get those using geolocation plugin, but I guess is doable by the maps plugin itself.
                        lng: currentLongitude
                    }, tilt: 15, zoom: 5}
                });
                await this.map.one('map_ready');
                this.mapReady = true;
                await this.plotMarkers();
            }
        } catch (e) {
            console.log(e);
            //display the error message properly
        }
    }
    async plotMarkers(): Promise<void> {
        if (!this.map || !this.mapReady) throw new Error('Map is not ready!');

        const markersOpts: MarkerOptions[] = [];
        const bounds: ILatLng[] = [];
        const itemsToPlot: any[] = [/* your items containing a location to be plot. I assume here there is a attribute named 'location'. */];
        for (const item of itemsToPlot) {
            if (item && item.location) {
                const pos: ILatLng = { lat: item.location.lat, lng: item.location.lon};
                const markerOpts: MarkerOptions = {
                    icon: {
                        url: this.markersPath + '/custom_marker.png', //has to be a PNG. SVG crashes the app.
                        anchor: { x: 40, y: 55}, //adjust the best fi for yor custom image
                        label: {
                            text: item.description, //assuming that there is a description in the item you want to plot
                            color: '#555555', //you can change the color according to any specific attribute of your item
                            fontSize: 12,
                            bold: true
                        }
                    },
                    animation: 'DROP', //set to null to remove animation,
                    position: pos,
                    origin: { x: 0, y: 0},
                    anchor: [40, 55]
                };
                bounds.push(pos);
                markersOpts.push(markerOpts);
            }
        }
        //prepare zoom to fit all markers
        if (bounds.length > 0) {
            this.map.animateCamera({ target: bounds, duration: 400});
        }
        //plot all markers
        markersOpts.forEach(async (opt: MarkerOptions) => {
            const marker: Marker = await this.map.addMarker(opt);
            marker.setZIndex(100000);
            marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(() => {
                //do something when click on a marker
            });
        });
    }

Upvotes: 1

Related Questions