In this Ionic 5 tutorial, we’ll discuss how to add Geolocation functionality to get current location in the form of coordinates like latitude, longitude and accuracy of the device. Also, we’ll add the Geocoder plugin in the application to convert coordinates into a readable physical address.
Fetching location of a device plays a great role in a number of real-world applications around us. In one or the other task, we may need coordinates, for example, to deliver some items, book a cab, check the weather at the current location etc.
Hybrid Application we can easily access native features of a device using Cordova plugin and Native wrappers for Ionic Framework. We’ll create an example Ionic 5 application and implement Geolocation service to get Lattitude, Longitude, Accuracy of location, Speed, Altitude etc of the device. After we have Latitude and Longitude, these can be used to get Addresses available on these coordinates. To fetch address from coordinates of the device, we use Geocoder service.
So, let’s begin …
Also Check: Ionic 4 | Turn on Device GPS in Ionic 4 Application Without Leaving App
Update Ionic CLI
We are going to build an Ionic application in using the latest version of the @ionic/cli
package which is 6.7.0. You can update by running below npm command in the terminal
$ npm install -g @ionic/cli</pre> <h3>Create New Ionic 5 application.</h3> After updating the Ionic CLI, execute below ionic command to create a new Ionic application using Angular framework by adding the <code>--type=angular
option with ablank
template.$ ionic start ionic-geolocation-geocoder-application blank --type=angular</pre> move to the application folder <pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ cd ionic-geolocation-geocoder-application</pre> If you have Visual Studio Code installed, open the product by running the following command <pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ code .</pre> <h3>How to Install Geolocation, Geocoder Cordova and Native Plugins in Ionic App</h3> In this step, we'll install Cordova plugins for Geolocation, Geocoder and then configure to use Native wrappers for Ionic 5 Angular application. <strong>Geolocation</strong> Install Cordova and Ionic Native plugins by running following command in the terminal at the application root <pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ ionic cordova plugin add cordova-plugin-geolocation $ npm install @ionic-native/geolocation</pre> This plugin provides information about the device's location, such as latitude and longitude. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs. This plugin is supported for following OS-based devices: <ul> <li>Android</li> <li>iOS</li> <li>Windows OS Based Apps</li> <li>Browser Application</li> <li>Amazon Fire OS</li> </ul> <p class="intro">If using for iOS, you have to add this configuration to your <code>configuration.xml
file<edit-config file="*-Info.plist" mode="merge" target="NSLocationWhenInUseUsageDescription"> <string>We use your location for full functionality of certain app features.</string> </edit-config>
Native Geocoder
The Native Geocoder plugin provides services to convert a given coordinate into address also it helps in native forward and reverse geocoding. This plugin is supported by Android and iOS devices.
Run the following command to install geocoder plugin for an Ionic application
$ ionic cordova plugin add cordova-plugin-nativegeocoder $ npm install @ionic-native/native-geocoder</pre> <h3>Configure App Module to Import Plugins</h3> Now import above plugins in the app module file to use its services, open the <strong>app.module.ts</strong> file, import the <code>Geolocation
andNativeGeocoder
class them add in theproviders
array// 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'; import { NativeGeocoder } from '@ionic-native/native-geocoder/ngx'; @NgModule({ declarations: [AppComponent], entryComponents: [], imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule], providers: [ StatusBar, SplashScreen, Geolocation, NativeGeocoder, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy } ], bootstrap: [AppComponent] }) export class AppModule { }
Get Device Current Location Coordinates and Address using Geolocation, Geocoder Plugins in Ionic Angular Application
Many popular applications like UBER, Facebook, Zomato, Amazon gets user's device location to personalize and facilitate in a better way. These applications depend on the user location for a number of operations.
In Ionic application, the combination of these Cordova and Native plugins makes it very easy to get user device located in a few lines of code in javascript.
Let's check to get user location and fetch address in the Home Page of our Ionic application.
Open the home.page.ts file, then make the changes shown below
// home.page.ts import { Component } from '@angular/core'; import { Geolocation } from '@ionic-native/geolocation/ngx'; import { NativeGeocoder, NativeGeocoderOptions, NativeGeocoderResult } from '@ionic-native/native-geocoder/ngx'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage { // Readable Address address: string; // Location coordinates latitude: number; longitude: number; accuracy: number; //Geocoder configuration geoencoderOptions: NativeGeocoderOptions = { useLocale: true, maxResults: 5 }; constructor( private geolocation: Geolocation, private nativeGeocoder: NativeGeocoder ) { } //Get current coordinates of device getGeolocation() { this.geolocation.getCurrentPosition().then((resp) => { this.latitude = resp.coords.latitude; this.longitude = resp.coords.longitude; this.accuracy = resp.coords.accuracy; this.getGeoencoder(resp.coords.latitude, resp.coords.longitude); }).catch((error) => { alert('Error getting location' + JSON.stringify(error)); }); } //geocoder method to fetch address from coordinates passed as arguments getGeoencoder(latitude, longitude) { this.nativeGeocoder.reverseGeocode(latitude, longitude, this.geoencoderOptions) .then((result: NativeGeocoderResult[]) => { this.address = this.generateAddress(result[0]); }) .catch((error: any) => { alert('Error getting location' + JSON.stringify(error)); }); } //Return Comma saperated address generateAddress(addressObj) { let obj = []; let address = ""; for (let key in addressObj) { obj.push(addressObj[key]); } obj.reverse(); for (let val in obj) { if (obj[val].length) address += obj[val] + ', '; } return address.slice(0, -2); } } </pre> The <strong><code>getCurrentPosition()
method available in theGeolocation
class fetches the device coordinates including latitude, longitude, accuracy, speed, time and other information. In the customgetGeoencoder()
method we are passing the latitude and longitude which in turn calling thereverseGeocode
method available in theNativeGeocoder
class. We also passed the configuration object of typeNativeGeocoderOptions
to set a number of nearby address based on coordinates supplied. ThereverseGeocode()
method returns a bit non-readable array including address data, which we are passing to a custom methodgenerateAddress()
method, which saved the readable comma separated string in theaddress
variable.
Also, check Geolocation & Geocoder plugins with Javascript API Google Maps in Ionic 5 Application.
In home.page.html, add following HTML<ion-header [translucent]="true"> <ion-toolbar color="secondary"> <ion-title> Cordinates & Address in Ionic App </ion-title> </ion-toolbar> </ion-header> <ion-content [fullscreen]="true" class="ion-padding"> <h4>Geolocation & Gecoder App</h4> <ion-grid> <!-- Latitude --> <ion-row> <ion-col size="4" class="ion-text-center"> Latitue </ion-col> <ion-col> <ion-badge class="ion-text-wrap" color="medium">{{latitude}}</ion-badge> </ion-col> </ion-row> <!-- Longitude --> <ion-row> <ion-col size="4" class="ion-text-center"> longitude </ion-col> <ion-col> <ion-badge class="ion-text-wrap" color="medium">{{longitude}}</ion-badge> </ion-col> </ion-row> <!-- Accuracy --> <ion-row> <ion-col size="4" class="ion-text-center" color="medium"> Accuracy </ion-col> <ion-col> <ion-badge class="ion-text-wrap" color="medium">{{accuracy}}</ion-badge> </ion-col> </ion-row> <!-- Address --> <ion-row> <ion-col size="4" class="ion-text-center"> Address </ion-col> <ion-col> <ion-badge class="ion-text-wrap" color="medium">{{address}}</ion-badge> </ion-col> </ion-row> </ion-grid> <ion-button (click)="getGeolocation()" color="success" expand="full">Get Location</ion-button> </ion-content></pre> In the HTML template, we used <code>ion-grip
component withion-badge
to display the coordinates and address in an aligned format. The button is calling the customgetGeolocation()
method we defined in the class. We are done with the implementation let's check how to run the application in the real device asNativeGeocoder
service only works in the presence of Cordova.Add OS Platform for Ionic Application
To create a build of the Ionic application to install in a real device, we need to add a target platform in our Ionic application. Run following commands to add a platform for Ionic 5 application# For Android $ ionic cordova platform add android # For iOS $ ionic cordova platform add ios # For Windows $ ionic cordova platform add windows
Build Ionic 5 Application
After adding the required platforms, we need to create a build by running following command for each platform.
# Android Build $ ionic cordova build android # iOS Build $ ionic cordova build ios # Windows Build $ ionic cordova build windows
Test Run Your App on Device
You can move you build file from above command to your device or run the following command after connecting your Device with computer via USB cable.
# Run Android App $ ionic cordova run android -l # Run iOS App $ ionic cordova run ios -l # Run Windows App $ ionic cordova run windows -l
Conclusion: That's it now we have an Ionic 5 application with Geolocation and Native Geocoder plugins installed. We can now fetch the user's device location coordinates and convert them into readable Address using Geocoder service. Also, we discussed how to add a platform then build a source file to test it in a real device.
Happy coding 🙂
Category: Ionic Framework
Leave a Reply