DEV Community

Cover image for How to use Geolocation, Geocoding and Reverse Geocoding in Ionic 4
Umang Darji for Enappd

Posted on • Originally published at enappd.com

How to use Geolocation, Geocoding and Reverse Geocoding in Ionic 4


In this post, you will learn how to implement Geolocation in Ionic 4 apps using Ionic Native Plugins. We will also learn how to Convert Geocode in Location address (Reverse Geocoding) and Location Address into Geocode(Geocoding) in a simple Ionic 4 app and test.

Complete source code of this tutorial is available in the GeoCoding In IONIC 4 app

What is Ionic 4?

You probably already know about Ionic, but I’m putting it here just for the sake of beginners. Ionic is a complete open-source SDK for hybrid mobile app development. Ionic provides tools and services for developing hybrid mobile apps using Web technologies like CSS, HTML5, and Sass. Apps can be built with these Web technologies and then distributed through native app stores to be installed on devices.

In other words — If you create native apps in Android, you code in Java. If you create native apps in iOS, you code in Obj-C or Swift. Both of these are powerful, but complex languages. With Cordova (and Ionic) you can write a single piece of code for your app that can run on both iOS and Android (and windows!), that too with the simplicity of HTML, CSS, and JS.

What is Geolocation?

The most famous and familiar location feature — Geolocation is the ability to track a device’s whereabouts using GPS, cell phone towers, WiFi access points or a combination of these. Since devices are used by individuals, geolocation uses positioning systems to track an individual’s whereabouts down to latitude and longitude coordinates, or more practically, a physical address. Both mobile and desktop devices can use geolocation.
Geolocation can be used to determine time zone and exact positioning coordinates, such as for tracking wildlife or cargo shipments.

Some famous apps using Geolocation are

  • Uber / Lyft — Cab booking
  • Google Maps (of course) — Map services
  • Swiggy / Zomato — Food delivery
  • Fitbit — Fitness app
  • Instagram / Facebook — For tagging photos

What is Geocoding and Reverse geocoding?

Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate. 
Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address. The amount of detail in a reverse geocoded location description may vary, for example, one might contain the full street address of the closest building, while another might contain only a city name and postal code.

Post structure

We will go in a step-by-step manner to explore the anonymous login feature of Firebase. This is my break-down of the blog

STEPS

  1. Create a simple Ionic 4 app
  2. Install Plugins for Geocoding and Geolocation and get User Location
  3. Get User Current Location (Geocoding)
  4. Convert User Geolocation into an address (Reverse Geocoding)
  5. Convert User Entered Address into Geocode (Geocoding)

We have three major objectives

  1. Get User Current Location which we will get in latitude and longitude (Geolocation)
  2. Convert that latitude and longitude in Street Address (Reverse Geocoding)
  3. And again convert Street address entered by the user into latitude and longitude (Geocoding)

Let’s dive right in!


Woah! where did he dive in 😛

Step1 — Create a simple Ionic 4 app

I have covered this topic in detail in this blog.

In short, the steps you need to take here are

  • Make sure you have node installed in the system (V10.0.0 at the time of this blog post)
  • Install ionic cli using npm
  • Create an Ionic app using ionic start

You can create a blank starter for the sake of this tutorial. On running ionic start blank , node modules will be installed. Once the installation is done, run your app on browser using

$ ionic serve

Step2 — Install Plugins for Geocoding and Geolocation and get User Location

Geolocation

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 API is based on the W3C Geolocation API Specification, and only executes on devices that don’t already provide an implementation.

For iOS you have to add this configuration to your 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>

Installation

ionic cordova plugin add cordova-plugin-geolocation
npm install @ionic-native/geolocation

Geocoding

This plugin Used for Converting street address in Geocode and vice versa

Installation

ionic cordova plugin add cordova-plugin-nativegeocoder
npm install @ionic-native/native-geocoder

Step — 3 Get User Current Location (Geocoding)

Using this plugin The first step you will need to do is Add this plugin to your app’s module

Import this plugin like this

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

and add this to Providers of your app Like this

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

So after Adding Your app.module.ts look like this

Now time to import this plugin in your home.ts in which we are going to take user current location

So for using this plugin in our home.ts first, we will import the plugin like this

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

and eject it in our Constructor (Dependency injection) like this

constructor(private geolocation: Geolocation) {}

And use this code for getting user location

this.geolocation.getCurrentPosition().then((resp) => {
// resp.coords.latitude
// resp.coords.longitude
}).catch((error) => {
console.log('Error getting location', error);
});

If you want a continuous tracking of user location, use can you this

let watch = this.geolocation.watchPosition();
watch.subscribe((data) => {
// data can be a set of coordinates, or an error (if an error occurred).
// data.coords.latitude
// data.coords.longitude
});

So this function will give you user Current Location latitude and longitude

After adding this code your home.ts will something look like this

Step — 4: Convert User Geolocation into an address (Reverse Geocoding)

In this step we will use Native Geocoder Plugin

Using this plugin The first step you will need to do is Add this plugin to your app’s module

Import this plugin like this

import { NativeGeocoder, NativeGeocoderOptions } from '@ionic-native/native-geocoder/ngx';

and add this to Providers of your app Like this

@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
StatusBar,
Geolocation,
NativeGeocoder,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})

So after Adding Your app.module.ts look like this

Now add this plugin into your home.ts and use like this

So for using this plugin in our home.ts first, we will import the plugin like this

import { NativeGeocoder, NativeGeocoderOptions, NativeGeocoderResult } from '@ionic-native/native-geocoder/ngx';

and eject it in our Constructor (Dependency injection) like this

constructor(private nativeGeocoder: NativeGeocoder) {}

And use this code to Convert Your lat-long into the street address

reverseGeocode(lat, lng) {
if (this.platform.is('cordova')) {
let options: NativeGeocoderOptions = {
useLocale: true,
maxResults: 5
};
this.nativeGeocoder.reverseGeocode(lat, lng, options)
.then((result: NativeGeocoderResult[]) => this.userLocationFromLatLng = result[0])
.catch((error: any) => console.log(error));
} else {
this.getGeoLocation(lat, lng, 'reverseGeocode');
}
}
async getGeoLocation(lat: number, lng: number, type?) {
if (navigator.geolocation) {
let geocoder = await new google.maps.Geocoder();
let latlng = await new google.maps.LatLng(lat, lng);
let request = { latLng: latlng };
await geocoder.geocode(request, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
let result = results[0];
this.zone.run(() => {
if (result != null) {
this.userCity = result.formatted_address;
if (type === 'reverseGeocode') {
this.latLngResult = result.formatted_address;
}
}
})
}
});
}
}

In this function, we will cover two cases. Actually, Cordova plugins used for Cordova devices only So in case of PWA it will give an error to us. In the case of PWA, we will use Google Geocode Feature

So after adding this code in OUR home.ts our home.ts will something look like this

Step — 5: Convert User Entered Address into Geocode (Geocoding)

This step is the opposite of the previous step. And this step we use the same plugin we use in the previous step.

Code for Reverse Geocoding

if (this.platform.is('cordova')) {
let options: NativeGeocoderOptions = {
useLocale: true,
maxResults: 5
};
this.nativeGeocoder.forwardGeocode(address, options)
.then((result: NativeGeocoderResult[]) => {
this.zone.run(() => {
this.lat = result[0].latitude;
this.lng = result[0].longitude;
})
})
.catch((error: any) => console.log(error));
} else {
let geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
this.zone.run(() => {
this.lat = results[0].geometry.location.lat();
this.lng = results[0].geometry.location.lng();
})
} else {
alert('Error - ' + results + ' & Status - ' + status)
}
});
}

After adding This code you home.ts something look like this

Conclusion

In this blog, we learned how to implement Geolocation Ionic 4 apps using Ionic Native Plugins. We also learnt how to Convert Geocode in Location address(Reverse Geocoding) and Location Address into Geocode(Geocoding) in a simple Ionic 4 app and test.

Complete source code of this tutorial is available in the GeoCoding In IONIC 4 app

Next Steps

Now that you have learnt the implementation of Firebase anonymous login in Ionic 4, you can also try

If you need a base to start your next Ionic 4 app, you can make your next awesome app using Ionic 4 Full App

Top comments (0)