• abhinav185

Simplest Way to implement Google maps in Ionic 5

Google map implementation to make useful apps in ionic framework.

Step 1: Create a new ionic project using ionic start myApp blank and select angular framework from drop option as in below image. After project is created go to project directory using cd myApp.

Step 2: Install Geolocation plugin by and dependencies by running following command.

Step 3: Import Geolocation plugin in app.module.ts in following manner and add it to @NgModule providers array. Check below image.

import { Geolocation } from '@ionic-native/geolocation/ngx';

 declarations: [AppComponent],
 entryComponents: [],
 imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
 providers: [
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
 bootstrap: [AppComponent]

Ionic native Geolocation gives coordinates of user.

Step 4: Similarly import Geolocation plugin in in following manner and add it to constructor(). Add two variables latitude and longitude to store values of respective coordinates.

Step 5: Lets start Integrating google maps for your app now add <script> tag for google maps in your index.html file in this manner.

<script type="text/javascript" src=""></script>

Your index.html will look like above.

Step 6: Next, declare a new const variable just below your imports for google map script and another variable map; similar to latitude and longitude refer step 4 to refer in your file. Also add a new function testmap() to initialize map functionality.

declare const google;
testmap() {
 var myLatlng = new google.maps.LatLng(this.latitude,this.longitude);
 var mapOptions = {
 zoom: 12,
 center: myLatlng,
 mapTypeControl: false,
 scaleControl: false,
 zoomControl: false,
 streetViewControl: false,
 rotateControl: false,
 fullscreenControl: false,
 styles: [{
 stylers: [{
 saturation: -100
     } = new google.maps.Map(document.getElementById("map"), mapOptions);
 //Add User Location Marker To Map
 var marker = new google.maps.Marker({
 position: myLatlng,    
 // To add the marker to the map, call setMap();
 //Map Click Event Listner'click', function() {
 //add functions here

We have also implemented on map click function at the end of testmap(). You can add your logic in there.

Step 7: Next, add following function ionViewDidEnter() below constructor(){} inside this add following code to get geolacation and initialize testmap() function inside it after storing location coordinates so that map brings marker to your location.

 this.geolocation.getCurrentPosition().then((resp) => {
 // resp.coords.latitude
 this.latitude= resp.coords.latitude;
 // resp.coords.longitude

Step 8: Now, add following html code to to show map. Refer below image.

<div style="height: 100%;width: 100%;" id="map"></div>

Step 8: You are done! Save all the files edited and ionic serve

38 views0 comments

Recent Posts

See All