Get location android studio

How to get user location in Android

Many apps in Android uses user’s locations be it for ordering cabs or delivering food and items. Here, a simple android app that would return the user’s latitude and longitude is made. Once the latitude and longitude are known, the exact location on Google Maps can be seen using the following query: https://www.google.com/maps/search/?api=1&query=,

Note: The app will run completely fine on an actual device but might show an error on an emulator. So, please try to run it on an actual device!

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.

Approach

Step 1. Acquiring Permissions

Since using the user’s permission is a matter concerned with high privacy, first acquire the user’s permission to use their location by requesting them for it. From Android 6.0(Marshmallow), the concept of run-time permissions was rolled in and so the same will be used for getting permission. Any of the following permissions can be used for this:

ACCESS_COARSE_LOCATION: It provides location accuracy within a city block.

ACCESS_FINE_LOCATION: It provides a more accurate location. To do this, it needs to do some heavy lifting so it’s recommended to use this only when we need an accurate location.

In case the app needs to access the user’s location while the app is running in the background, we need to add the following permission along with the above ones:

We need to add all these permissions in the AndroidManifest.xml. To access this file, select your project view as Android and click on:

app->manifests->AndroidManifest.xml.

After adding all the permissions, this is how the AndroidManifest.xml file looks like:

Also, as Google’s PlayServices will be used to access the device’s location, add it in dependencies, in the Build.Gradle (app) file:

Step 2. Designing the layout
As the app is fairly simple, it would contain only the MainActivity and hence a single main layout. In the layout, add an ImageView and two TextViews which would be displaying the user’s latitude and longitude. The latitude and longitude which would be displayed will be returned from the logic of our MainActivity which will be discussed next. Here’s how activity_main.xml looks like:

Output:

Step 3. Writing the logic

  • To work on the main logic of our app, we will follow the following key points:
    • Check if the permissions we request are enabled.
    • Else request the permissions.
    • If permissions are accepted and the location is enabled, get the last location of the user.
  • In order to get the last location of the user, make use of the Java public class FusedLocationProviderClient. It is actually a location service that combines GPS location and network location to achieve a balance between battery consumption and accuracy. GPS location is used to provide accuracy and network location is used to get location when the user is indoors.
  • In conjunction with FusedLocationProviderClient, LocationRequest public class is used to get the last known location. On this LocationRequest object, set a variety of methods such as set the priority of how accurate the location to be or in how many intervals, request of the location is to be made.
  • If very high accuracy is required, use PRIORITY_HIGH_ACCURACY as an argument to the setPriority(int) method. For a city level accuracy(low accuracy), use PRIORITY_LOW_POWER.
  • Once the LocationRequest object is ready, set it on the FusedLocationProviderClient object to get the final location.

Источник

How to get current latitude and longitude in android example

This Android tutorial is to help learn How to get the current latitude and longitude in the Android platform. Knowing the current location in an android mobile will pave the way for developing many innovative Android apps to solve people’s daily problems. Developing the location-aware application in android needs location providers.

Checkout my other useful post:

Table of Contents

Types of location providers:

GPS Location Provider

Network Location Provider

Any one of the above providers is enough to get the current location of the user or user’s device. But, it is recommended to use both providers as they both have different advantages. Because the GPS provider will take the time to get the location to the indoor area. And, the Network Location Provider will not get location when the network connectivity is poor.

Network Location Provider vs GPS Location Provider

  • Network Location provider is comparatively faster than the GPS provider in providing the location coordinates.
  • GPS provider may be very very slow in indoor locations and will drain the mobile battery.
  • The network location provider depends on the cell tower and will return to our nearest tower location.
  • GPS location provider will give our location accurately.
Читайте также:  Bluetooth клавиатура для планшета андроид

Steps to get current latitude and longitude in Android

  • Location permissions for the manifest file for receiving the location update.
  • Create LocationManager instance as a reference to the location service.
  • Request location from LocationManager.
  • Receive location update from LocationListener on change of location.

Location Permissions

To access current location information through location providers, we need to set permissions with the android manifest file.

As higher versions of Android need in-app permission so we will request app permission this way,

ACCESS_COARSE_LOCATION is used when we use network location provider for our Android app.

But, ACCESS_FINE_LOCATION is providing permission for both providers. INTERNET permission is a must for the use of a network provider.

Create LocationManager Instance

For any background Android Service, we need to get a reference for using it. Similarly, location service references will be created using the getSystemService() method. This reference will be added to the newly created LocationManager instance as follows.

Request Current Location From LocationManager

After creating the location service reference, location updates are requested using the requestLocationUpdates() method of LocationManager. For this function, we need to send the type of location provider, number of seconds, distance, and the LocationListener object over which the location to be updated.

Receive Location Update From LocationListener

Receive location update from LocationListener on change of location LocationListener will be notified based on the distance interval specified or the number seconds.

Also, LocationListener having its own callbacks to provide locations based on location/provider changes.

onLocationChanged(Location location) — Called when the location has changed.

onProviderDisabled(String provider) — Called when the provider is disabled by the user.

onProviderEnabled(String provider) — Called when the provider is enabled by the user.

onStatusChanged(String provider, int status, Bundle extras) — This callback will never be invoked on Android Q and above, and providers can be considered as always in the LocationProvider#AVAILABLE state.

Lets see the example for getting current location in android.

Get current location in android example

Using Location Listener

I have created a service that extends locationListener. By extends Location Listener you can receive location updates.

Requesting Location Permission

To get the current latitude and longitude you need a location permission.

Getting NetworkingProvider / GpsProvider

To get the networking / Gps providers, first we need to get location manager.

Once, we get the location manager then we can get the location providers.

check any one of the location provider available to get the location.

Using Network Provider to get location

Once we know that the network provider enabled, Then, you can request the location update from locationLintener using LocationManager.NETWORK_PROVIDER.

In above you can see that, we can also get last known location from the location manager using NETWORK_PROVIDER.

Using GPS provider to get location

Same like Network provider, we can request the location update using LocationManager.GPS_PROVIDER .

Also,we can also get last known location from the location manager using GPS_PROVIDER.

All your location updates received in LocationListener callbacks.

Stop receiving location

To stop receiving location updates in location manager by using removeUpdates.

Entire Android app code is as follows,

GpsTracker.java

MainActivity.java

AndroidManifest.xml

Android Output

Note: If you are running this Android app on the emulator, you need to send the latitude and longitude explicitly for the emulator.

To send the latitude and longitude from your emulator,

  1. Click More Button from your emulator’s layout.

2. Select Location > Then set the Latitude and Longitude values. Then press Send to set the Latitude and Longitude values to the emulator device.

You can download this example in GITHUB.

Conclusion

Thank you for the reading.

I hope, Now you can able to get the current latitude and longitude in your android device. If you have any issues please put them in the comments section.

Источник

Android Get Current Location Programmatically Latitude Longitude

How to get current location in android (latitude and longitude) with GPS is the today’s example.

Along with current location, we will also see how you can get address from current location and how to get latitude and longitude of any particular place or address.

1. Get Current Location In Android

It is necessary to find current location in android studio programmatically when you are developing location-based applications.

Globally, the location of any object is found in terms of the latitude and longitude.

For example, if you want to find restaurants near by you, you need your current gps location latitude and longitude.

With the help of latitude and longitude, you will be able to find location regardless of how far the object is from you.

In current GPS location android example tutorial, you will learn to get current latitude and longitude of Android device.

We will use Google’s FusedLocationAPI for getting current location with latitude and longitude.

Show the output of the tutorial in the below video.

Follow all the below steps carefully to get the current location.

Step 1. Create a new project in Android Studio.

Make a fresh new project in Android Studio. Make sure you have select Empty activity as a Main Activity while creating a new project.

Step 2. Update build.gradle(Module:app) file

Add below source code in build.gradle(Module:app)

We need to use google’s play services to accomplish our task of getting current latitude and longitude.

Above line will import all the necessary classes from google api.

Step 3. Implement necessary interfaces

These interfaces are required.

All the above interfaces are required for using google’s fusedlocation API.

We also need to override necessary methods associated with these interfaces.

Step 4. Declare instances:

Declare Necessary statements as per below source code.

Читайте также:  Как отключить экран гугл андроид

All these instances will help to use location services of the android architecture.

Step 5. Put following in onCreate() method

Update your onCreate() method as per following:

Step 6. Last but not least, put required permissions in AndroidManifest.xml

Below two permissions are must to get desired results.

If you are targeting marshmallow and after versions (targetSdkVersion >=23) then you have to check for run-time permissions.

Now full source code:

AndroidManifest.xml

build.gradle(Module:app)

activity_main.xml

In the above layout file, I have used four TextViews. Two are static which will give you reference about which digit is latitude and which is other.

Other two textview represents the location factors and will be changed frequently.

After implementing interfaces, you need to override all of it’s required methods. Here is the full source code with those methods in MainActivity.java class.

Source snippet for the MainActivity.java file.

Descriptions of the various methods

In above class, there is a method

This method is used to check whether location service is on or off in your phone. If off, then it will pop up one dialog, which will take the user to settings to enable location service.

showAlert()

This method will prompt a dialog if the location settings of the device is off. Title of the dialog will tell user about this. From here, user can turn on the location or can simply ignore it.

startLocationUpdates()

In this method, android will finally use google’s FusedLocation API to fetch the current latitude and longitude of the android device.

onLocationChanged()

Latitude and Longitude are very sensitive factors. It changes constantly every seconds to fetch the exact gps location of the device.

When these two factors have changed their values, this method onLocationChanged() will be called every second.

I have updated the textview values which represents the latitude and longitude in this method.

We will get the values of latitude and longitude in the long variable format because we must consider 7 to 8 decimal digits for the accuracy of the gps location.

If you have any query or questions then use comment section to ask them.

I will be happy to solve your questions as quickly as possible.

2. Get Address From Current Location In Android

Learn about Android Get Current Address Location From Latitude Longitude in this tutorial.

Learn how to get location name from latitude and longitude in android.

In this tutorial, we will get current country, state, city, postal or pin code, zip code and location name from latitude and longitude.

For this purpose, we will use Geocoder and Address classes from android library.

Step 1. Manifest Permissions

First of all, make a fresh new project in the android studio.

Select “Empty activity” as a main activity.

In order to fetch the current location, we need to have some permissions from the user.

Write down the below lines in AndroidManifest.xml file.

We need to ask for runtime permissions in this case because location permission is sensitive in terms of user’s security and privacy.

We will ask it using dexter library in the main activity later.

Step 2. Some Dependencies

In your build.gradle(Module : app) file, add the following two lines

First line is for fetching the classes from google. These classes will help us to get the current location in terms of latitude and longitude of the user.

Second line is for dexter library which will help us to simplify the process of asking runtime location permissions.

Step 3. Main XML file

In your activity_main.xml file, add the following code snippet

Above main XML file includes one Button and several Text views.

When the user will click the button, we will fetch the address from current latitude and longitude.

We will fill the text views with the information like country, city, state, pin code, zip code etc.

Step 4. Main Java Class

Following is the source code for the MainActivity.java class.

Checking the Code

Let us see how the source code of Main Activity will work.

First of all, consider the following lines

With this code, compiler will define objects of various useful classes.

Classes like GoogleApiClient, Location, LocationManager, LocationRequest etc. will help us to get the current latitude and longitude.

Then there are objects of text view and button widgets.

Two double variables latitude and longitude will hold the co ordinates.

Now read the code of the onCreate() method.

First of all, compiler will call requestMultiplePermissions() method.

Code for requestMultiplePermissions() method is as the below

As you can see that we are asking for ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION in this method.

If the user have given all the permissions then compiler will show a toast like “All permissions are granted!”

Otherwise, it will call the openSettingDialog() method.

source code for openSettingDialog() method is as the following

Compiler will show one alert dialog to the user.

It has two buttons. One is Cancel and another is “Take me to settings.”

when the user will call “Take me to settings.” button, compiler will open the app settings, from where user can turn on the permissions.

Now again see the onCreate() method.

After requestMultiplePermissions() method, compiler will call checkLocation() method.

This method will check whether the location service of android device is on or off.

If it is off then, compiler will pop up one alert dialog and will tell user to turn on the location service.

Now some overriden methods are there. For example, onConnected(), onConnectionSuspendend(), onConnectionFailed(), onStart(), onStop() and onLocationChanged().

All these methods are related to getting current location.

Compiler will call onLocationChanged() method every 2 seconds. This method will give us updated latitude and longitudes.

Source code for onLocationChanged() method is as the following

Compiler will store latitude and longitude in global variables.

When the user will click the button, compiler will call setAddress() method.

Читайте также:  Adb android debug bridge run

setAddress() method will get two parameters. One latitude and another will longitude.

We will pass global variables as these parameter, so this method will always get updated current co ordinates.

Code structure for setAddress() method is as the below

In this method, compiler will first create the object of Geocoder class.

Then it will create a list with the objects of Address class.

.getFromLocation() method will give us the address associated with the latitude and longitude.

Result given by .getFromLocation() method will give us full address, city, country, state, pin code and finally we will set these information in various text views.

3. Android Get Latitude And Longitude From Address

Android Get Latitude And Longitude From Address is the today’s main topic.

We will fetch the co ordinates in form of latitude and longitude from the address of the location.

There may be some case where user do not know his/her current location in terms of latitude and longitude but he can write his address.

In such case, you need to fetch the co ordinates from the address given by the user.

This tutorial will guide you how to insert this feature in your android application with easy and simple coding lines.

User will enter the address in the edit box. Our code will get the co ordinates (latitude and longitude) from this address using Address, Geocoder and Message class.

Read Fetched Address

Watch the below video to show how this demo tutorial is working.

Step 1. Geo Coding Class

First of all, make a new class named GeocodingLocation.java

Source code for GeocodingLocation.java is as the following

Above class is primarily using three classes : Geocoder, Address and Message.

Compiler will first start one thread.

Inside this thread, it will create the object of the Geocoder class.

Then it will fetch the latitude and longitude using .getFromLocationName() method.

An object of List class will hold the output given by .getFromLocationName() method. Object of Address class will get output from List class object.

After this, an object of StringBuilder class will fetch co ordinates and than a string variable will finally get latitude and longitude from given address.

Step 2. XML file for main activity

When you create a new project in android studio, system creates two files automatically.

One of them is activity_main.xml.

Copy the below code snippet in activity_main.xml.

There are some UI widgets in the above file.

Two buttons, two text views and one edit text is present.

In the edit text, user can input the address. By default, I have written one address.

Below this edit text, there will be two buttons. One button will erase the text from the edit text when user clicks it.

Other button will fetch the latitude and longitude from the address when it is clicked.

Step 3. Writing Main File

Write down the below source code in MainActivity.java file

Looking Main Class Deeply

Consider the below code

Compiler will create the objects of Button, Text view and Edit text etc. classes.

Now look at the below code

Compiler will execute the above code when the user clicks on the erase button.

It will set the null or empty text on the edit text.

Now read the following code structure

When the user clicks “GET LATITUDE LONGITUDE” button, compiler will run the above code lines.

It will first get the address in the string format from the edit text.

Then it will create the object of the GeocodingLocation class.

Then compiler will user .getAddressFromLocation() method.

.getAddressFromLocation() method will get the address in string format as the first parameter, application context as a second parameter and object of GeocoderHandler() as the last parameter.

Below is the code writings for GeocoderHandler class.

Here, handleMessage() method will get the object of the Message class in it’s first parameter.

Then compiler will get the data from this object using Bundle class.

From this bundle, compiler will get the latitude and longitude in the string format using .getString(“address”) class.

Finally, compiler will set this latitude and longitude in the text view.

106 thoughts on “Android Get Current Location Programmatically Latitude Longitude”

Hello,
Latest version for google play service is “9.4.0”, can I use this version instead of “9.0.2”, which is mentioned on the above blog post?

Yes, you can always use latest version of Google API.

Thank Hardik bro i am developing an app ..i need your help.

what kind of help you need?

Hey!
First off, great tutorial!
Secondly, my questions:
I am new to android, but I am quite good in java. I work in android studio 1.5(do I need to update it?). I wonder if this code can be used as is for broadcasting the location to other devices with the same app, and then somehow plot the coordinates on google maps, such that a nearby person can be notified of the position of another person?

Or do I have to do a lot of tweaks in this code?

You can implement this code on Android Studio 1.5 (No need to update). This code will give you latitude and longitude of your device, for broadcasting these latlong you can send them to server and from server all other devices can get them and then you can show it on google map. So this tutorial will give you only coordinates of your device, for your whole purpose, you have to do lot of tweaks as you guessed.
Thanks 🙂

is it also possible to store this value in SharedPreferences and keeping the mode MODE_WORLD_READABLE so that every one can see it.

i wan to ask, this code can get every current gps location each minute

Thank you very much for amazing tutorial, it’s nice and easy to understand.

Thanks for your words and do share our site with other learners.

Источник

Оцените статью