Ionic 2 – Google Maps

Hi Friends,

Hope you are all well. This post is clearly the most requested one by our friends. We’ll see how to embed a map into your Ionic 2 app, and then moving the view, adjusting the zoom on the map and also how to place a marker on the map.

Let’s begin.

A screencast of this post.

The complete code for this post can be found here.

First of all let’s scaffold out a new app using the ionic-cli.

Now to access the Google Maps Api we need a key.

To obtain an API key

Follow the instructions here – For Mac & Linux.

Follow the instructions here – For windows.

(Please see video for more details on getting key)

Now install the plugin using the below command.

Once you have installed the plugin install the ionic-native wrapper for google maps using the below command.

Open up app.module.ts and add the GoogleMap class as shown below.

Now open up home.html and add the below line of code inbetween the <ion-content> tags.

Now open up app.component.html and add the below line of code.

The code is very simple. We have simply created a reference to the div tag in our view and placed a google map in it. Let’s run this code and see what happens.

If everything goes fine, you would see a screen as shown below.

Screenshot_2017-04-01-19-25-00

Whoa, we got the map, but wait, isn’t it a bit zoomed out and also we would like to maybe show a particular place on the map when it loads rather than trying to show the whole of the world right..?

Say for example we want to show New york on the map when it loads.  The latitude and longitudes of new york can be found using a simple google search.

Open app.component.ts and edit it as shown below

We are using the LatLng class to create a new LatLng instance. We then pass it on to the CameraPosition instance as the target and few other options like zoom and tilt to enhance the viewieng experience. Then we use the moveCamera() to move the view to the new postion (New York).

Note that we are using GoogleMapsEven.MAP_READY) event to signify whether the map has been loaded into our view.

Now run the app. If everything goes fine, you should see something like this.

Screenshot_2017-04-01-19-27-37

Wow.. That’s great right ?

Markers:

Markers are visual aids which are placed on maps to denote the key places/cities/areas to be noticed in the first glance. In short, they are like thumbtacks placed on a physical map.

To create a marker on a specified location on the map we could use the map.addMarker() function and we could also pass in several options to the marker.

Open up app.component.html and add the below code.

Now run the app. If everything goes fine, you should see a screen as shown below.

Screenshot_2017-04-01-19-21-05

As you could see our marker is now placed on New York.

 

I have dealt with very basic steps in embedding maps into your app in this article. There are a lot of cool stuff that you could do with the google-maps plugin.

Hopefully this was helpful to you guys. If you found it helpful, kindly share it with someone and help them too.

Thanks for reading guys. Peace.. :)

Liked it? Take a second to support admin on Patreon!
  • Pratik Bachchhe

    https://uploads.disquscdn.com/images/2e2eb73cfd402ca04dfd97fb3f1ae281f588c74e2f6c015b8ead47d90d747bde.jpg

    I have follow above codes but output display below one.

    PLEASE NEED HELP TO RESOLVE this issues.

    • khalid

      I have the same problem. did you resolve it. Thank you

      • Pratik Bachchhe

        Yes but When i open left side menu that menu item didn’t click.

        Also that whilte area space if i move my finger than background MAP will be moved.

        • khalid

          Where was the problem exactly. because the map doesn’t appear.

          • Pratik Bachchhe

            import { Component } from ‘@angular/core’;

            import { NavController,Platform,NavParams, ToastController } from ‘ionic-angular’;

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

            import { Geolocation, Geoposition } from ‘@ionic-native/geolocation’;
            import { NativeGeocoder, NativeGeocoderReverseResult } from ‘@ionic-native/native-geocoder’;
            import { LocationAccuracy } from ‘@ionic-native/location-accuracy’;

            //declare var google: any;
            //this.platform.ready().then(()=>this.loadMap());

            @Component({
            selector: ‘page-page1’,
            templateUrl: ‘page1.html’
            })
            export class Page1 {

            //@ViewChild(‘map’) map;
            lat:any;
            long:any;

            constructor(public navCtrl: NavController,
            public platform: Platform,
            public googleMaps:GoogleMaps,
            public navParams: NavParams,
            private geolocation: Geolocation,
            public geocoder: NativeGeocoder,
            public toaster: ToastController,
            public locac: LocationAccuracy) {
            }

            ngAfterViewInit() {
            this.geolocate();
            //this.loadMap();
            }

            loadMap() {
            let element = document.getElementById(‘map’);
            let map: GoogleMap = this.googleMaps.create(element, {});
            //let latlng = new LatLng(52.370216,4.895168);
            let latlng = new LatLng(this.lat,this.long);

            map.one(GoogleMapsEvent.MAP_READY).then(() => {
            let position: CameraPosition = {
            target: latlng,
            zoom: 10,
            tilt: 30
            }
            map.moveCamera(position);
            let markeroptions: MarkerOptions = {
            position: latlng,
            title: ‘Netherland Map Demo’
            };

            let marker = map.addMarker(markeroptions).then((marker: Marker) => {
            marker.showInfoWindow();
            })

            })
            }

            geolocate() {
            let options = {
            enableHighAccuracy: true
            };

            this.geolocation.getCurrentPosition(options).then((position: Geoposition) => {
            this.getcountry(position);
            }).catch((err) => {
            alert(err);
            })
            }
            getcountry(pos) {
            this.lat=pos.coords.latitude;
            this.long=pos.coords.longitude;
            this.geocoder.reverseGeocode(pos.coords.latitude, pos.coords.longitude).then((res: NativeGeocoderReverseResult) => {
            alert(‘NativeGeocoderREverseResult’);
            alert(JSON.stringify(res));
            let country = this.toaster.create({
            message: res.countryName,
            duration: 4000
            });
            country.present();
            this.loadMap();
            })
            }
            }

          • khalid

            Why you have putted Geolocation and Geocoder ?

          • Pratik Bachchhe

            this is for Current location get and for geocoder return JSON data for the same.

          • khalid

            that doesn’t work for me. Try to do the google map first to ensure that you don’t have a problem with it

          • Pratik Bachchhe

            Make sure you have successfully installed API KEY

          • Pratik Bachchhe

            ALSO in app.module.ts file added in providers see below code of it.

          • Pratik Bachchhe

            import { NgModule, ErrorHandler } from ‘@angular/core’;
            import { IonicApp, IonicModule, IonicErrorHandler } from ‘ionic-angular’;
            import { MyApp } from ‘./app.component’;
            import { Page1 } from ‘../pages/page1/page1’;
            import { Page2 } from ‘../pages/page2/page2’;

            import { StatusBar } from ‘@ionic-native/status-bar’;
            import { SplashScreen } from ‘@ionic-native/splash-screen’;

            import { GoogleMaps } from ‘@ionic-native/google-maps’;

            import { Geolocation } from ‘@ionic-native/geolocation’;
            import { NativeGeocoder } from ‘@ionic-native/native-geocoder’;
            import { LocationAccuracy } from ‘@ionic-native/location-accuracy’;
            /*import {
            GoogleMaps,
            GoogleMap,
            GoogleMapsEvent,
            LatLng,
            CameraPosition,
            MarkerOptions,
            Marker
            } from ‘@ionic-native/google-maps’;*/

            @NgModule({
            declarations: [
            MyApp,
            Page1,
            Page2
            ],
            imports: [
            IonicModule.forRoot(MyApp)
            ],
            bootstrap: [IonicApp],
            entryComponents: [
            MyApp,
            Page1,
            Page2
            ],
            providers: [
            StatusBar,
            SplashScreen,
            GoogleMaps,
            Geolocation,
            NativeGeocoder,
            LocationAccuracy,
            {provide: ErrorHandler, useClass: IonicErrorHandler}
            ]
            })
            export class AppModule {}

          • khalid

            nothing appears the same as the first screenshot you have posted

          • khalid
          • Pratik Bachchhe

            Can you please share your home.ts file please

  • khalid

    First Thank you for this tutorial which is useful.
    Please we will change ap.componene.ts or home.ts.
    Regards

  • mansoor

    hi,nice tutorial, thanks
    i just worked on your code after running for me it showing blank or white page help me to debug this

  • rahul arora

    Hello
    I hope you are doing great.

    I have read most of the tutorials and they are actual really great and I am very gratefully for that.
    I have a problem and hoping you can help me out with it, I am in urgent need of this and not able to find anything on the internet on this topic.
    I have created an application that is using google map native and I need to plot a route in between two points on that map.

    Any suggestion will be appreciated

    Thanks