×

Ionic Geolocation

In today’s time, the mobile location plays an essential role in the mobile application. The Ionic Cordova geolocation plugin provides information about the location of the device, like as latitude and longitude. The most common sources to get the location information of devices are Global Positioning System (GPS) and location derived from network signals like as IP addresses, Radio Frequency Identification (RFID), GSM/CDMA cell IDs, and Wi-Fi and Bluetooth MAC addresses.

The geolocation API is based upon the specifications of the W3C Geolocation API. It runs only on devices that do not provide an implementation. It supports different platforms such as Android, Browser, iOS, Windows, and Amazon Fire OS.

Nowadays, the most popular mobile applications, like WhatsApp, Twitter, Facebook, and Instagram, use geolocation plugin to share the user’s location. Some apps give the riding, food, E-commerce services based on the geolocation.

In this topic, we are going to discuss the ionic geolocation. Here, you will see step by step all the process of ionic geolocation in the ionic application.

Step 1. Firstly, you create a new project in the ionic application. It also makes sure that you have installed the latest version of the ionic framework.

Step 2. After the installation of the latest version of the ionic framework, you are required to select a blank template from the various templates. After this process, you need to run the following commands to install the Cordova geolocation plugin in the ionic application. 

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

Step 3. After executing these commands, it is required to import the geolocation plugin in the app.module.ts file, as shown below:

App.module.ts

 import { NgModule } from '@angular/core';  
 import { BrowserModule } from '@angular/platform-browser';  
 import { RouteReuseStrategy } from '@angular/router';  
 import { IonicModule, IonicRouteStrategy } from '@ionic/angular';  
 import { SplashScreen } from '@ionic-native/splash-screen/ngx';  
 import { StatusBar } from '@ionic-native/status-bar/ngx';  
 import { AppComponent } from './app.component';  
 import { AppRoutingModule } from './app-routing.module';  
 import { Geolocation } from '@ionic-native/geolocation/ngx';   
 @NgModule({  
   declarations: [AppComponent],  
   entryComponents: [],   
   imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],  
   providers: [  
     StatusBar,  
     SplashScreen,  
     Geolocation,    
     { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }  
   ],  
   bootstrap: [AppComponent]  
 })  
 export class AppModule {}   

Step 4. In this step, you are required to import geolocation plugin in the home.page.ts file. Here, you create a function to find the location of the device, as shown below:

Home.page.ts

import { Component } from '@angular/core';  
 import { Geolocation } from '@ionic-native/geolocation/ngx';  
 import { LoadingController } from '@ionic/angular';  
 import { AlertController } from '@ionic/angular';  
 @Component({  
   selector: 'app-home',  
   templateUrl: 'home.page.html',   
       message: 'Please wait.....',  
       });  
     await loading.present();  
     this.geolocation.getCurrentPosition({maximumAge: 1500, timeout: 6000, enableHighAccuracy: true }).then((resp) => {  
       // resp.coords.latitude  
       // resp.coords.longitude  
       loading.dismiss();  
       this.lati = resp.coords.latitude;  
       this.longi = resp.coords.longitude;  
       }, er => {  
         // alert("error getting location")  
         loading.dismiss();   
         this.showLoader('Can not retrieve Location');  
       }).catch((error) => {  
       // alert('Error getting location'+JSON.stringify(error));   
       loading.dismiss();  
       this.showLoader('Error getting location - ' + JSON.stringify(error));  
       });  
   }  
  async showLoader(msg) {  
     const alert = await this.alertController.create({   
       message: msg,  
       buttons: ['OK']  
     });  
     await alert.present();  
   }  
 }   

Step 5. In this step, you write the code in the home.page.html file and also create a button to get the location of device, as shown below:

Home.page.html

<ion-header>  
   <ion-toolbar color="success">  
     <ion-title>Ionic Geolocation Example</ion-title>  
   </ion-toolbar>   
 </ion-header>  
 <ion-content class="padding">  
   <ion-button (click)="getCurrentLocation()" expand="block">Search Location</ion-button>  
   <ion-list>  
     <ion-list-header>  
       <ion-label>Location Details</ion-label>  
     </ion-list-header>  
     <ion-item>   
       <ion-label>Longitude</ion-label>  
       <ion-badge>{{longi}}</ion-badge>  
     </ion-item>  
     <ion-item>  
       <ion-label>Latitude</ion-label>  
       <ion-badge>{{lati}}</ion-badge>  
     </ion-item>  
   </ion-list>   
 </ion-content>   

Step 6. In this step, you can use your android device to run the app. Before testing the app, you required to add the platform to the app. The following command helps to install the platform with android, as shown below:

$ ionic cordova platform add android
 $ ionic cordova run android –aot 

Output: After successful execution of the code, you will get the following output:

Ionic Geolocation

When you click on the Search Location button, it shows the latitude and longitude information of the location, as shown below:

Ionic Geolocation

Related Topics

Ionic Colors

Ionic Colors Before we start with the actual elements available in the Ionic frame, let's understand a little bit how Ionic uses colors for different elements. Ionic Color Classes Ionic framework is a set of nine predefined...

3 minutes read.

Ionic Loading

The ionic loader is an overlay that can be used to indicate activity, the user interaction while blocking. The ionic loader shows on the top of the app content, and it can...

5 minutes read.

Ionic Buttons

Ionic Buttons There are different types of buttons in the Ionic framework. These buttons are subtly animated, enhancing the user experience when using the application. Buttons are a fundamental way of interacting and navigating...

4 minutes read.

Ionic Radio

Ionic Radio The radio button is the type of input component that has a Boolean value. The Ionic radio button has a different pattern on every platform, as well as other Ionic components....

2 minutes read.

Features of Ionic Framework

The Ionic Framework is based on the AngularJS framework that permits a programmer to use a combination of many other programming languages, like HTML5, CSS, and JavaScript. Some of the...

4 minutes read.

Ionic Tabs

The ionic tabs mostly used for mobile navigation. It means that tabs are placed at the top of the display on android devices, while at the bottom on IOS. It does not provide...

2 minutes read.

Ionic Range

The Range slider lets users choose from a range of values by moving the slider knob. You can accept two knobs, but by default, one-knob controls the range value. Range labels You can put down on...

2 minutes read.

Ionic Navigation and Routing

The latest version (ionic 4) of the ionic framework, no longer limited to the angular. In Ionic 4, you can create an ionic project in different front-end frameworks such as Vue.js, React.js, and...

6 minutes read.

Ionic Segment

A segment is a collection of buttons, sometimes which are known as segmented controls. The segment buttons are displayed at horizontal rows. These segment buttons can be shown in a toolbar or the...

2 minutes read.

Ionic Toggle

The toggle is the same as the HTML checkbox entry, but it looks different and easier to use on a touchscreen device. It is an input component that holds the boolean value. Toggle...

2 minutes read.

Ionic List

Ionic List The ionic list is created of several rows of items that can contain text, buttons, thumbnails, keys, icons, and more. Lists are one of the essential components in any web or...

4 minutes read.

Ionic vs PhoneGap

Ionic Vs PhoneGap Ionic and PhoneGap are both used to develop the mobile application. Both Frameworks are used in large enterprises by the developers. Here, we are going to compare the important differences between ionic...

3 minutes read.

Ionic Date Time

Ionic Date Time The DateTime component is used to display an interface that makes it simple for users to select dates and times. Tapping on <ion-datetime> will display a slider up from the...

4 minutes read.

Ionic Checkbox

Ionic Checkbox Ionic Checkbox is nearly the same as a toggle. It can be placed in an ionic element or used as a separate checkbox. It is designed differently for every platform, such...

2 minutes read.

Ionic Input

Ionic Input Inputs are necessary to collect and process user inputs securely. To be easy for users to communicate, they must follow the process and communication guidelines for each platform. It is a...

3 minutes read.

Ionic progress bar

The ionic progress bar element is a horizontal progress bar used to visualize the progression of operation and activity. You can use the <ion-progress-bar> component to create a progress bar in the ionic...

4 minutes read.

Ionic Alert

Ionic Alert An Alert is a dialog box that presents the users with important information, or it stores the data from the user by using the inputs. Alerts are a great way to provide...

5 minutes read.

Ionic vs Apache Cordova

Ionic Vs Apache Cordova Ionic and Cordova are two popular technology going on in the market for mobile application development. The combination of these two technologies creates a development platform that is known as...

3 minutes read.

Ionic Reorder

The Ionic offers the <ion-reorder> component to reordering features. Ionic reorder component adds the Drag and Drop feature to list items, in which the user can change the order of the items. Reorder...

3 minutes read.

Ionic Select

The Ion Selection component is similar to the HTML <select> element. However, the Ionic Selection component makes it easy for users to categorize and choose the preferred option or other options. You must...

3 minutes read.