Javatpoint Logo
Javatpoint Logo

Ionic Geolocation

Today, location plays a vital role in mobile applications. The geolocation plugin gives information about the device locations, such as latitude and longitude. Some of the common sources to find the location information are GPS (Global Positioning System) and location inferred from network signals, such as IP address, Wi-Fi and Bluetooth MAC addresses, RFID, and GSM/CDMA cell IDs.

The most popular mobile application, such as WhatsApp, Facebook, and Instagram, uses geolocation to share your location instead of explaining the direction. Ola and Uber's app provides riding services based on geolocation.

The geolocation plugin is based on the W3C Geolocation API Specification, which only executes on devices that do not provide an implementation. In this tutorial, we are going step by step to get the current location by using the geolocation plugin.

Step 1: Create a new project. You can learn how to create a project in Ionic 4 from here. You can skip this step if you already had an Ionic project.

Step 2: Next, navigate to the project and install the following geolocation plugin using the below command.

Step 3: Import the geolocation plugin in the app.module.ts file and also include the plugin in the providers as below. It is a mandatory step. If you skip this step, you will find an error like no provider for geolocation. You can understand it from the following code snippet.

Step 4: Open the home.page.ts file and import the geolocation plugin, then create an object reference for the geolocation class by using the constructor. Now, create a function to get the current location. The following code snippet gives you a detailed explanation.

Step 5: After creating a function, open the home.page.html file. In this file, you need to create a button and click event to use the function defined in the home.page.ts file.

Step 6: Now, you need to add the target platform to deploy the app. You can use your phone to run and test the app. For this, you need to install the following command.

If you want to test your app in the browser, run the below command.

Step 7: When you execute the app, you will get the output as below image.

Ionic Geolocation

Now, click on the Get Location button, you will get the current location of your device in the form of latitude and longitude. It can be shown in the below screen.

Ionic Geolocation




Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA