Ionic Maps Video

Ionic 2 & 3: How to Use Google Maps & Geolocation



·

Adding map functionality to a mobile application can be extremely useful, especially when we throw Geolocation into the mix. The nature of mobile devices are that they are mobile obviously, and maps are generally most useful to people when they are on the move. It also gives us an awesome opportunity to display information contextually to a user (e.g. other users of the app that are nearby).

I’ve already covered how to add Google Maps API to an Ionic application, but now I’m going to show you how to set up the Google Maps API in an Ionic 2 application.

UPDATE: For a more advanced implementation of Google Maps in Ionic 2, check out this tutorial.

Before we Get Started

Last updated for Ionic 3.0.0

Before you go through this tutorial, you should have at least a basic understanding of Ionic 2 concepts. You must also already have Ionic 2 set up on your machine.

If you’re not familiar with Ionic 2 already, I’d recommend reading my Ionic 2 Beginners Guide first to get up and running and understand the basic concepts. If you want a much more detailed guide for learning Ionic 2, then take a look at Building Mobile Apps with Ionic 2.

Setting up a new Ionic 2 Project

I’m just going to be running through the motions here and listing off the commands you’ll need to run and things you’ll need to do to get your project ready for building this application. I explained this process and gave a lot more background in my tutorial on building a todo application in Ionic 2, so I highly recommend checking that out if you’re unfamiliar with how an Ionic 2 project is structured.

To generate a new Ionic 2 project, we can run the following command:

ionic start ionic-maps blank --v2

Once the project has finished generating, make it your current directory:

cd ionic-maps

If you take a look at the files and folders that are generated by the Ionic CLI, you will see that under app there is a home folder. This contains the default home component, which is made up of both a TypeScript file (where the class definition is held) and a HTML file (where the template is defined). We will use this for creating our map.

1. Adding the Google Maps SDK to an Ionic 2 Application

The Google Maps JavaScript API can be embedded and used on any website for free (up to a reasonably generous limit). Since it can be embedded in websites, it can also be embedded in HTML5 mobile applications.

It’s worth noting that there is also native Google Maps SDKs for iOS and Android, which we can also make use of through the use of a PhoneGap plugin. Although I’ve never used it myself, the native SDK should have better performance.

The JavaScript API works very well on mobile though, and I’ve used it for all of my projects that have required map functionality so far. As long as you take a smart approach to rendering markers, which I’ve covered in a previous series for map integration in Ionic 1, the Javascript API on mobile is capable of handling maps with thousands of markers.

Add the JavaScript SDK

To make the JavaScript API available within our application we will need to include the library. You can do so by loading it in your src/index.html file.

Include the Google Maps API in your src/index.html file (above the cordova.js file):

  <script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY_HERE"></script>
  <script src="cordova.js"></script>

NOTE: It is also important that you generate an API key for Google Maps and add it to the query string for the <script> tag above (replace YOUR_API_KEY_HERE). To generate an API key, just go to this page and follow the instructions under Get an API key.

Load the Map

Now that the Google Maps Javascript API is available within our application, we can create and load a map. Let’s start by adding a map to the template for our map component

Modify home.html to reflect the following

<ion-header>
  <ion-navbar>
    <ion-title>
      Map
    </ion-title>
    <ion-buttons end>
      <button ion-button (click)="addMarker()"><ion-icon name="add"></ion-icon>Add Marker</button>
    </ion-buttons>  
  </ion-navbar>
</ion-header>

<ion-content>
  <div #map id="map"></div>  
</ion-content>

We’re providing a title of Map and a button in the end position (you may also use start instead). We add a click listener for this button which will trigger the addMarker() function which will soon be defined in our home.ts file when clicked. Then we simply create a placeholder <div> to act as a container for the map we will add shortly. By adding #map to the element, we will be able to grab a reference to it with ViewChild later.

Now we need to modify our class definition for the map component to take care of generating a new map, and adding it to that container we just created.

Modify home.ts to reflect the following

import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';

declare var google;

@Component({
  selector: 'home-page',
  templateUrl: 'home.html'
})
export class HomePage {

  @ViewChild('map') mapElement: ElementRef;
  map: any;

  constructor(public navCtrl: NavController) {

  }

  ionViewDidLoad(){
    this.loadMap();
  }

  loadMap(){

    let latLng = new google.maps.LatLng(-34.9290, 138.6010);

    let mapOptions = {
      center: latLng,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);

  }
}

We have created a member variable to hold our map and we have also created a member variable that references the map element (the one we added #map to in the template). Also, notice that we have added declare var google; above the decorator, this is to prevent any warnings from TypeScript about the google object that the Google Maps SDK makes available to us. We use the ionViewLoaded function, which will run when the view is loaded, to call the loadMap function.

This function will handle creating a new map and loading it into our map div. We create a LatLng object, which is provided by the Google Maps API, to represent the location that we want to center the map on. For now I’ve set it to be my hometown of Adelaide, but in the next section we will use the Geolocation API to automatically set this to the users location.

Before creating our map, we create a mapOptions object which allows us to define some options for our map. Here we supply the center coordinates we just created, the initial zoom level, and the type of map we want (in this case we are using the road map style, but you could also use the satellite style for example).

Note that we are also keeping a reference to our map using this.map as we will need to refer to it elsewhere in this class.

Style the Map

All the code is in place to get our map working now, but if you take a look at it by running ionic serve you’ll just see a big blank screen. To get Google Maps to display correctly in an Ionic application, you need to add some styles first.

Add the following styles to your src/pages/home/home.scss file:

.ios, .md {

    home-page {

      .scroll {
        height: 100%
      }

      #map {
        width: 100%;
        height: 100%;
      }

    }

}

Now if you try to view your application you should actually be able to see the map.

2. Add the Geolocation plugin

The Geolocation API is the perfect companion for a maps application – maps deal with locations, and the Geolocation API allows you to retrieve a users location.

If you’re running this on a device, make sure to install the Geolocation plugin by running:

ionic plugin add cordova-plugin-geolocation

You will also need to install the Ionic Native package for this plugin with the following command:

npm install --save @ionic-native/geolocation

and add Geolocation as a provider in your src/app/app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { Geolocation } from '@ionic-native/geolocation';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

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

Geolocation will also work directly through the browser though, as it is part of the HTML5 API. Let’s modify our src/pages/home/home.ts file to make use of Geolocation now.

Modify src/pages/home/home.ts to reflect the following:

import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';

declare var google;

@Component({
  selector: 'home-page',
  templateUrl: 'home.html'
})
export class HomePage {

  @ViewChild('map') mapElement: ElementRef;
  map: any;

  constructor(public navCtrl: NavController, public geolocation: Geolocation) {

  }

  ionViewDidLoad(){
    this.loadMap();
  }

  loadMap(){

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

      let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

      let mapOptions = {
        center: latLng,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }

      this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);

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

  }

}

NOTE: Make sure your browser does not block the request for getting the users position, otherwise this function will not run and your map will not load.

The Geolocation API is asynchronous (meaning the code will not wait for the result before continuing), and the code inside of the fat arrow function (=>) will run when the position has been successfully retrieved.

The “fat arrow” functions may look a little bit confusing at first, but they are essentially just replacing the callback functions. So that this:

function(success){
    console.log(success);
}

becomes this:

(success) => {
    console.log(success);
}

so just drop the “function” and add an arrow “=>” – easy! One of the main benefits of doing this is that code executed within the fat arrow function will have the same scope as its parent (meaning you don’t need to do things like var me = this or var that = this).

The position object that is returned will contain the current latitude and longitude of the user, which we use to create our LatLng object instead of the hard coded values we were using before.

3. Adding Markers and Info Windows to the Map

Markers are a very commonly used feature in map applications, so we definitely want to take a look at how to add those. We’ve already got a button that calls an addMarker function, now we just need to create that in home.ts.

Add the following function to src/pages/home/home.ts

addMarker(){

  let marker = new google.maps.Marker({
    map: this.map,
    animation: google.maps.Animation.DROP,
    position: this.map.getCenter()
  });

  let content = "<h4>Information!</h4>";          

  this.addInfoWindow(marker, content);

}

This is a pretty simple function, we’re just using the Marker function provided by the Google Maps API. Simply by creating the marker variable with this function, the marker will automatically be added to the map we specify.

After that, we’re also creating some content and adding an info window that will be shown when the user taps on the marker. If you don’t want info windows, you can just remove those last two lines, but if you do want them, make sure to add the following function as well.

Add the following function to src/pages/home/home.ts

  addInfoWindow(marker, content){

    let infoWindow = new google.maps.InfoWindow({
      content: content
    });

    google.maps.event.addListener(marker, 'click', () => {
      infoWindow.open(this.map, marker);
    });

  }

This just creates a new info window by using another function provided by the Google Maps API, and then we set up a click listener on the marker that the info window is for.

If you run your application now you should see the map centered on your current location, and you should be able to add markers to the center of the map by clicking the + Add Marker button.

Summary

This is a very basic implementation of Google Maps in an Ionic 2 application, but it covers most of the core concepts you will need to know (initiating the map, adding markers and adding info windows). As I mentioned before, if you are creating an application with a lot of markers then you should take some steps to optimise how those markers are rendered. I will create a tutorial for doing that in Ionic 2 at some point, but for now you can take a look at how I did that with Ionic 1.

What to watch next...

  • guy katz

    I wonder, is there a time table for at least a beta release from angular 2 and ionic 2?
    I would like to wait for a beta before I start fiddling with it.

    • I just spoke to one of the Ionic guys about a rough estimate for a beta release of Ionic 2 for my next podcast, but they can’t say at the moment. You could assume it’s going to tie in pretty closely with the Angular 2 timeline, but obviously that’s pretty up in the air too. Ionic 2 seems reasonably polished, so I’m hoping for a beta release in a few months, but who knows!

  • Luís Cunha

    From your experience working with ionic 2, was there any noticeable performance improvement in mobile devices?

    • I haven’t been running the apps I’ve been building on devices, so I couldn’t say. A well designed Ionic 1 app performs very well anyway and in a lot of cases is indistinguishable from a native app, so I doubt you’d be able to notice any performance increases until you start getting into some more complex apps.

      • Luís Cunha

        What I wanted to know was that exactly, if an ionic 2 app performs closer to a native app, especially on android where web content rendering performs so poorly when compared to iOS.
        I’ve not run into any major issues besides some minor hiccups in view transitions, but my users have pointed them out and in general the navigation fluidity isn’t the same.
        Perhaps you could bring up the topic in your next podcast since you’ll be having an ionic team member as a guest, if I’m not mistaken, I’d be very interested on what he has to say on the matter, especially when considering competing technologies such as react native and nativescript who perform so well.

      • Good point on the Android devices, that’s somewhere where the difference could be visible to the naked eye. Unfortunately I’ve already finished recording for my next podcast, but I do have a low end Android device so I might do a comparison of v1 vs v2 as a blog post.

      • Luís Cunha

        Alright then, looking forward to it.

  • Hamza Alazzeh

    Hello Josh, I’m really happy I found your websites, alot of useful articles and tutorials
    As I found good resources on handling geolocation using ionic framework, do you know an easy to detect if gps is enabled or not on the user’s device, I tried diagnostics plugin but it didn’t work on iOS devices.

  • Pingback: Mobile Web Weekly No.81 | ENUE()

  • jeff

    Hi Josh,

    After doing all the steps in this tutorial,
    I got this error upon running the app in my browser.

    “TypeError: Cannot read property ‘getCurrentPosition’ of undefined”

    Am I missing something that is not included in this tutorial maybe?

    Thank you

    • Hi Jeff,

      Geolocation, as well as the other plugin interfaces, have been removed from Ionic 2 from now so this will no longer work. You would have to just use the standard syntax for the Geolocation plugin: https://github.com/apache/cordova-plugin-geolocation e.g: navigator.geolocation.getCurrentPosition(…)

      • Mox

        I’m running into the same issue as jeff. When calling “Geolocation.getCurrentPosition…” I get an error about Geolocation being undefined, even though I import the class at the top of my file.

        i.e. import {Geolocation} from ‘ionic/ionic’;

        I’m confused by your response. Your tutorial above and the official documentation for Geolocation (http://ionicframework.com/docs/v2/platform/geolocation/) do not use “navigator.geolocation…” are you saying the tutorial and Documentation are out of date and that one must use “navigator.geolocation …” instead of “Geolocation.getCurrent …”?

        When I do use “navigator” the error goes away, but I get a new error saying the first parameter is not a function. I’m guessing “navigator….” is not compatible with TypeScript? I have no idea, but any help is appreciated.

      • Hi Mox, the Geolocation implementation used in this tutorial has been removed from Ionic 2. So for now you just need to use the normal Cordova syntax which is navigator.geolocation.getCurrentPosition. Please see the link in the comment you replied to for information on how to use it – you can’t use the same syntax that is in this tutorial (right now at least) – the normal Cordova syntax doesn’t support promises.

      • Mox

        Thanks! Using standard syntax works

      • Thomas Thai

        I tried to use the standard syntax and got this error:

        EXCEPTION: TypeError: Cannot set property ‘map’ of undefined

        Which is related to this line:

        this.map = new google.maps.Map(document.getElementById(‘map’), mapOptions);

        It seems as though it thinks “this.map” doesn’t exist but was defined int he constructor.

        Would you post your map.js file so I can see what that looks like?

      • DringaDucal

        this.map is not available in the callback. I did like this to solve the problem with this:
        loadMap(){
        let el = this.mapElement.nativeElement;
        let map = this.map;
        navigator.geolocation.getCurrentPosition(function(pos){

        let latLng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);

        let mapOptions = {
        center: latLng,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
        }

        map = new google.maps.Map(el, mapOptions);

        });

  • Thomas Thai

    What I got was a black screen in the content section. I’m running Ionic 2 Beta. In addition, I put your www folder from the zip download file into the project directory.

  • Thomas Thai

    Update on why the screen is black. When I copy the www folder from your zip file and page it into the project directory while “ionic serve” is active, that screen will show the map as it should. If I quit from the “ionic serve” CLI window, and restart it again with “ionic serve,” the screen will turn black again. It looks like ionic copies some files from “projectFolder/app/pages” folder to “projectFolder/www/build” folder.

    • Thomas Thai

      The folder structure used in this tutorial is different than the recent ionic 2 beta. I ended up moving things around and into the projectFolder/app folder to get this corrected. In the new folder structure, there isn’t a projectFolder/www/app folder as was in this tutorial.

      • Thomas Thai

        I finally got this to work using the new file structure for ionic 2 beta, using the cordova’s navigator.geolocation.getCurrentPosition instead of the built-in ionic geolocation.getcurrentPosition() (which was temporarily removed — see Josh’s comments below). Here is the change to map.js loadMap() method. To addressed the error “EXCEPTION: TypeError: Cannot set property ‘map’ of undefined,” I added “var that = this;” and changed “this.map…” to “that.map…” The callback function onSuccess’s ‘this” is not the same as ‘this’ in the main class. I read you can reference the class’ ‘this” variable using fat arrows but I’m still not up to date on javascript yet.

        loadMap(){ // using cordova geolocation plugin

        var that = this;

        var onSuccess = function(position) {

        let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

        let mapOptions = {

        center: latLng,

        zoom: 15,

        mapTypeId: google.maps.MapTypeId.ROADMAP

        }

        that.map = new google.maps.Map(document.getElementById(‘map’), mapOptions);

        };

        // onError Callback receives a PositionError object

        function onError(error) {

        alert(‘code: ‘ + error.code + ‘n’ +

        ‘message: ‘ + error.message + ‘n’);

        }

        let options = {timeout: 10000, enableHighAccuracy: true};

        navigator.geolocation.getCurrentPosition(onSuccess, onError, options);

        } // loadMap()

  • Mike Schall

    Your tutorials are very helpful. Thanks for all the time you put in on them. I’m just getting started with Angular and Ionic. I have maps loading into a page. I then moved to loading a map page based on tapping on a list. The first time I push the MapPage on to the nav stack it works fine. Every time after that it fails with a blank map page. I think it has something to do with the map div already contains the google.maps.Map html the second time the MapPage is constructed even before the map is instanciated (confirmed by logging outerHTML to console before the new). I’m sure I’m missing something…


    constructor(app: IonicApp, nav: NavController, navParams: NavParams) {
    this.nav = nav;
    this.map = null;
    this.item = navParams.get('item');
    this.loadMap();
    }
    loadMap() {
    let itemLatLng = new google.maps.LatLng(this.item.geolocation.lat, this.item.geolocation.long);
    let mapOptions = {
    center: itemLatLng,
    zoom: 18,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    let mapDiv = document.getElementById("map");
    console.log("mapDiv.outerHTML", mapDiv.outerHTML);
    this.map = new google.maps.Map(mapDiv, mapOptions);
    console.log("map created", this.map);
    }

    • Mike Schall

      I have this “working” by using a setTimeout. It feels dirty, but the maps always load… Do angular templates get cached AFTER the constructor?


      constructor(app: IonicApp, nav: NavController, navParams: NavParams) {
      this.nav = nav;
      this.map = null;
      this.item = navParams.get('item');
      setTimeout(() => {
      this.loadMap();
      }, 100);
      }

  • make sure map.scss is added inside app.core.scss file `@import “../pages/map/map”;` else map wont show… it sounds simple and stupid, but happened to me 🙂

  • Please help!! I have the following issue, this method is working fine on the browser with the ‘ionic serve’ command, but showing a blank white screen while running the app on the phone.

  • dskaza

    Hi Josh,
    I have a problem with run in browser this app. So when I’m try to build with ionic serve have an synty error:
    ionic-maps2/app/app.js: Unexpected token (12:22)
    10 | })
    11 | export class MyApp {
    12 | constructur(platform: Platform) {
    | ^
    13 | this.platform = platform;
    14 | this.initializeApp();
    15 | this.root = MapPage;

    The problem is in the line 12 with character :.

    Thanks for your help.

    Denis

    • matt

      YES ME TOO. ALWAYS! CANT RUN IT…

  • Tommy R. Williams

    The regular google map works fine for me with Ionic 2. HOWEVER, When I use side nav to switch to a different page, and then switch back to the map/home page, the map is blank. I tried triggering a gmap resize if the map is already loaded, and even tried to add a timeout, but to no avail. Any ideas?

  • Bobby Naidu

    this.map = new google.maps.Map(document.getElementById(“map”), mapOptions);
    in above line’ google’ is not supprting in my editor ,,it comes from which import ,?????????????

    • Elaine Skapetis

      Hi Bobby, for me was the same (I’m using ts / visual studio)
      may you need to install typing for google.maps,

      yourprojecttypings>typings install google.maps –ambient

      for me was only this.

      • Bobby Naidu

        I already done it ,Thanks for your Reply

      • Bobby Naidu

        Is there any code in Ionic2 for passing simple data using NFC???

      • For anyone who’s interested… `–ambient` changed to `–global` so the new command is…


        typings install dt~google.maps --global

  • Pingback: Adding Background Geolocation to an Ionic 2 Application | HTML5 Mobile Tutorials | Ionic, Phaser, Sencha Touch & PhoneGap()

  • Can Delibaş

    How do we add ionic2 components such buttons, ion-card, etc to info windows? We had $compiled in Angular1 but what about Ionic2?

  • For anyone who has the same problem, I got a “cannot read property ‘offsetwidth’ of null” issue when running because not all scripts were initialized, So in part 1 I just removed the this.loadMap() call and added it to the ngOnInit function like this:

    ngOnInit(){
    this.loadMap();
    }

    • Daniel Archer

      dude thanks so much. it fixed it for me 😀

      • Daniel Archer

        oh wait, ionViewDidLoad() works just as fine. Turns out I wrote ionViewDidLoaded(). shows how good me grammar are

  • Pingback: Creating an Advanced Google Maps Component in Ionic 2 | HTML5 Mobile Tutorials | Ionic, Phaser, Sencha Touch & PhoneGap()

  • Ramesh Bas

    Your tutorial did not work. Where do you find import {App, Platform, Config} from ‘ionic/ionic’; that is line 1 in map.ts?
    ionic serve command throws this error
    I did follow:
    npm install -g [email protected]
    ionic start ionic-maps blank –v2
    cd ionic-maps
    my ionic apps are working!
    :

    • Mike Schall

      Depending on what version of Ionic you are using, there have been breaking changes. You don’t import from ionic/ionic anymore… Take a look at the breaking changes document to see what changes need to be made to this example: https://github.com/driftyco/ionic/blob/master/CHANGELOG.md

    • Stacktx

      i guess there is no import ionic/ionic anymore, i think ur version is too old, try just follow the steps from this tutorial and will be working at the end
      btw u are using TS based project or JS one?

  • Ritesh Bhat

    please update this post according to beta.10 release of ionic 2 ….

  • worldnick

    This tutorial is far from working. Number one problem is “initMap()” is not a function. Of course it’s not a function. If google maps calls that function and we have not defined it. Secondly there is something with typings that seems like a problem and that’s not even mentioned here. This tutorial is like 50% of how this might work. It’s like a hint. I’m not even sure if it’s completely wrong, which would make this process take even longer…

    • Thibauld nuyten

      the tutorial uses ionViewDidLoad(){this.loadMap();} It doesn’t use the method of having the callback in the script url.

  • Pingback: Creating an Advanced Google Maps Component in Ionic 2 | joshmorony - Build Mobile Apps with HTML5()

  • Pingback: Integrating Native Google Maps into an Ionic 2 Application | joshmorony - Build Mobile Apps with HTML5()

  • Rolvar

    I ran this code on a real device and I’m getting a blank screen, I already ran “ionic plugin add cordova-plugin-geolocation” and still nothing, what can I do?

    • TheVoiceInYourHead

      i also had the same problem. The tutorial is great, but there are 2 things missing:

      – Install the cordova whitelist plugin and add following line to config.xml –> lets you use resources from the specific url (watch out: this url uses HTTPS!)

      – open the android manifest and add the following line: –> grants permission to connect to the internet

      after these two changes, the map will be displayed on your android device… have fun

      • Varaparla Narasinga Rao

        till i didn’t get any map screen on the screen

      • Łukasz Dramiński

        Could you share your config.xml file? I followed your steps but didn’t work.

      • Łukasz Dramiński

        Could you share your config.xml? I followed your steps but didn’t work for me.

      • didaevag

        Not for me either.

      • didaevag

        Even performing
        these procedures to make the map plan build on a blank screen, it works
        using the ionic serve, and for the ionic view using ionic upload now
        when I do the build the map does not appear appears

      • Thibauld nuyten

        I did all of these steps but no dice. When I call addMarker() it gives an error stating it can’t find the map object.

        when loading the page I get a bit more useful error:

        PositionError
        code: 1
        message: “Illegal Access”
        __proto__: Object

  • Suresh

    Hi Josh,
    Thanks for the tutorial., I ‘m trying to use text services from google rather than displaying a map. I’m not sure how to implement the callback function of the results from the text search. Can you help me in correcting it..

    Original Js file from Ionic1:

    service = new google.maps.places.PlacesService(map);
    service.textSearch(request, callback);
    }

    function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
    angular.forEach(results, function(data){
    $scope.db.push(data);
    });
    }
    }

    currently in ts:

    Geolocation.getCurrentPosition().then((position) =>{
    let request = {
    location: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
    radius: 500,
    type: [‘store’]
    };
    console.log(position.coords.latitude, position.coords.longitude);
    var service = new google.maps.places.PlacesService(document.getElementById(‘map’));

    service.textSearch(request).then((result) =>{
    console.log(“result”,result);
    }, (err1)=>{
    console.log(err1,”textsearch error”);
    });

    },(err2)=>{
    console.log(err2,”currentlocation error”);});
    };
    }

    Is this the correct way of callback implementation on the text search api call??
    If i execute this then i see error on the console like “Error: Uncaught (in promise): TypeError: Cannot read property ‘then’ of undefined”
    Looking forward to hear from you.
    Regards
    Suresh

  • Daniel Marc Ehrhardt

    i think it is better to replace:
    this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
    with:
    this.map.setOptions(options);

  • Garel Bidi

    Hi Josh ! Thank you so much for your tutorial !!!
    I’ve a small issue (I guess) with the geolocation part :
    When I use “ionic serve”, I’ve this message : “Error TS2339: Property ‘getCurrentPosition’ does not exist on type ‘{ new (): Geolocation; prototype: Geolocation; }’.”

    Can you help me please ?

    Thanks a lot from France 😉

  • Joel Sene

    Thank you, your Tutorial worked just fine.
    Theres only one thing tho, since Im new to this.. how do add the “My Position” button to the app?

  • José Ortega

    Dear, how I can add buttons and links to InfoWindow?

  • Stacktx

    Awesome, that helps me alot! thanks!!
    But i have some question, since u are using external JS lib (Google) and u declare the variable google inside ur TS file to TSCompiler allow u to use it, how can do i to use external function since i dont have the object to declare?
    Exemple: “U are using google, so u can declare google and use his function, google.maps…”
    But im my case im trying to use socket.io, i imported the JS in index but i need use the funtion io() and thats i dont call it from one objeto, how can i declare it?

  • Jonathan Chin

    Very awesome tutorial. I followed this, the one on native google maps, and the one comparing the two. I’ve decided to stick with the web / javascript implementation.
    It works well, except when I navigate to the page that has the map, navigate away, then come back to the page, the map no longer displays. How can I fix that?

  • Francesco Polimeni

    Hello,
    ionViewLoaded doesn’t work, it has been replaced by ionViewDidLoad

    • Benjamin McMullan

      Thanks, fixed my problem!

  • munashif muhsin

    i am sorry but i am getting the “google is not defined error”. Can you please help me with it?

    • Pedro Leal

      Maybe late, but I had this error, too. This might happen because ionic is not refreshing your index.html into www folder. I solved this by just deleting the www/index.html file and restarting ionic.

      • Shane

        This is exactly what happened to me. Thanks!

    • Alan Dunning

      Have you added ‘declare var google;’?

      It will be beneath ‘import { NavController } from ‘ionic-angular’;’

  • sundara nataraja amancharla

    ionViewLoaded() should be Changed to ionViewDidLoad

  • Shane

    Does anyone know how to avoid the `Access to geolocation was blocked over insecure connection to http://localhost:8100.` error when previewing the app in safari?
    It seems to work in Chrome without issues, but that’s not my browser of choice.

    • Alexander Contreras

      Did you solve the problem? I have the same mistake.

      • Shane

        Nah, I just resorted to using Chrome for all my Ionic testing. I believe Firefox works as well.

  • Shareq Shaikh

    Geolocation is not getting latitude and longitude. It works in browser but not in real phone or emulator.

  • Francesco Mussi

    Great tutorial! You can just remind to call the addMarker() function from inside the loadMap(). It can save some time as it can easily be overlooked.

  • Daniel Archer

    followed up to the point where you add the custom css styles and said “Now if you try to view your application you should actually be able to see the map.”
    although i cannot see the map and there are no errors. i also tried copying and pasting your code but same result O.o

  • Master Game

    Hi!

    Thank you for this very interesting tutorial about Google Maps.
    Just, I invite you to npm install @types/google-maps, so you don’t need to declare var google in the top of your home.ts and also you can benefit of all Google Maps definition 🙂

    Enjoy.

  • Master Game

    Oh! Also, ionViewLoaded() is no longer a valid lifecycle event: https://ionicframework.com/docs/v2/api/navigation/NavController/#lifecycle-events

    You should replace it by ionViewDidLoad() 😉

  • Ravishel Naicker

    Hi. I want to implement navigation as well. I have a marker on the map and i want the map to show the user route/path from its current location to the marker. Is it possible either via google maps api javascript or via Cordova plugin for native app

    • Dias

      It would be great to find tutorial

  • Scriline

    https://uploads.disquscdn.com/images/83c7ebf770bfc89fd6120bd0cd62d5718f27e99fdd3f939a0236aa4c6aec59ac.png

    Hi guys, I’ve just been following this tutorial, but google maps don’t works for me, I have a blank page :

    Don’t understand why, have you an idea ?

    Thanks a lot

    • Jose Angel Martinez Descalzo

      Hi!.

      I have the same problem as Scriline, google maps don’t works for me, i have a blank page.

      any idea?

      Thx!.

      • Jesus Man

        Check my reply above

      • salwaniza

        i got the blank page too and already insert this.ionViewLoaded(); in the constructor. help me please :/

      • Jesus Man

        Are you getting any errors/warnings while compiling? Are you using ionic serve? What does your home.scss and home.HTML look like? Can you post your project in plunkr?

      • Neel Muley

        am also facing same problem, app showing blank page and map did not load, and no error.

      • Juanjo

        Could someone solve the problem? To me also shows me a blank page, no error in the chrome console.

      • Juanjo

        The problem was style. Solution:

      • Krunal Vaghela

        Yes ,… Thanks My Problem Resolved.. By

      • Aniket Gundecha

        Give an inline style of height:500px .. if you dont have any console errors

      • Jesus Man

        Also, user Master Game posted this below: “3 months ago
        Oh! Also, ionViewLoaded() is no longer a valid lifecycle event: https://ionicframework.com/

        You should replace it by ionViewDidLoad() ;-)”

        Have you tried this?

    • Jesus Man

      Hi! Put something in that empty constructor 😉

      constructor(public navCtrl: NavController) {
      this.ionViewLoaded();
      }

  • Berkhan

    How to get coordinates of an address ?

    • Benjamin McMullan

      Search the address on google maps and then look at the url

  • Abhimanyu Kumar
    • Kino10

      I’m getting the same error. Any workaround?

  • Mustafa Aydin

    Hey everbody,
    How can I add google Maps direction service?

    thanks a lot

  • Roshan Dhabekar

    Thanks man, i added js script path as src, its working on browser with ionic serve but i am facing problem while running on android devices , it showing error “Failed to load resource: the server responded with a status of 404 (Not Found)” for google map js , can you please help me for this.

  • Vivek B

    I would like to add map in a different page other than home page. Can i do this?
    Attached is my app folder structure. When i tried to add map in temples page, i had to mandatorily place the css contents in homes directory. Why so? Any one has some knowledge on this reason?

    https://uploads.disquscdn.com/images/b831efe0045116610a09d7ad8cee7224cc61bd679c6a44cbbae41f5df0245234.png https://uploads.disquscdn.com/images/780ed1a446fa4bbd7790f204374a404e5ecb62ee3aacae0666dd85d4eea42f93.png

  • Vivek B

    Can i have styling without selector?

  • Kevin Gomez

    Hi josh, when I do “ionic serve” work perfectly, but when I emulate in androd, ios, browser get:
    PositionError
    Code
    2
    Message
    “Network location provider at ‘https://www.googleapis.com/’: Returned error code 400.”
    Any idea why? I read a lot and I try many things, but I cant fix it.

    • Alexander Contreras

      Did you solve the problem? I have the same mistake

      • Kevin Gomez

        Hi Alexander, finally I did not use the native option, for me works perfectly:

        navigator.geolocation.getCurrentPosition(success, error, options);

        function success(pos) {
        var crd = pos.coords;
        console.log(‘Your current position is:’);
        console.log(‘Latitude : ‘ + crd.latitude);
        console.log(‘Longitude: ‘ + crd.longitude);
        console.log(‘More or less ‘ + crd.accuracy + ‘ meters.’);
        };

        function error(err) {
        console.warn(‘ERROR(‘ + err.code + ‘): ‘ + err.message);
        };

        Tested in android, iOS , both in emulator and real device, and tested in the browser.

      • ng_gopi

        hi kevin, i tried ur solution it doest work
        1.getCurrentPosition(success, error, options);–> error:Cannot find name ‘options’.
        2.its going to error case
        can u tell me how to solve.thanks in advance

      • Kevin Gomez

        Hi ng_gopi… Sorry fot that .. miss this…
        var options = {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
        };

      • ng_gopi

        thanks for an replay.
        Advanced Google Maps Component in Ionic 2 am working on that with network and without network maps has to show. it working as i expected in web . when it comes to mobile showing blank page can u please tell me how to solve this.

  • Boutar Badii

    I first had a problem of the map not showing .. so i changed the ionViewLoaded() to ionViewDidLoad() and it’s working now!

  • viknek

    how would you use the same map in different components, without reinitialising in every component?

  • Dejan Slijepčević

    For anyone who still has problems with blank page, what worked for me is just setting width and height of the div where map should be placed.

  • med amine

    i have a problem with blank page even i did ionViewDidLoad?

    • zzz.td

      In tutorial he said to put inside the constructor this.ionViewLoaded(); // call the method that you created. But, this method doesnt work anymore. Put: this.ionViewDidLoad(); and change the name of your method inside the same class. PAY ATTENTION ON THIS!

      • med amine

        nop this is not the problem, the problem it was in browser he didn’t share the location so the application show blank page but when i change the browser it’s work fine
        thanks for your reply

  • Ignacio

    Hello everybody,
    I am receiving the following error, does anyone have any idea of what’s causing it? Btw, the name of my project is ionic-maps, not MyApp.
    Thanks!

    https://uploads.disquscdn.com/images/daf01afa3c391899575c5a2525277ca36850726127fc344df88e24084ec85227.png

    • Raphael Arthur

      Hi!! I have the same problem!!

  • Braian Mellor

    Hello I get this error on device and browser

    Error: No provider for ApplicationInitStatus!

    • EM Products

      I’m facing the same error 2

      • Braian Mellor

        I solve it. Into app.module.ts if you add import { BrowserModule } from ‘@angular/platform-browser’; you need to add the browser into imports
        like this

        import { BrowserModule } from ‘@angular/platform-browser’;
        import { NgModule, ErrorHandler } from ‘@angular/core’;
        import { IonicApp, IonicModule, IonicErrorHandler } from ‘ionic-angular’;
        import { MyApp } from ‘./app.component’;
        import { HomePage } from ‘../pages/home/home’;
        import { Geolocation } from ‘@ionic-native/geolocation’;
        import { StatusBar } from ‘@ionic-native/status-bar’;
        import { SplashScreen } from ‘@ionic-native/splash-screen’;

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

      • EM Products

        thank you , this did really solved my problem , thanks again 🙂

      • John Paul

        Thank you

  • ng_gopi

    Hi Guys,

    i am pretty new to ionic2.i gone through this tutorial. after running my app. my web page is displaying blank.could u help me how solve this this problem i searched alot it doesnt work
    getting Error Like:(PositionError {code: 2, message: “Network location provider at ‘https://www.googleapis.com/’ : Returned error code 403.”})
    https://uploads.disquscdn.com/images/b06f07f8ce4bb9e3a04e317f640ba55e844edc9db3fd9f7e411090beeba40399.png

  • Great tutorial,
    is there anyway to display markers on page loading ? without clicking on buttons ?
    Thanks in advance

  • Mattheus Sgrott

    this is work on ‘ionic serve’, but not in ‘ionic run android’. I see only a blank page.

  • Stephen Murphy

    Could anyone Tell me how to mark the users location with a blue dot or marker ? also trying to find a search box method any help would be very much appreciated

  • mansoor

    Uncaught (in promise): TypeError: Cannot read property ‘nativeElement’ of undefined TypeError: Cannot read property ‘nativeElement’ of undefined at http://localhost:8100/build/main.js:83102:61 at t.invoke (http://localhost:8100/build/polyfills.js:3:9655) at Object.onInvoke (http://localhost:8100/build/main.js:36749:37) at t.invoke (http://localhost:8100/build/polyfills.js:3:9606) at e.run (http://localhost:8100/build/polyfills.js:3:7019) at http://localhost:8100/build/polyfills.js:3:4661 at t.invokeTask (http://localhost:8100/build/polyfills.js:3:10284) at Object.onInvokeTask (http://localhost:8100/build/main.js:36740:37) at t.invokeTask (http://localhost:8100/build/polyfills.js:3:10220) at e.runTask (http://localhost:8100/build/polyfills.js:3:7637) at i (http://localhost:8100/build/polyfills.js:3:3707) im getting this error how debug this error plz help me

    • Yusuf

      i was run it smoothly last night.. and suddenly i got this error..

    • Yusuf

      i found the solution man.. you need to add on your html.

      in my case, i was cut the text and for get to paste it.

  • Emma Reavley

    Hi Josh,
    In section 3 of this tutorial, you are adding an Info Windows to each of your marker.
    You have added: let content = “Information!” I can see the same title for each of my markers.
    But I would like to know how to custom those ‘info windows’ with our own information from our JSON database.
    For example, instead of having “information” written in the window, it specifies the title of the landmark and the description link to it (created in database).
    Do you any solution?
    Thank you very much in advance and thank you for all your tutorials!

  • Danilo

    Please help me. What would be the role of clearing the map for this example?

  • Vivek Sinha

    Is there any way to get the city name from latlng?

    • freeze

      geocoder service from google maps api.

  • hesam alizadeh

    ionic 2 current location doesn’t return any positions when i fire up the app and then aks the user switch on the location. Once the user swtiches the GPS on and clicks the retry button to get the position of the user the getcurrent user location doent return any positions. However when the gps is on and i fire up the app every thing works.

    I also check to see if the location is enabled first and then try to get the current location. any idea why would this happen ?

    Diagnostic.isLocationEnabled().then( bool =>{
    if( bool == false ){
    console.log(“location is disbaled”)
    }
    else{

    Geolocation.getCurrentPosition(options).then((position) => {

    this.usersLocation = {
    lat: position.coords.latitude,
    lng: position.coords.longitude
    };

    console.log(‘user location’, this.usersLocation);

    }).catch((error) => {

    console.log(‘falling back to deafult user location’,
    this.usersLocation);

    });
    }
    });

    Any help would be appreciated. Thanks.

  • Erasmo Bellumat

    Thank you for this tutorial! Help’s me a lot! Regards from Brazil.

  • Ravishel Naicker

    I want to implement info window similar to how the native Google Maps apps have. I have seen viewing Map on a normal browser via the phone also have same look of the info window.

    On Android its known as Bottom Sheet. Since its possible to get same look on a mobile browser i believe it might be possible to have that in ionic 2 as well ?

  • Nick Malialis

    When I click on the AddMarker it does nothing on my nexus 4. In the browser it fails to load anything.

  • Testq Tests

    How to remove specific marker ?

  • noor

    I keep getting Cannot read property ‘maps’ of undefined. How do I solve this

  • Kiran Dhongade

    Very nice tutorial! Thank you 🙂

  • Max

    Hello there,
    I am getting this error.. May I know which part should I look into? Seems like the google API isn’t initiatlize properly
    TypeError: Cannot read property ‘maps’ of undefined

  • Why don’t you use the google-map ionic/native plugin?
    https://ionicframework.com/docs/native/google-maps/

  • Pedro Santos

    how to customize infowindow ?

  • Goodwin Goodwin

    Hello there,
    the geolocation is not working in the android 7 and above.. I have both ionic1 and ionic2 project.. both of them working in android 5,6.. can you please help ..

  • aztecatl

    que tal saludos….. como puedo hacer rutas de un puntoA a un punto B en ionic 2, puedes hacer un tutorial asi?

  • Vocay

    I got an error on the home ts file :
    Supplied parameters do not match any signature of call target.

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

    I don’t understand the problem

  • Vanessa Tan

    Can someone help me? I copied the codes till the part that your map should show part but my map is still a blank page. I’m using genymotion emulator to test the plugin and my ionic is ver 3. Also, anyone noe if im able to upload ionic 3 app to ionic view? I tried changing the styling codes as suggested in the codes but it still doesn’t work

    • Vanessa Tan

      now it gives me an error tat google isnt defined although i alr declared it as a var

  • Phinah Ogutu

    Hey guys, I am also trying to impliment Google maps for my ionic app. I want to support Android, iOS and Windows. Which method is good for my requirement?

  • Manuel Castillo

    Hello, I’m trying to integrate a map of google maps into an application with ionic 2/3.
    When trying to display the map, everything works OK, except when I try to use a MODAL page or a page that contains SLIDES.
    I tried using Angular Google Maps and also direct with the Google api.
    In no case it works, only in “normal” pages.
    1. Is there any content restriction to be deployed in MODAL or SLIDES?
    2. Has anyone used MODAL or SLIDES to display a map?
    I hope you can help me. I have been working on this for 14 consecutive hours and I have to deliver it TODAY.

  • vinu

    update the ionic cordova commands

  • Ignatios Santiktsis

    Hello Josh, thanks for the tutorial.

    With command ionic serve the geolocation is working and the map shows the current location correct in Chrome browser

    When i run command “ionic cordova run android” and the app opens in my Lenovo android phone( 5.1) the GET THE LOCATION BUTTON does not get the current location.

    I inspect the app from chrome browser when the phone runs the app and i have console.log the lattitude and longitude inside function getLocation but the getLocation function is never called.

    Here is the console output when i inspect the device:

    Angular is running in the development mode. Call enableProdMode() to enable the production mode.
    cordova.js:1223 deviceready has not fired after 5 seconds.
    main.js:101178 Ionic Native: deviceready did not fire within 5000ms. This can happen when plugins are in an inconsistent state. Try removing plugins from plugins/ and reinstalling them.
    main.js:101173 Ionic Native: deviceready event fired after 6728 ms
    index.html:1 Deferred long-running timer task(s) to improve scrolling smoothness. See crbug.com/574343.

    I also faced the same issue on another app i build which uses the cordova geolocation plugin. The geolocation plugin works on chrome browser but on the phone it doesnt and get the same messages when i call the getPosition function.

    Could you please help me on this issue?

    Thank you

  • Andrew S

    I have successfully built an app around this method however it is unclear how successful I actually was as it works inside of ionic lab but not when I do ionic cordova run android. Here it only displays a blank a page

  • Francisco Vieira

    This is not working for Ionic v3 with cordova-plugin-googlemaps 2.0.0-beta2-20170725-1201, the map is always blank.
    Would you have an example of how to do for Ionic v3 and the above plugin?

  • sam

    Hi everyone!!
    I have this error on running serve

    Typescript Error
    Cannot find name ‘addInfoWindow’.
    E:/Devoir & Projets/Ionic/Maps/src/pages/home/home.ts
    addInfoWindow(marker, content){

    Typescript Error
    Cannot find name ‘marker’.
    E:/Devoir & Projets/Ionic/Maps/src/pages/home/home.ts
    addInfoWindow(marker, content){

    Typescript Error
    Cannot find name ‘content’.
    E:/Devoir & Projets/Ionic/Maps/src/pages/home/home.ts
    addInfoWindow(marker, content){

    Typescript Error
    Cannot find name ‘content’.
    E:/Devoir & Projets/Ionic/Maps/src/pages/home/home.ts
    let infoWindow = new google.maps.InfoWindow({
    content: content
    });
    Typescript Error
    Cannot find name ‘marker’.
    E:/Devoir & Projets/Ionic/Maps/src/pages/home/home.ts
    google.maps.event.addListener(marker, ‘click’, () => {
    infoWindow.open(this.map, marker);
    Typescript Error
    Cannot find name ‘marker’.
    E:/Devoir & Projets/Ionic/Maps/src/pages/home/home.ts
    google.maps.event.addListener(marker, ‘click’, () => {
    infoWindow.open(this.map, marker);
    });

  • Dinan Rangga M

    How about add marker in automatically? So, it’s not depending on we click that button to add a marker..

    What should I do? Changing ‘click’?

  • EsimioJ

    Hi there, very intersting post
    i had a problem on point 2 with ApplicationInitStatus:
    Runtime Error No provider for ApplicationInitStatus!

    i’ve found that BrowserModule is missing,you need to import browser module in app.module.ts

    import { BrowserModule } from ‘@angular//platform-browser’;
    import { HttpModule } from ‘@angular/http’;

    imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp)
    ],

  • Marcelo

    Hi all!
    Anyone knows how to set a navigation inside a google marker? I want to set a button (href) like “know more” and sent the user to an existing page.

    Thank you in advance.

  • omarz

    Could anyone please tell me how to add fixed marker on the center of the map(my location) ? Thanks

  • Mihai Miulescu

    on device i am getting this error:

    Uncaught in promise
    can’t find variable: google

  • Sharanagouda K

    TypeError: Cannot read property ‘nativeElement’ of undefined
    TypeError: Cannot read property ‘nativeElement’ of undefined
    at search.ts:100 any solution

  • benjamin

    nice tutorial. do you have a tutorial that gives shows directions on a map from one place to the other?