Ionic Maps Video

Ionic 2: 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

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 peformance.

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 index.html file:

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

NOTE: When building production applications, you should also obtain an API key for your Google Maps integration and supply it as a parameter in the query string (i.e ?key=yourkey)

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) {

  }

  ionViewLoaded(){
    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 centre 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 home.scss file:

.ios, .md {

    home-page {

      .scroll-content {
        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

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

Modify home.ts to reflect the following:

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

declare var google;

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

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

  constructor(public navCtrl: NavController) {

  }

  ionViewLoaded(){
    this.loadMap();
  }

  loadMap(){

    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);
    });

  }

}

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 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 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.

BONUS CONTENT: Download the source code for this application by entering your email address below:

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.

  • 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 [email protected] “../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…

  • 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.

  • 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

  • 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.

  • 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

  • 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

  • Berkhan

    How to get coordinates of an address ?

  • Abhimanyu Kumar
  • Mustafa Aydin

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

    thanks a lot