A Complete guide on adding google maps in your ionic application[2022 updated]

 A Complete Guide to Add Google Maps API to your Ionic Application. [lines, circles, polygon, markers] everything covered.

Google Maps API with Ionic v5

I have searched about this topic alot but didn’t find anything detailed content as I was working on a project. I needed this thing and went alot of trouble that’s why I decided to write a complete post adding each and every topic of Google Maps API. 
Adding Markers to maps, Shapes, and showing some details. How to work with places API, distance matrix API everything we will be talking about.
NOTE:- [Places API, Distance matrix API] require a payment method added to get API key.
So let’s get Started…

#1] Get API key from Google console

Visit https://console.cloud.google.com/ create a account and enable maps Javascript SDK from the dashboard. Once done get the API key we will need it load maps, Add markers and show shapes on it.

#2] Add URL to your ionic application

<script async src=“https://maps.googleapis.com/maps/api/js?key=”YOUR-API-KEY-HERE”></script>
Copy and paste this url inside your ionic application index.html inside head tag.

#3] Install Plugin

Now, to get our location we need to install geolocation plugin
 
$ npm install cordova-plugin-geolocation 
$ npm install @awesome-cordova-plugins/geolocation
$ ionic cap sync

Add the plugin to the app.module.ts file 

import { Geolocation } from ‘@awesome-cordova-plugins/geolocation/ngx’;

Add Geolocation to the providers array.

#4] Get Current Location

open the ionic project in the browser using ionic serve.
If you error saying
(node:10438) UnhandledPromiseRejectionWarning: Error: The target entry-point “@awesome-cordova-plugins/geolocation” has missing dependencies:
[ng]  – @awesome-cordova-plugins/core
[ng] 
Just install the library and everything will be fine
npm install –save @awesome-cordova-plugins/core

Now, inside home.page.ts create a function to get user position, Add Geolocation in the constructor and import it. Call the below function inside constructor. and open developer tools to see the logs. If everything worked correctly you should see location details.
getUserPosition(){
this.geo.getCurrentPosition().then((location) => {
console.log(location);
}).catch((error) => {
console.log(error);
})
}
This is what we get in the logs.
We get the latitude and longitude of your current position. We will use this to load a map inside our home.page.html.
  1. GeolocationPosition {coords: GeolocationCoordinates, timestamp: 1642870104703}
    1. coordsGeolocationCoordinates
      1. accuracy62.487
      2. altitudenull
      3. altitudeAccuracynull
      4. headingnull
      5. latitude18.4434585
      6. longitude73.8252679
      7. speednull
    2. timestamp1642870104703

#5] Load Google Maps

<ion-content [fullscreen]=“true”>
<div #map id=“map” style=height: 70%;></div>
</ion-content>
Add the div inside ion-content with id=”map” so that we can get it’s reference in our home.page.ts file.
In home.page.ts
below import statements add 
declare var google: any;

@ViewChild(‘map’) mapView: ElementRef;

After this create a function addMap(latitude, longitude) which will take two arguments lat and long and based on that will a map.
addMap(lat, lon){
let latlng = new google.maps.LatLng(lat, lon);

let mapOptions = {
center: latlng,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}

this.map = new google.maps.Map(this.mapView.nativeElement,mapOptions);
this.addMarker(latlng);

}
Also this two function 
getOnDragEvent -> get the marker position when dragged by the user and logs the details
addMarker -> Adds a red marker at your position.
getOnDragEvent(vMarker){
google.maps.event.addListener(vMarker, ‘dragend’,
(evt) =>
{
console.log(evt);

})

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

//icon: ”
});

this.getOnDragEvent(marker);

let content =“<p>Your Current Location</p>”;

}

Save your project and you will see Google Maps has been loaded in your home page.

#6] Draw a Line

Polygon class is used to draw lines on the maps. It takes two things the starting point and the end point. Or you can pass an array of objects containing latitude and longitudes.
addMap(lat, lon){
let latlng = new google.maps.LatLng(lat, lon);

let mapOptions = {
center: {lat: 25.774, lng: 80.19},
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}

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

let cordsTraingle = [
{ lat: 25.774, lng: 80.19 },
{ lat: 18.466, lng: 66.118 },
]
const line = new google.maps.Polygon({
paths: cordsTraingle,
strokeColor: “#FF0000”,
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: “#FF0000”,
fillOpacity: 0.35,
});
line.setMap(this.map);

this.addMarker(latlng);

}
Now, you can see the line drawn like this

#7] Add a Circle 

To add a circle we use the Circle class and provide the center of the circle with it’s radius. And the circle is drawn.
addMap(lat, lon){
let latlng = new google.maps.LatLng(lat, lon);

let mapOptions = {
center: latlng,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}

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

// Add the circle for this city to the map.
let cityCircle = new google.maps.Circle({
strokeColor: “#05a074”,
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: “#05a074”,
fillOpacity: 0.03,
map: this.map,
center: { lat: lat, lng: lon },
radius: 670 * 10,
});
this.addMarker(cityCircle);

}

Hope you guys liked and enjoyed reading this post. I will keep sharing such informative posts with you.
If you like reading please bookmark and share this post. It keeps me motivated to write more cool stuff you.
THANK YOU😇

1 thought on “A Complete guide on adding google maps in your ionic application[2022 updated]”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top