Google Maps inconsistently displaying in Ionic app on Android device

I am adding Google Maps Javascript to my ionic app below.

The map is displaying as expected when I run ionic serve ,

However, when I try to run on my android device using below commands, the map is displaying sometimes , but not always.

  1. ionic build
  2. npx cap sync
  3. npx cap open android

Can someone please tell me why this is occurring, & how it can be resolved?

Here is my code below, I’ll also show the console output in Android studio when I try to run the app:

<ion-header [translucent]="true">
  <ion-toolbar color="primary">
    <ion-title>
      Google Maps
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <div #map id="map" [hidden]="!user"></div>
</ion-content>

Typescript:

  user = null;
  @ViewChild('map', { static: false }) mapElement: ElementRef;
  map: any;
  markers = [];
  watch = null;
  latLng = null;

  constructor(private afAuth: AngularFireAuth, private afs: AngularFirestore) { }

  ionViewWillEnter() {
    this.anonLogin();
    this.loadMap();
  }

  anonLogin() {
    this.afAuth.auth.signInAnonymously().then(res => {
      this.user = res.user;
      this.watch = Geolocation.watchPosition({}, (position, err) => {
        if (position) {
          this.deleteMarkers();
          var newLocation = { lat: position.coords.latitude, lng: position.coords.longitude };
          this.addMarker(newLocation);
        }
      });
    });
  }

  addMarker(location) {
    var marker = new google.maps.Marker({
      position: location,
      map: this.map,
      animation: google.maps.Animation.BOUNCE,
    });
    this.markers.push(marker);
  }

  deleteMarkers() {
    this.clearMarkers();
    this.markers = [];
  }

  clearMarkers() {
    this.setMapOnAll(null);
  }

  setMapOnAll(map) {
    for (var i = 0; i < this.markers.length; i++) {
      this.markers[i].setMap(map);
    }
  }

  loadMap() {

    var locationOnLoad = null;

    Geolocation.getCurrentPosition().then((resp) => {
      this.latLng = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
      locationOnLoad = { lat: resp.coords.latitude, lng: resp.coords.longitude };
    }).then(() => {

      this.map = new google.maps.Map(this.mapElement.nativeElement, {
        center: locationOnLoad,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });

      this.addMarker(locationOnLoad);

    }).catch((err) => {
      console.log(err);
    });
  }

And here is the console output when I try to run in Android Studio:

03/26 14:53:18: Launching ‘app’ on samsung SM-G965F. $ adb shell am start -n “io.ionic.starter/io.ionic.starter.MainActivity” -a android.intent.action.MAIN -c android.intent.category.LAUNCHER Connected to process 29347 on device ‘samsung-sm_g965f-2410169c6d0c7ece’. Capturing and displaying logcat messages from application. This behavior can be disabled in the “Logcat output” section of the “Debugger” settings page. E/Zygote: isWhitelistProcess - Process is Whitelisted E/Zygote: accessInfo : 1 I/SELinux: SELinux: seapp_context_lookup: seinfo=untrusted, level=s0:c139,c258,c512,c768, pkgname=io.ionic.starter I/o.ionic.starte: Late-enabling -Xcheck:jni D/ConnectivityManager_URSP: Ursp sIsUrsp=false, sIsCheckUrsp=false, uid=10651 D/Proxy: urspP is null: 10651 W/FirebaseApp: Default FirebaseApp failed to initialize because no default options were found. This usually means that com.google.gms:google-services was not applied to your gradle project. I/FirebaseInitProvider: FirebaseApp initialization unsuccessful D/libEGL: loaded /vendor/lib64/egl/libGLES_mali.so W/o.ionic.starte: Accessing hidden method Landroid/graphics/drawable/Drawable;->getOpticalInsets()Landroid/graphics/Insets; (light greylist, linking) Accessing hidden field Landroid/graphics/Insets;->left:I (light greylist, linking) Accessing hidden field Landroid/graphics/Insets;->right:I (light greylist, linking) Accessing hidden field Landroid/graphics/Insets;->top:I (light greylist, linking) Accessing hidden field Landroid/graphics/Insets;->bottom:I (light greylist, linking) E/o.ionic.starte: Invalid ID 0x00000000. W/o.ionic.starte: Accessing hidden method Landroid/view/View;->getAccessibilityDelegate()Landroid/view/View$AccessibilityDelegate; (light greylist, linking) W/o.ionic.starte: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection) W/o.ionic.starte: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection) I/WebViewFactory: Loading com.android.chrome version 80.0.3987.149 (code 398714932) E/o.ionic.starte: Invalid ID 0x00000000. E/o.ionic.starte: Invalid ID 0x00000000. I/cr_LibraryLoader: Loaded native library version number “80.0.3987.149” W/o.ionic.starte: Accessing hidden method Landroid/content/Context;->bindServiceAsUser(Landroid/content/Intent;Landroid/content/ServiceConnection;ILandroid/os/Handler;Landroid/os/UserHandle;)Z (light greylist, reflection) D/ConnectivityManager: requestNetwork; CallingUid : 10651, CallingPid : 29347 D/ConnectivityManager: requestNetwork; CallingUid : 10651, CallingPid : 29347 D/Capacitor: Starting BridgeActivity D/Capacitor: Registering plugin: App D/Capacitor: Registering plugin: Accessibility D/Capacitor: Registering plugin: BackgroundTask D/Capacitor: Registering plugin: Browser D/Capacitor: Registering plugin: Camera D/Capacitor: Registering plugin: Clipboard D/Capacitor: Registering plugin: Device D/Capacitor: Registering plugin: LocalNotifications D/Capacitor: Registering plugin: Filesystem D/Capacitor: Registering plugin: Geolocation D/Capacitor: Registering plugin: Haptics D/Capacitor: Registering plugin: Keyboard D/Capacitor: Registering plugin: Modals D/Capacitor: Registering plugin: Network D/Capacitor: Registering plugin: Permissions D/Capacitor: Registering plugin: Photos D/Capacitor: Registering plugin: PushNotifications D/Capacitor: Registering plugin: Share D/Capacitor: Registering plugin: SplashScreen D/Capacitor: Registering plugin: StatusBar D/Capacitor: Registering plugin: Storage D/Capacitor: Registering plugin: Toast D/Capacitor: Registering plugin: WebView E/Capacitor: Unable to read file at path public/plugins D/Capacitor: Loading app at http://localhost W/o.ionic.starte: Accessing hidden method Landroid/media/AudioManager;->getOutputLatency(I)I (light greylist, reflection) W/cr_media: Requires BLUETOOTH permission I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0 android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0 W/AudioCapabilities: Unsupported mime audio/ac4 W/AudioCapabilities: Unsupported mime audio/x-ima W/AudioCapabilities: Unsupported mime audio/x-ape W/AudioCapabilities: Unsupported mime audio/eac3-joc W/AudioCapabilities: Unsupported mime audio/mpeg-L1 Unsupported mime audio/mpeg-L2 W/AudioCapabilities: Unsupported mime audio/x-ms-wma D/Capacitor/Plugin/LN: LocalNotification received: null Activity started without notification attached D/Capacitor: App started D/Capacitor/Plugin/App: Firing change: true W/VideoCapabilities: Unrecognized profile 4 for video/hevc V/Capacitor/Plugin/App: Notifying listeners for event appStateChange D/Capacitor/Plugin/App: No listeners found for event appStateChange W/VideoCapabilities: Unsupported mime video/mp43 W/VideoCapabilities: Unrecognized profile/level 1/32 for video/mp4v-es Unrecognized profile/level 32768/2 for video/mp4v-es Unrecognized profile/level 32768/64 for video/mp4v-es D/Capacitor: App resumed W/VideoCapabilities: Unsupported mime video/wvc1 D/OpenGLRenderer: Skia GL Pipeline W/VideoCapabilities: Unsupported mime video/wvc1 D/EmergencyMode: [EmergencyManager] android createPackageContext successful D/InputTransport: Input channel constructed: fd=133 D/ViewRootImpl@edef802[MainActivity]: setView = DecorView@80c6513[MainActivity] TM=true MM=false W/VideoCapabilities: Unsupported mime video/x-ms-wmv7 W/VideoCapabilities: Unsupported mime video/x-ms-wmv8 D/ConnectivityManager: requestNetwork; CallingUid : 10651, CallingPid : 29347 D/ConnectivityManager: requestNetwork; CallingUid : 10651, CallingPid : 29347 D/Capacitor: Handling local request: http://localhost/ I/VideoCapabilities: Unsupported profile 4 for video/mp4v-es D/ViewRootImpl@edef802[MainActivity]: dispatchAttachedToWindow D/ViewRootImpl@edef802[MainActivity]: Relayout returned: old=[0,0][1080,2220] new=[0,0][1080,2220] result=0x7 surface={valid=true 493862674432} changed=true I/OpenGLRenderer: Initialized EGL, version 1.4 D/OpenGLRenderer: Swap behavior 2 D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000 D/OpenGLRenderer: eglCreateWindowSurface = 0x72f5333200, 0x72fc826010 D/InputTransport: Input channel constructed: fd=146 D/ViewRootImpl@528b903[MainActivity]: setView = android.widget.ImageView{607e080 V.ED… …ID 0,0-0,0} TM=true MM=false D/InputTransport: Input channel constructed: fd=147 D/ViewRootImpl@84a84ac[MainActivity]: setView = android.widget.ProgressBar{52f1575 I.ED… …ID 0,0-0,0} TM=true MM=false V/Capacitor/Plugin/Network: Notifying listeners for event networkStatusChange D/Capacitor/Plugin/Network: No listeners found for event networkStatusChange D/ViewRootImpl@edef802[MainActivity]: MSG_RESIZED: frame=Rect(0, 0 - 1080, 2220) ci=Rect(0, 63 - 0, 39) vi=Rect(0, 63 - 0, 39) or=1 MSG_WINDOW_FOCUS_CHANGED 1 1 D/InputMethodManager: prepareNavigationBarInfo() DecorView@80c6513[MainActivity] getNavigationBarColor() -855310 D/InputMethodManager: prepareNavigationBarInfo() DecorView@80c6513[MainActivity] getNavigationBarColor() -855310 V/InputMethodManager: Starting input: tba=io.ionic.starter ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false D/InputMethodManager: startInputInner - Id : 0 I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus D/InputTransport: Input channel constructed: fd=148 D/ViewRootImpl@528b903[MainActivity]: dispatchAttachedToWindow D/ViewRootImpl@528b903[MainActivity]: Relayout returned: old=[0,0][1080,2220] new=[0,0][1080,2220] result=0x7 surface={valid=true 493740634112} changed=true D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000 D/OpenGLRenderer: eglCreateWindowSurface = 0x72f541f280, 0x72f53c3010 D/ViewRootImpl@84a84ac[MainActivity]: dispatchAttachedToWindow D/ViewRootImpl@84a84ac[MainActivity]: Relayout returned: old=[0,0][1080,2220] new=[477,1047][603,1173] result=0x1 surface={valid=false 0} changed=false D/ViewRootImpl@528b903[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 1 1 D/InputMethodManager: prepareNavigationBarInfo() android.widget.ImageView{607e080 V.ED… …ID 0,0-1080,2220} getNavigationBarColor this view is not DecorView or null getNavigationBarColor() Fail D/InputMethodManager: prepareNavigationBarInfo() android.widget.ImageView{607e080 V.ED… …ID 0,0-1080,2220} getNavigationBarColor this view is not DecorView or null getNavigationBarColor() Fail V/InputMethodManager: Starting input: tba=io.ionic.starter ic=null mNaviBarColor Fail mIsGetNaviBarColorSuccess false , NavVisible : true , NavTrans : false D/InputMethodManager: startInputInner - Id : 0 I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus D/InputTransport: Input channel constructed: fd=152 W/InputMethodManager: Ignoring onBind: cur seq=43450, given seq=43449 D/InputTransport: Input channel destroyed: fd=148 D/ViewRootImpl@528b903[MainActivity]: MSG_RESIZED: frame=Rect(0, 0 - 1080, 2220) ci=Rect(0, 63 - 0, 39) vi=Rect(0, 63 - 0, 39) or=1 D/ViewRootImpl@edef802[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 0 1 D/InputMethodManager: prepareNavigationBarInfo() DecorView@80c6513[MainActivity] getNavigationBarColor() -855310 D/Capacitor: Handling local request: http://localhost/polyfills-es2015.js D/Capacitor: Handling local request: http://localhost/runtime-es2015.js D/Capacitor: Handling local request: http://localhost/vendor-es2015.js D/Capacitor: Handling local request: http://localhost/main-es2015.js D/Capacitor: Handling local request: http://localhost/styles-es2015.js I/Capacitor/Console: File: http://localhost/vendor-es2015.js - Line 69837 - Msg: Angular is running in the development mode. Call enableProdMode() to enable the production mode. D/Capacitor: Handling local request: http://localhost/5-es2015.js D/Capacitor: Handling local request: http://localhost/common-es2015.js D/Capacitor: Handling local request: http://localhost/home-home-module-es2015.js I/Capacitor/Console: File: http://localhost/vendor-es2015.js - Line 117994 - Msg: Ionic Native: deviceready event fired after 506 ms W/Capacitor/Console: File: http://localhost/vendor-es2015.js - Line 118299 - Msg: Native: tried calling StatusBar.styleDefault, but the StatusBar plugin is not installed. File: http://localhost/vendor-es2015.js - Line 118311 - Msg: Install the StatusBar plugin: ‘ionic cordova plugin add cordova-plugin-statusbar’ W/Capacitor/Console: File: http://localhost/vendor-es2015.js - Line 118299 - Msg: Native: tried calling SplashScreen.hide, but the SplashScreen plugin is not installed. File: http://localhost/vendor-es2015.js - Line 118311 - Msg: Install the SplashScreen plugin: ‘ionic cordova plugin add cordova-plugin-splashscreen’ D/Capacitor: Handling local request: http://localhost/swipe-back-d2cdbf9a-js-es2015.js V/Capacitor/Plugin: To native (Capacitor plugin): callbackId: 125075709, pluginId: Geolocation, methodName: getCurrentPosition V/Capacitor: callback: 125075709, pluginId: Geolocation, methodName: getCurrentPosition, methodData: {} D/Capacitor: Handling local request: http://localhost/tap-click-606f325e-js-es2015.js V/Capacitor/Plugin: To native (Capacitor plugin): callbackId: 125075710, pluginId: App, methodName: addListener V/Capacitor: callback: 125075710, pluginId: App, methodName: addListener, methodData: {“eventName”:“backButton”} D/Capacitor: Handling local request: http://localhost/focus-visible-70713a0c-js-es2015.js D/Capacitor: Handling local request: http://localhost/status-tap-2ec46489-js-es2015.js D/Capacitor: Handling local request: http://localhost/assets/icon/favicon.png D/TcpOptimizer: TcpOptimizer-ON D/NetworkSecurityConfig: No Network Security Config specified, using platform default V/Capacitor/Plugin: To native (Capacitor plugin): callbackId: 125075711, pluginId: Geolocation, methodName: watchPosition V/Capacitor: callback: 125075711, pluginId: Geolocation, methodName: watchPosition, methodData: {} I/Capacitor/Console: File: http://localhost/home-home-module-es2015.js - Line 2796 - Msg: new position: 51.9294869-8.5130874 D/Capacitor: Handling local request: http://localhost/33-es2015.js D/Capacitor: SplashScreen was automatically hidden after the launch timeout. You should call SplashScreen.hide() as soon as your web app is loaded (or increase the timeout).Read more at Splash Screen Capacitor Plugin API | Capacitor Documentation W/libEGL: EGLNativeWindowType 0x72f53c3010 disconnect failed D/OpenGLRenderer: eglDestroySurface = 0x72f541f280, 0x72f53c3000 D/ViewRootImpl@528b903[MainActivity]: Relayout returned: old=[0,0][1080,2220] new=[0,0][1080,2220] result=0x5 surface={valid=false 0} changed=true D/ViewRootImpl@528b903[MainActivity]: dispatchDetachedFromWindow Surface release. android.view.ViewRootImpl.doDie:7954 android.view.ViewRootImpl$ViewRootHandler.handleMessage:4955 android.os.Handler.dispatchMessage:106 android.os.Looper.loop:214 android.app.ActivityThread.main:6986 java.lang.reflect.Method.invoke:-2 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run:494 com.android.internal.os.ZygoteInit.main:1445 D/InputTransport: Input channel destroyed: fd=146 E/ViewRootImpl: sendUserActionEvent() returned. D/ViewRootImpl@edef802[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 1 1 D/InputMethodManager: prepareNavigationBarInfo() DecorView@80c6513[MainActivity] getNavigationBarColor() -855310 D/InputMethodManager: prepareNavigationBarInfo() DecorView@80c6513[MainActivity] getNavigationBarColor() -855310 V/InputMethodManager: Starting input: tba=io.ionic.starter ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false D/InputMethodManager: startInputInner - Id : 0 I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus D/InputTransport: Input channel constructed: fd=149 D/InputTransport: Input channel destroyed: fd=152 E/Capacitor/Console: File: https://maps.googleapis.com/maps/api/js?key=AIzaSyDfdy3Tu2pS2QX8m8f_iPPKfX4vgQHBel8 - Line 55 - Msg: You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at Erste Schritte mit der Google Maps Platform  |  Google for Developers D/ViewRootImpl@edef802[MainActivity]: ViewPostIme pointer 0 D/ViewRootImpl@edef802[MainActivity]: ViewPostIme pointer 1 D/InputMethodManager: prepareNavigationBarInfo() DecorView@80c6513[MainActivity] getNavigationBarColor() -855310 V/InputMethodManager: Starting input: tba=io.ionic.starter ic=null mNaviBarColor -855310 mIsGetNaviBarColorSuccess true , NavVisible : true , NavTrans : false D/InputMethodManager: startInputInner - Id : 0 I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus D/InputTransport: Input channel constructed: fd=197 D/InputTransport: Input channel destroyed: fd=149 D/InputMethodManager: HSIFW - flag : 0 Pid : 29347 I/o.ionic.starte: Compiler allocated 4MB to compile void android.view.ViewRootImpl.performTraversals() I/Capacitor/Console: File: http://localhost/home-home-module-es2015.js - Line 2796 - Msg: new position: 51.9294876-8.5130852

In general the JavaScript Map is not a good Choice for native Apps. It behaves inconsistent and bad, is not offline able, etc. so you should use a Plugin. The official Cordova Plugin is sadly not Capacitor ready on iOS. The Creator knows this and has it in mind but he is very busy. i know this is not the answer you would like to hear :confused:

1 Like

Thanks for this, at least it clears up the issue, I was driving myself crazy wondering what I was doing wrong! :slight_smile:

Is there a particular plugin you would suggest using?

Below is a list of the functionality I require:

  1. Use Geolocation to get my current location

  2. Create a map & center it on my current location

  3. Drop a marker on my current location

  4. Add a new marker when my location updates so that it appears that the marker is moving with me

  5. Read multiple locations in from firebase, & display markers on each

  6. Create a modal to display info on each marker when marker is clicked.

  7. Inside this modal, have a button that navigates to a different page, & take some data regarding that modal to this new page

  8. Display route from one marker to another, & give “sat-nav” like directions as you can on Google Maps.