- Android address from location
- Get Current Location Address Android
- Setup Location API
- Add Location API Library
- Fused Location Provider Location API
- GeoCoder
- Get Current Location Address Example
- Android Manifest
- Activity
- Intent Service
- Activity Layout
- About
- Данные о местоположении
- Примеры кода
- Работа с данными о местоположении
- Доступ к данным о местоположении
- Добавление разрешений в манифест приложения
- Запрос разрешений в среде выполнения
- Kotlin
- Слой «Мое местоположение»
- Kotlin
- Location API сервисов Google Play
- Android Get Address with Street Name, City for Location with Geocoding
- Download the Example Android Application
- Geocoding
- Android Reverse Geocoding Example to find Address
- Step1: Define Permissions
- Step 2: Accessing the Geo Location for Lat and Long
- Step 3: Reverse Geocoding to get Location Address
- Step 4: Android UI
- Key Points to Note for Geocoding
- Example Geo coordinates Latitude and Longitude with respective location address:
- Download the Example Android Application
- Popular Articles
- Comments on «Android Get Address with Street Name, City for Location with Geocoding»
Android address from location
Get Current Location Address Android
November 20, 2017
In your android app, if you want to get the address of device’s current location, you need to use Google play service location API to do that. Google play service location API provides an optimized location API called fused location provider that you can use to get last known location easily by specifying location accuracy and battery power.
In this post, you can learn how to use fused location provider location API to get last location, how to get location updates and how to use GeoCoder get address for the given location.
Setup Location API
To use location API in your project, first you need to create a project in Google developer console, enable Google play services API, generate key, add the key to your project manifest file, add android.permission.ACCESS_FINE_LOCATION permission to manifest file, and add location API library to build.gradle file. For more details, see setting up Google play services API.
Add Location API Library
Add below entry to build.gradle file/
Fused Location Provider Location API
The main class in fused location provider API is FusedLocationProviderClient. You can get FusedLocationProviderClient object by calling getFusedLocationProviderClient method on LocationServices. FusedLocationProviderClient has getLastLocation and requestLocationUpdates methods which can be used to location. Method getLastLocation gives last know location. If you want location updates as device location changes, you need to use requestLocationUpdates.
These methods run on the background not on the main thread, you can use callback handlers and listeners to get data and update UI.
GeoCoder
To get address for the given location, you need to use GeoCoder class. GeoCoder can be used to geocoding and reverse geocoding, geocoding converts street address into longitude and latitude coordinates and reverse-geocoding converts longitude and latitude coordinates into street address.
To get street address of the current location, you need to call getFromLocation method on GeoCoder object passing current location coordinates. To run this call on background thread, we need to use intent service. To receive results from GeoCoder and update UI, you’ll have to define ResultReceiver in the activity.
Get Current Location Address Example
Android Manifest
Add ACCESS_FINE_LOCATION permission and declare intent service.
Activity
Method requestLocationUpdates is called on FusedLocationProviderClient object passing LocationRequest and LocationCallback objects to get location updates. LocationRequest allows you to configure request. You can set location update interval and accuracy of location by calling setInterval and setPriority methods on LocationRequest object.
LocationCallback object’s onLocationResult callback method gets called when location result is available. In this method, once location is available, intent service is started with an intent that contains result receiver object and location.
In the activity, you need to define result receiver by extending ResultReceiver class. You need to override onReceiveResult method that gets called when intent service calls send method on the result receiver object. In onReceiveResult method, the received address data will be displayed in UI.
Intent Service
Intent service calls getFromLocation method on GeoCode to get address for the location retrieved from intent and sends the result to result receiver retrieved from intent.
Activity Layout
About
Android app development tutorials and web app development tutorials with programming examples and code samples.
Источник
Данные о местоположении
В приложениях для мобильных устройств особенно важную роль играют данные о местоположении, применение которых способно обеспечить пользователю дополнительное удобство, где бы он ни находился.
Примеры кода
Хранилище ApiDemos на сайте GitHub содержит пример, который демонстрирует использование данных о местоположении на карте.
Java
- MyLocationDemoActivity: использование слоя «Мое местоположение», включая динамические разрешения.
- LocationSourceDemoActivity: использование собственного источника LocationSource .
- CurrentPlaceDetailsOnMap: определение текущего местоположения устройства Android и отображение сведений об организации или другом объекте, который там находится. Ознакомьтесь с руководством по отображению сведений о месте на карте.
Kotlin
- MyLocationDemoActivity: использование слоя «Мое местоположение», включая динамические разрешения.
- CurrentPlaceDetailsOnMap: определение текущего местоположения устройства Android и отображение сведений об организации или другом объекте, который там находится. Ознакомьтесь с руководством по отображению сведений о месте на карте.
Работа с данными о местоположении
Устройствам Android могут быть доступны данные о текущем местоположении (для их сбора используется комбинация нескольких технологий), о направлении и способе движения, а также о том, покинуло ли устройство геозону, т. е. пересекло ли оно заданную географическую границу. Работать с данными о местоположении можно несколькими способами в зависимости от задач конкретного приложения.
- Слой Мое местоположение представляет собой простой способ отобразить местонахождение устройства на карте. Он не возвращает никаких данных.
- Для всех программных запросов данных о местоположении рекомендуется использовать Location API сервисов Google Play.
- Интерфейс LocationSource позволяет использовать собственный источник данных о местоположении.
Доступ к данным о местоположении
Если приложению требуется доступ к данным о местоположении пользователя, вы должны запросить разрешение, добавив в приложение соответствующие настройки.
Android предлагает два разрешения на использование данных о местоположении: ACCESS_COARSE_LOCATION и ACCESS_FINE_LOCATION . От вашего выбора зависит, насколько точную информацию будет предоставлять API. Вам необходимо запросить только одно из разрешений на использование данных о местоположении Android в зависимости от требуемого уровня точности:
- android.permission.ACCESS_COARSE_LOCATION позволяет использовать точки доступа Wi-Fi и/или мобильные данные, чтобы определять приблизительное местоположение устройства. API предоставляет информацию о местоположении с точностью примерно до городского квартала.
- android.permission.ACCESS_FINE_LOCATION позволяет API максимально точно определять местоположение на основании информации, предоставляемой поставщиками данных о местоположении, включая глобальную систему позиционирования (GPS), сеть Wi-Fi и мобильные данные.
Добавление разрешений в манифест приложения
Добавьте одно из следующих разрешений в качестве дочернего для элемента в манифесте Android. Укажите разрешение для данных о приблизительном местоположении:
Или разрешение для данных о точном местоположении:
Запрос разрешений в среде выполнения
В Android 6.0 (Marshmallow) представлена новая модель работы с разрешениями, которая оптимизирует процесс установки и обновления приложений пользователями. Если ваше приложение предназначено для API уровня 23 или более позднего, вы можете использовать новую модель разрешений.
Если приложение поддерживает новую модель разрешений, а на устройстве используется Android 6.0 (Marshmallow) или более новая версия, пользователю не нужно предоставлять какие-либо разрешения при установке приложения или его обновлении. Пользователь увидит диалоговое окно с просьбой предоставить соответствующее разрешение.
Чтобы обеспечить удобство для пользователя, важно запрашивать доступ в контексте. Если эта информация необходима для работы приложения, запрашивайте разрешение при запуске. Для этого рекомендуется использовать экран приветствия или мастер с объяснением причины запроса.
Если доступ к данным о местоположении необходим приложению лишь для некоторых функций, то запрос следует показывать лишь при выполнении действия, требующего такого разрешения.
Приложение должно корректно продолжить работу, если пользователь откажется предоставить доступ. Например, если разрешение требуется лишь для определенной функции, приложение может просто отключить ее. Если же приложение неспособно работать без этих данных, в нем могут отключиться функциональные возможности. При этом следует проинформировать пользователя о том, что для дальнейшей работы нужен доступ к данным о местоположении.
В следующем примере кода проверка разрешения выполняется с использованием библиотеки поддержки перед включением слоя «Мое местоположение»: Затем результат запроса разрешения обрабатывается путем реализации ActivityCompat.OnRequestPermissionsResultCallback из библиотеки поддержки.
Kotlin
Слой «Мое местоположение»
Слой «Мое местоположение» и одноименная кнопка позволяют пользователям видеть свое актуальное местоположение на карте. Чтобы включить слой «Мое местоположение», вызовите метод mMap.setMyLocationEnabled() .
Простой пример использования слоя «Мое местоположение»:
Kotlin
Если включен слой «Мое местоположение», соответствующая кнопка отображается в правом верхнем углу экрана. При нажатии этой кнопки камера центрирует карту по текущему местоположению устройства, если оно известно. На карте местоположение обозначается маленькой синей точкой, если устройство неподвижно, или значком шеврона, если устройство находится в движении.
На скриншоте ниже вы можете увидеть кнопку «Мое местоположение» справа вверху и синюю точку в центре карты.
Чтобы предотвратить показ кнопки «Мое местоположение», вызовите UiSettings.setMyLocationButtonEnabled(false) .
Ваше приложение может реагировать на следующие события:
- Если пользователь нажимает кнопку «Мое местоположение», ваше приложение получает обратный вызов onMyLocationButtonClick() от прослушивателя GoogleMap.OnMyLocationButtonClickListener .
- Если пользователь нажимает на синюю точку «Мое местоположение», ваше приложение получает обратный вызов onMyLocationClick() от прослушивателя GoogleMap.OnMyLocationClickListener .
Важный пункт Условий использования
Обеспечивайте конфиденциальность пользователей,
информируйте их о том, что происходит в приложении.
Всегда сообщайте пользователям, как вы собираетесь применять их данные. Препятствуйте персональной идентификации пользователей по их данным. Перед применением данных о местоположении обязательно получите разрешение. Дайте пользователям возможность в любое время отозвать его.
Location API сервисов Google Play
Данные о местоположении в приложениях для Android лучше всего обрабатывать с помощью Location API сервисов Google Play. Он позволяет выполнять следующие задачи:
- определять местоположение устройства;
- отслеживать изменение местоположения с помощью прослушивателей;
- определять способ движения, если местоположение устройства меняется;
- создавать геозоны и отслеживать пересечение их границ.
Location API упрощает создание приложений, работающих с данными о текущем местоположении пользователя и эффективно расходующих ресурс аккумулятора устройства. Как и Maps SDK for Android, Location API распространяется как часть SDK сервисов Google Play. Дополнительную информацию вы можете найти в учебном материале об использовании в приложении данных о местоположении, а также в документации по Location API. Примеры кода содержатся в SDK сервисов Google Play.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник
Android Get Address with Street Name, City for Location with Geocoding
In this Android tutorial, I will walk you through how to find the address based on the mobile location. We have got GPS or network provider in the Android device and we can use that to get the current location in terms of latitude and longitude. Using the latitude and longitude we can get the address by Google Geocoding API.
Download the Example Android Application
Geocoding
Geocoding is the process of converting the addresses (postal address) into geo coordinates as latitude and longitude. Reverse geocoding is converting a geo coordinate latitude and longitude to an address. In this tutorial we will be doing reverse geo coding and get the addresses of the passed coordinates.
Android Reverse Geocoding Example to find Address
Step1: Define Permissions
We need location access permission to find the latitude and longitude of the Android device. Following two lines are the key to give permission to access the location.
So the complete manifest file will be as below:
Step 2: Accessing the Geo Location for Lat and Long
Following class is the key element in accessing the latitude and longitude of the Android device. It implements the LocationListener and gets the location coordinate updates. We have designed our requirement not to be a continous update for location. On demand we will get the location coordinates.
AppLocationService.java
Step 3: Reverse Geocoding to get Location Address
Following class is the key element for reverse geocoding to get the address for the passed latitude and longitude coordinates. We access the Geocoder Google API for reverse geocoding and get every line of address like street, city, pin / zip code and etc.
LocationAddress.java
Step 4: Android UI
How these pieces fit together is with the following Android activity.
MyActivity.java
Android UI layout file to show the address and location
Key Points to Note for Geocoding
- Need Google API access and so remember to run in an emulator that is configured for Google API.
- Remember to have the right permissions defined in the Mainfest.xml
- To test via an Android Emulator, we can use the DDMS and pass the latitude and longitude using the ‘Emulator Control’.
Example Geo coordinates Latitude and Longitude with respective location address:
Download the Example Android Application
Popular Articles
Comments on «Android Get Address with Street Name, City for Location with Geocoding»
Awesome demo Sir Ji…
Sir, My one Suggestion,
if you don’t mind,
try using findViewById(R.id.btnGPSShowLocation).setOnClickListener(new View.OnClickListener() <
@Override
public void onClick(View arg0) <
//if you want to manage only onClick no other use in java file
>
>
OR
in layout xml, put OnClick property in atlest one post. so that people can get another way also if they might like.
[…] how to find latitude/longitude for a give address location. In a previous tutorial we learnt about reverse geocoding to find address for a latitude/longitude. This tutorial is a reverse of […]
the code have fatal exception
The app is continously asking me to enable location provider, but i have enabled my gps and wifi, and i am trying it on a real device
i have the same problem as hasan has the app when tried on real device says enable location provider inspite of gps n wifi being enabled.. can u please solve our query …
Thenkyu sir,i use this tutorial
it does not show city name why?
Thank you very much sir….. Simple n Effective.. Gr8 Work
Settings.ACTION_LOCATION_SOURCE_SETTINGS
i got error ;
what i will do
hello sir
i am getting settings Dialogs while my Location Provided is already Enabled.
I am also getting same issue as it is opening settings and even enabled the GPS i am not getting the location.
Can anyone help to solve this issue.
My friend’s device can get the address, but mine can’t. Is it the API level of the device problem? Cause my friend’s device API level is 19, but mine is API 18. Can someone help me?
sir,
i am too getting the same problem what they mentioned above as open setting even it is ON.
I am getting the same issue as the dialogue box keep prompting although I have already switched on the GPS and Wi-fi on my mobile. Any ideas?
For those, who are not getting lattitude, longitude values and address too, try using NETWORK_PROVIDER instead of GPS_PROVIDER in your codings. Comment the else part in codings that call the settings. Turn Wi-Fi on in your mobile and try, it will work. I did so and it worked. Thank you!
Thank you so much for this tutorial.
Why u are extending service? You did not start service at all in above program.
Use this for perfect work…
and same for address button click
btnGPSShowLocation.setOnClickListener(new View.OnClickListener() <
@Override
public void onClick(View arg0) <
Location gpsLocation = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
Location networkLocation = appLocationService
.getLocation(LocationManager.NETWORK_PROVIDER);
if (gpsLocation != null) <
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
String result = “Latitude: ” + gpsLocation.getLatitude()
+ ” Longitude: ” + gpsLocation.getLongitude();
tvAddress.setText(result);
> else if (networkLocation != null) <
double latitude = networkLocation.getLatitude();
double longitude = networkLocation.getLongitude();
String result = “Latitude: ”
+ networkLocation.getLatitude() + ” Longitude: ”
+ networkLocation.getLongitude();
tvAddress.setText(result);
> else <
showSettingsAlert();
>
>
>);
this solution solve all the errror
gps = new GPSTracker(MainActivity.this);
if(gps.canGetLocation())<
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
String result = “Latitude: ” + latitude +
” Longitude: ” + longitude;
tvAddress.setText(result);
Use this Class insted of AppLocationService.java this class
public class GPSTracker extends Service implements LocationListener <
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context context) <
this.mContext = context;
getLocation();
>
public Location getLocation() <
try <
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) <
> else <
this.canGetLocation = true;
if (isNetworkEnabled) <
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d(“Network”, “Network”);
if (locationManager != null) <
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) <
latitude = location.getLatitude();
longitude = location.getLongitude();
>
>
>
if (isGPSEnabled) <
if (location == null) <
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d(“GPS Enabled”, “GPS Enabled”);
if (locationManager != null) <
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) <
latitude = location.getLatitude();
longitude = location.getLongitude();
>
>
>
>
>
> catch (Exception e) <
e.printStackTrace();
>
public void stopUsingGPS() <
if(locationManager != null) <
locationManager.removeUpdates(GPSTracker.this);
>
>
public double getLatitude() <
if(location != null) <
latitude = location.getLatitude();
>
public double getLongitude() <
if(location != null) <
longitude = location.getLongitude();
>
public boolean canGetLocation() <
return this.canGetLocation;
>
public void showSettingsAlert() <
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle(“GPS is settings”);
// Setting Dialog Message
alertDialog.setMessage(“GPS is not enabled. Do you want to go to settings menu?”);
// On pressing Settings button
alertDialog.setPositiveButton(“Settings”, new DialogInterface.OnClickListener() <
public void onClick(DialogInterface dialog,int which) <
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
>
>);
// on pressing cancel button
alertDialog.setNegativeButton(“Cancel”, new DialogInterface.OnClickListener() <
public void onClick(DialogInterface dialog, int which) <
dialog.cancel();
>
>);
// Showing Alert Message
alertDialog.show();
>
@Override
public void onLocationChanged(Location location) <
>
@Override
public void onProviderDisabled(String provider) <
>
@Override
public void onProviderEnabled(String provider) <
>
@Override
public void onStatusChanged(String provider, int status, Bundle extras) <
>
@Override
public IBinder onBind(Intent arg0) <
return null;
>
WTF it only keep asking to enable location provider and never show location..
It doesn’t work. it asks me to enable location provider.please fix it.
In addition to changing your settings in emulator, go to DDMS and set latitude and longitude in emulator control and click on send. This code works then.
Hi,
It worked like a miracle. I just followed your steps.
But It is taking little bit of time (2sec, In my case) to get address. Is it the normal latency or it its happening in my case? Please provide if there is any faster way / new alternative.
Hi,
for all whose getting a Setting Dialog when using this code, why don’t you try using LocationManager.Network_Provider?
in this code, the MainActivity is using GPS_Provider.
because GPS is often taking a long time to get our location
I can sit here in my office and waiting all day for gps to get my location, and still nothing
try to change it to Network_Provider and it’ll work
Thank You so much 🙂 It helped me lot 🙂 🙂
Hi,
can we find the longitude and latitude of a current location with no internet connectivity.
if yes,can you provide me the code.
thanks in advance
Comments are closed for «Android Get Address with Street Name, City for Location with Geocoding».
Источник