Ionic: How to Use Google Maps & Geolocation (Native & JavaScript)

Ionic Google Maps: An alternate approach

Many developers want to use Ionic Google Maps to add mapping and geolocation to their applications. I’ve been exploring different ways to integrate Google Maps into an Ionic application over the last month. MobeeWash, an Ionic Framework application, uses the map as an integral part of the user experience.

You have two options for integrating Google Maps into your Ionic application. There are versions using the native SDK’s for iOS and Android or the JavaScript version intended for the web. Your choice affects how you will interact with the map and both options have different pros and cons.

One of the key advantages of Ionic is the speed of development while in the browser. Things like live reload for native testing improve performance but does not get you to the same productivity level as staying in the browser.

The native Google Maps experience is smoother than the JavaScript Google Map version while the JavaScript version is easier to test in the browser.

I’ve been exploring a method for using both Native & JavaScript Google Maps in the same application. The correct version is chosen when the device boots. This allows you to test in the browser while developing and deliver the best experience for the current device when the application is deployed.

This approach does come with some overhead which I am still exploring.

With that being completed we have a function that requests the user’s location that fires using the Ionic Framework lifecycle event, ionViewDidLoad().

Using this lifecycle event ensures that we only initiate the request once the view is ready and loaded.

The function findUserLocation() will perform the legwork of fetching and handling the user’s location.

In the body of the findUserLocation() function, we set some initial options. It’s important to set the enableHighAccuracy to true as it may not activate the Geolocation on some devices if not turned on.

We use getCurrentPosition() to retrieve the position which is returned to us via a Promise.

When the promise resolves we are given the users location as properties on the response.coords object.

This we store in the location variable that we set up for this purpose earlier.

You can handle any errors in the catch block. For now, we will only include the console.log().

home.ts

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

ionViewDidLoad(){

this.findUserLocation();

}

findUserLocation(){

let options={

enableHighAccuracy:true,

timeout:25000

};

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

this.location={

latitude:position.coords.latitude,

longitude:position.coords.longitude

};

}).catch((error)=>{

console.log('Error getting location',error);

});

}

Create the different Map providers you will require

We will be creating three different providers to interact with Google Maps. The MapsProvider() will interface with the different implementations of Javascript and Native maps.

The JsMapsProvider() and NativeMapsProvider() will have the concrete implementation of the map functionality.

Run the following in your terminal to create the providers:

Shell

1

2

3

ionicgprovider MapsProvider

ionicgprovider JsMapsProvider

ionicgprovider NativeMapsProvider

Now add the new providers to your app module:

app.module.ts

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

...

import{MapsProvider}from'../providers/maps/maps';

import{JsMapsProvider}from'../providers/js-maps/js-maps';

import{NativeMapsProvider}from'../providers/native-maps/native-maps';

...

providers:[

...

MapsProvider,

JsMapsProvider,

NativeMapsProvider

...

]

Setup your Google Maps API keys

To use the Google Maps API you will need an API key for each environment you want to tackle. In our case, we will be using the Web ie JavaScript and Native which covers iOS and Android.

Then we create a map variable to hold the Google Map and create the init() function that will initialize and display the map.

native-maps.ts

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

@Injectable()

exportclassNativeMapsProvider{

map:any;

constructor(public googleMaps:GoogleMaps){

}

init(location,element){

let latLng=newLatLng(location.latitude,location.longitude);

let opts={

camera:{

latLng:latLng,

zoom:11,

tilt:30

}

};

this.map=this.googleMaps.create(element.nativeElement,opts);

this.map.on(GoogleMapsEvent.MAP_READY).subscribe(()=>{

console.log('Map is ready!');

});

}

}

When the init() is fired we use the location to set the center of the camera for the map. The new map is created by passing in the options and the DOM element that will hold the map.

We’ve also added a listener that will log out to the console when the GoogleMapsEvent.MAP_READY event is fired. You can add logic here to handle things like adding map markers, changing the map center programmatically etc.

Handle the creation and display of the map on your page

This is the final step to display the map on your page.

First, we create the DOM element that will host our map on the page.

main.html

XHTML

1

2

3

4

5

6

7

8

9

10

11

<ion-header>

<ion-navbar>

<ion-title>

Google Maps

</ion-title>

</ion-navbar>

</ion-header>

<ion-content>

<div #mapid="map"></div>

</ion-content>

Then we add some styles that will ensure that the DOM element can host the map. If you don’t include this your map will not display.

main.scss

Sass

1

2

3

4

5

6

7

8

9

10

11

12

13

page-home {

#map {

width:100%;

height:100%;

display:flex;

justify-content:center;

align-items:center;

}

ion-app._gmaps_cdv_ .nav-decor{

background-color:transparent!important;

}

}

Finally we create the map by passing the users location and the DOM element to our map provider.

Testing

We are now ready to test the final implementation. You can do this by running ionic serve to test the web-based implementation of Google Maps. Run ionic cordova run android or ionic cordova run ios to test the iOS and Android implementations.

Conclusion: Ionic Google Maps

This approach to handling Ionic Google Maps is focused on having the flexibility of being able to test in the browser and the performance of running the iOS or Android SDK versions of Google Maps. It takes a bit more effort as you have to maintain the code in two places but I feel the payoff is worth it.

Changing from an existing Google Maps implementation should not be too difficult as long as you don’t leave out any functions when you refactor this alternative approach.

Hi, I'm Baadier Sydow. I author this blog and work as a developer in Cape Town, South Africa. I spend most of my time developing hybrid mobile applications and working with Ionic, Angular, WordPress and Laravel. I'm excited to see what Progressive Web Apps can do for the future of the web.

Thank you, this is great. However I can’t get it to work in the browser or the dev app which are the two main ways I’d like to test during development. I realise that the dev app can’t run ionic native for google maps but could we detect this and serve the JS implementation? In the browser I get the following error :

That’s ok, I just got off the phone and I’m knackered 🙂 Let me know when its up and I can have a look tomorrow night. On an aside, I’ve assumed throughout the conversation that you’re using Cordova and not Capacitor?

It doesn’t work for me when I build for emulator or device either.. Do I need to install the SDK for Xcode and all that? Seems strange if I did as this is not in the documentation for cordova-plugin-googlemaps

Thanks for your reply. I am able to build the app and run it on an iPhone and the Xcode emulator (haven’t tested android yet) I can get a js google map in the browser now using fake location data but the problem is the native map simply isn’t showing up. I’ve tested the google maps demo Xcode app on device using my api key and that works fine so the key is good. I’ve followed your tutorial step by step, one thing I changed was “tnpm install –save @ionic-native/geolocation” as I assumed it was a typo. Any ideas?

Thanks for helping me get this running! Now It’s working, I was wondering what your suggestion would be to do other maps processes such as adding markers and updating locations using the same kind of dual-implementation way. Obviously the ideal solution would be if the plugin was written to handle js browser as well but that’s unlikely to happen.

While the dual approach is cumbersome I don’t see a way around it at this stage.

The only consolation is that you likely wont have to create too many methods that handled by both. You’ll probably be handling a few map interactions with the rest of your application living as things that handle or respond to those actions.

Its a pity that its unlikely Ionic will create a package for this in Capacitor https://capacitor.ionicframework.com/ which would make everyones lives easier. Capacitor allows you to use the correct underlying technology wherever your application runs. The community may well create something in the future that could be used.

The other alternative is that you bit the bullet and use the native only.