I am trying to display Google Maps in my Ionic app & center on my current location.
When I run this on my laptop, it displays as expected.
But when I try to run it on my mobile device, the map isn’t rendering.
Here is the code:
ngAfterViewInit() {
this.locateUser();
console.log('My Coords', this.coordinates);
this.getGoogleMaps().then(googleMaps => {
const mapEl = this.mapElementRef.nativeElement;
const map = new googleMaps.Map(mapEl, {
center: this.coordinates,
zoom: 16
});
googleMaps.event.addListenerOnce(map, 'idle', () => {
this.renderer.addClass(mapEl, 'visible');
});
}).catch(err => {
console.log('Google Maps error:', err);
});
}
private getGoogleMaps() {
const win = window as any;
const googleModule = win.google;
if (googleModule && googleModule.maps) {
return Promise.resolve(googleModule.maps);
}
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?key=myAPIKey';
script.async = true;
script.defer = true;
document.body.appendChild(script);
script.onload = () => {
const loadedGoogleModule = win.google;
if (loadedGoogleModule && loadedGoogleModule.maps) {
resolve(loadedGoogleModule.maps);
} else {
reject('Google Maps SDK not available.');
}
};
});
}
private locateUser() {
if (!Capacitor.isPluginAvailable('Geolocation')) {
this.showErrorAlert();
return;
}
Plugins.Geolocation.getCurrentPosition()
.then(geoPosition => {
this.coordinates = {
lat: geoPosition.coords.latitude,
lng: geoPosition.coords.longitude
};
console.log(this.coordinates);
})
.catch(err => {
this.showErrorAlert();
});
}
Can someone please tell me why this is working on my laptop, but not on my mobile?
Also, here are the steps I’m taking to run on the mobile:
ionic build
ionic capacitor run android
- Then I run the app in Android Studio.