Note: This post is for Ionic 2 or 3. If you are working with Ionic 1 check Add Google Maps, Places, and Geolocation to an Ionic App.

Introduction

In this tutorial we are going to cover how to implement Google maps inside an ionic 2+ app, using the Google Maps JavaScript SDK.


We merged three of the most common cases around location based apps Maps, Geolocation and Places into one functional and coherent/comprehensive ionic app.

Google Maps and ionic mobile 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’s a ton of awesome apps out there that uses 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’s a ton 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 place suggestions, and then use the nearby search endpoint to find restaurants around your desired location.


If you are looking for a more complete example you should check Ion2FullApp ELITE.


Set Up

  • You need to get an API key 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>
  • Install Geolocation Plugin in order to access the user location

    $ ionic cordova plugin add cordova-plugin-geolocation

    $ npm install --save @ionic-native/geolocation

Step 1: Show me a map!

Let’s start with the basics. We are going to initialize the map in a random place, using latitude and longitude coordinates, and setting a defoult zoom.

The map

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 at 100%, otherwise the map will not show:

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

Then in the component we initialize the map in our 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.


Step 2: Google Places Autocomplete

Let’s dig deeper, and add Google Places searching and autocomplete functionalities.

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

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


Step 3: Select a place and show a Pin

In step 2 we learned how to search for a place, but what happens when we select one?

Location

The code belows 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 contructor. 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 = [];

Step 3: Geolocation

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

Nearby Places

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

Next Steps

If you are looking for a more complete and UI/UX polished example you should check Ion2FullApp PRO which includes a complete example about maps.

Now that you’ve learned how to handle google maps in an Ionic App, you can focus on:

Did you know we also sell beautiful ionic templates and components which you may find super useful because they save you hours of development, time and effort, while giving your projects a great design from scratch?

Save weeks of development and design time by using any of our Ionic Templates!