In this Ionic Maps tutorial we are going to explain how to integrate Google maps with Ionic, using the Google Maps JavaScript SDK.

For this tutorial, we merged three of the most common use cases around location based apps Maps, Geolocation and Places into one functional Ionic App.

Google Maps and Ionic apps are a perfect match. By itself, the Google Maps API is an amazing piece of tech, but when you combine it with a device that's meant to be mobile, it opens up an array of possibilities. There are a ton of awesome apps out there that use Google Maps to do all kinds of marvelous things.

Even when you're making an app that doesn't have maps as the core functionality, it can often be quite useful as a supplementary feature as well (by displaying the location of your business on a map, for example).

Maps + Geolocation + Places Autocomplete + Nearby Places

We will use the popular Google Maps API to display and interact with maps. There are a lot of things you can do with the maps API and we will cover some of them in this Ionic tutorial.

We will explore how to apply place recommendations and suggestions using Google Places API, with its up-to-date information about millions of locations.

Combining all these functionalities, we'll be building an app where you will be able to search for places using Google autocomplete and places suggestions and then, use the nearby places search endpoint to find restaurants around your desired location. The following are some screenshots of this demo app.

Ionic Maps Example App
Ionic Maps Example App
Ionic Maps Example App

You need to get a Google Maps API key in order to be able to make requests to the Google Maps API. Once you have your KEY you should add the following script into your index.html.

  <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&v=3.exp&libraries=places">
  </script>

In order to get the information about the device's location, such as latitude and longitude we need to install the Cordova Geolocation Plugin. Run the following commands from your console:

$ ionic cordova plugin add cordova-plugin-geolocation
$ npm install --save @ionic-native/geolocation

Let's start with the basics. We are going to initialize a map in a random place, using latitude and longitude coordinates. To display a map we just add the following div in our html view.

<div id='map'></div>

We need to make sure that the map height is 100%, otherwise the map will not show:

page-map {
  #map {
    height: 100%;
  }
}

Then in the component we initialize the map in your preferred coordinates.

ionViewDidEnter() {
  //Set latitude and longitude of some place
  this.map = new google.maps.Map(document.getElementById('map'), {
    center: { lat: -34.9011, lng: -56.1645 },
    zoom: 15
  });
}

Setting the map full width and height, while removing some controls from the map, makes it look much more clean and simple.

So, with these few lines of code we are able to display a map in a static location.

Ionic Geolocation example

Now let's see how to add Google Places searching and autocomplete functionalities to our Ionic example app.

With the following code we are going to add a search bar where the user can start typing a place and we will show him a list with the Google search recommendations.

<ion-header>
  <ion-toolbar color="primary">
    <ion-searchbar [(ngModel)]="autocomplete.input" (ionInput)="updateSearchResults()" placeholder="Search for a place"></ion-searchbar>
  </ion-toolbar>
</ion-header>

The updateSearchResults() method is triggered everytime the user types something on the searchbar.

We will use a list for the autocomplete suggestions which we named: autocompleteItems, an input which will be the input typed by the user, which we named: autocomplete and an instance of the GoogleAutocomplete service.

So in the constructor we declare them as follow:

this.GoogleAutocomplete = new google.maps.places.AutocompleteService();
this.autocomplete = { input: '' };
this.autocompleteItems = [];

As mentioned before, everytime the searchbar input is updated we will trigger updateSearchResults() method. In this method we will make a request to Google Autocomplete service and ask for Places predictions based on the input typed.

updateSearchResults() {
  if (this.autocomplete.input === '') {
    this.autocompleteItems = [];
    return;
  }
  this.GoogleAutocomplete.getPlacePredictions({ input: this.autocomplete.input },
  (predictions, status) => {
    this.autocompleteItems = [];
    this.zone.run(() => {
      predictions.forEach((prediction) => {
        this.autocompleteItems.push(prediction);
      });
    });
  });
}

Please note that we fill our autocompleteItems list with the results inside a Zone because we want to tell Angular to perform change detection and display the new results quickly. (Try doing it without Zones and you will note the difference). If the word Zones is new for you, you should check this post: Using Zones in Angular for better performance. To display the prediction results we will use a very simple list:

<ion-list [hidden]="autocompleteItems.length === 0">
  <ion-item *ngFor="let item of autocompleteItems" tappable (click)="selectSearchResult(item)">
    {{ item.description }}
  </ion-item>
</ion-list>

So in this section you app should look like this:

Ionic Geolocation example

In the previous step we explained how to search for a place, but what happens when we select one?

The code below shows how to center the map and show a pin or marker on the selected place. As we can see, when we click in a result from the autocomplete list we trigger selectSearchResult(item) method.

selectSearchResult(item) {
  this.clearMarkers();
  this.autocompleteItems = [];

  this.geocoder.geocode({'placeId': item.place_id}, (results, status) => {
    if(status === 'OK' && results[0]){
      let position = {
          lat: results[0].geometry.location.lat,
          lng: results[0].geometry.location.lng
      };
      let marker = new google.maps.Marker({
        position: results[0].geometry.location,
        map: this.map,
      });
      this.markers.push(marker);
      this.map.setCenter(results[0].geometry.location);
    }
  })
}

Please note that we have initialized the geocoder and the markers list in the constructor. The Geocoder is an item from the google maps library that let us search by place id and markers list contains the information of the marked (or pinned) places.

this.geocoder = new google.maps.Geocoder;
this.markers = [];
Add a marker to google maps in ionic

In order to access the user current location we are going to use Geolocation Crodova Plugin. You need to install it, as explained in the Set Up section.

Once installed we call getCurrentPosition() method to get the latitude and longitude of our position, and then we create a simple pin/marker and move the camera there.

tryGeolocation() {
  this.clearMarkers();
  this.geolocation.getCurrentPosition().then((resp) => {
    let pos = {
      lat: resp.coords.latitude,
      lng: resp.coords.longitude
    };
    let marker = new google.maps.Marker({
      position: pos,
      map: this.map,
      title: 'I am here!'
    });
    this.markers.push(marker);
    this.map.setCenter(pos);
  }).catch((error) => {
    console.log('Error getting location', error);
  });
}
Ionic maps geolocation
Ionic maps geolocation

To go the extra mile in this tutorial we added another tab with Nearby Restaurants, this means that when the user selects a place in the autocomple list, instead of showing him a map with a pin, we will show a list of the restaurants in a radius of 500 meters.

For this example we only list nearby restaurants but there are lots of different places 'types'. Click here to learn more about Nearby Search Places.

Please note that YOUR_KEY_HERE is you Google API key.

selectSearchResult(item) {
  this.autocompleteItems = [];

  this.geocoder.geocode({'placeId': item.place_id}, (results, status) => {
    if (status === 'OK' && results[0]) {
      this.autocompleteItems = [];
      this.GooglePlaces.nearbySearch({
        location: results[0].geometry.location,
        radius: '500',
        types: ['restaurant'],
        // key: 'YOUR_KEY_HERE'
      }, (near_places) => {
        this.zone.run(() => {
          this.nearbyItems = [];
          for (var i = 0; i < near_places.length; i++) {
            this.nearbyItems.push(near_places[i]);
          }
        });
      })
    }
  })
}
Google maps nearby places

Google Maps and Ionic apps are a perfect match. The Google Maps Platform integrates seamlessly with iOS, Android, and desktop applications to help users discover the world with rich details for over 100 million points of interest.

There are a ton of awesome apps out there using Google Maps to do all kind of customized, agile experiences that bring the real world to their users. Check the Starters below to see how to use Google maps in an Ionic App.

There are lots of things you can do such as enabling users to find specific places using the Places API, or giving them the best way to get from A to Z with high-quality directions and real-time traffic updates using the Routes API.

To integrate Google Maps features into an Ionic app we can use the Google Maps JavaScript API that lets you customize maps with your own content and imagery for display on web pages and mobile devices.

Maps integration is just a tiny step in building a complete mobile app with Ionic. In our blog you can find lots of other tutorials that will guide you in the process of creating your Ionic App.

Did you know that we recently released Ionic 6 Full Starter App - PRO? It's an ionic 5 template that you can use to jump start your Ionic app development and save yourself hundreds of hours of design and development. And, of course, it has Google Maps and Geolocation.

ionic starter app

These are some of my favourite Ionic tutorials. All of them include a free Ionic starter that you can reuse for your own project.