This tutorial covers how to add markers on a Google map in an Ionic 2 app. We’ll continue where we left of the last with a Google map that is displayed in our app. If you haven’t already got that take a look at that tutorial first.
1. Markers JSON
To keep it simple we’ll store the marker information in a json file. Add a file called markers.json in the folder src/assets/data/ (create the folder data since it is not created by default).
The data we need at this point for a marker is, latitude, longitude and name. If you need help to find the latitude and longitude for your markers you can use maapcoordinates.net. My markers.json looks like this:
2. Loading JSON in Ionic 2 and Angular 2
To load our .JSON file we’ll be using angular http and something called an Observable which we’ll map with rxjs/add/operator/map. You can read more about these classes in the Http class documentation of Angular 2
Start by importing these into src/pages/home/home.ts
Then we also need to add Http to our constructor:
Now create a method called getMarkers in home.ts. In that method we’ll load the json file:
We are subscribing to an observable to get the markers. And in the subscribe method we will use the marker data to display them on the map.
3. Displaying markers on a Google map
Create a method called addMarkersToMap() in home.ts. In that method the markers will be looped through and added to the map.
Now we need to call this method from the subscribe callback of getMarkers():
That is all that is needed to display a marker on a Google map in Ionic 2 with Angular 2.