i try to get the current zip code from the longitude and latitude which MyLocationOverlay delivers and set this to a EditView on my Activity.
The Activity crashs when i try to get the longitude and latitude from MyLocationOverlay.
Whats wrong with this code?
Regards,
float
LogCat output: http://codepaste.net/vs6itk
Line 59 is the following line:
double currentLatitude = myLocationOverlay.getMyLocation().getLatitudeE6();
Here is my Code:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.partner_suche);
final EditText tView = (EditText) findViewById(R.id.editTextPLZ);
final MapView mView = (MapView) findViewById(R.id.mapview);
mView.getController().setZoom(14);
List<Overlay> mapOverlays = mView.getOverlays();
myLocationOverlay = new MyCustomLocationOverlay(this, mView);
mapOverlays.add(myLocationOverlay);
myLocationOverlay.enableMyLocation();
myLocationOverlay.enableCompass();
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mView.getController().animateTo(myLocationOverlay.getMyLocation());
}
});
Geocoder gc = new Geocoder(this, Locale.getDefault());
double currentLatitude = myLocationOverlay.getMyLocation().getLatitudeE6();
double currentLongitute = myLocationOverlay.getMyLocation().getLongitudeE6();
try
{
List<Address> addresses = gc.getFromLocation(currentLatitude, currentLongitute, 1);
if (addresses.size() > 0)
{
tView.setText(addresses.get(0).getLocality());
}
} catch (IOException e)
{
}
}
EDIT:
I created a LocationListener to get my current location. Now the part crashes where i try to run gc.getFromLocation(latitude, longitude, 1); I can't read the Exception? :/
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,Bundle extras){ }
};
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
private void updateWithNewLocation(Location location) {
final EditText tView = (EditText) findViewById(R.id.editTextPLZ);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
if (location != null) {
try
{
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0)
{
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++){
tView.setText(address.getPostalCode());
}
}
} catch (Exception e)
{
}
}
}
If you are using an emulator API level 8 or 9, and getting the exception:
java.io.IOException: Service not Available
then it is a known bug, see service not available
It works OK on real devices and emulator level 7 though. ( You should probably put a trap on addresses being null too, though this won't make the geocoder work!)
Most likely the location being returned from
myLocationOverlay.getMyLocation()
or
Location location = locationManager.getLastKnownLocation(provider);
is NULL. Likely due to your application not yet having received a location fix, and having no previously saved locations.
Try moving the code block where you do the geocoding into your runnable that runs after receiving a fix. Like this:
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
Location loc = myLocationOverlay.getMyLocation();
if (loc != null) {
mView.getController().animateTo(loc);
Geocoder gc = new Geocoder(this, Locale.getDefault());
double currentLatitude = loc.getLatitudeE6();
double currentLongitute = loc.getLongitudeE6();
try
{
List<Address> addresses = gc.getFromLocation(currentLatitude, currentLongitute, 1);
if (addresses.size() > 0)
{
tView.setText(addresses.get(0).getLocality());
}
} catch (IOException e)
{
}
}
}
});
Related
A part of my app is attempting to update the location (using DDMS with an emulator in Eclipse) and then get the address to print to LogCat.
My code:
LocationManager locationManager;
String providerName = LocationManager.GPS_PROVIDER;
LocationProvider gpsProvider;
public void enable()
{
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); //Need to ask for this system service
Criteria criteria = new Criteria(); //Setting the criteria for the location provider
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
criteria.setAltitudeRequired(true);
criteria.setBearingRequired(true);
criteria.setSpeedRequired(true);
criteria.setCostAllowed(true);
String provider = LocationManager.GPS_PROVIDER;
int time = 5000; //Time in ms
int distance = 5; //Distance in meters
LocationListener myLocationListener = new LocationListener()
{
public void onLocationChanged(Location locations)
{
updateLocation(locations);
}
public void onProviderDisabled(String arg0)
{
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0)
{
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2)
{
// TODO Auto-generated method stub
}
};
locationManager.requestLocationUpdates(provider, time, distance, myLocationListener);
}
/////////////////////////////////////////////////////////////////////////////////
public void findLocation()
{
gpsProvider = locationManager.getProvider(providerName);
//String bestProvider = locationManager.getBestProvider(criteria, true);
Location locations = locationManager.getLastKnownLocation(providerName);
updateLocation(locations);
}
public void updateLocation(Location locations)
{
if (locations != null)
{
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
double latitude = locations.getLatitude();
double longitude = locations.getLongitude();
List<Address> addresses = null;
Geocoder GCoder = new Geocoder(this, Locale.getDefault());
try
{
addresses = GCoder.getFromLocation(latitude, longitude, 10);
Address first = addresses.get(0);
Log.d("ADDRESS", first.toString());
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
This, to me, should print the value "first" into LogCat but it doesn't seem to actually display anything.
I have the required permission in the manifest so that is not the issue.
Any help that can be provided is great, thank you.
Use this code
See Updated Code
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), true);
Location locations = locationManager.getLastKnownLocation(provider);
List<String> providerList = locationManager.getAllProviders();
if(null!=locations && null!=providerList && providerList.size()>0){
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if(null!=listAddresses&&listAddresses.size()>0){
String _Location = listAddresses.get(0).getAddressLine(1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
i need your help regarding the location update in android. Following is my code for getting location update and it is working fine. But it returns invalid message body when i get the stored variable with location in oncreate method of main class. After thorough research it seems that the variable i called in oncreate method is empty. Can you please tell me how to get the address as it appears in onlocationChanged Method. Thank you!
Calling class with oncreate method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listener = new Mylocation();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
String address1= listener.getAddress();
{
sendSms(phone, message, false);
} catch (Exception e) {
Log.i("Error Is ", e.toString());
}
}
location class:
class Mylocation implements LocationListener{
double lat, lon;
static final String address="";
public void onLocationChanged(Location location)
{
//...
lat = location.getLatitude();
lon = location.getLongitude();
address = GetAddressDetail(lat, lon);
Log.i("Messge is", address); //working here
}
public String getAddress(){ //not returning the address
return address;
}
public String GetAddressDetail(Double lat2, Double lon2)
{
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
return ret;
}
}
Make sure your variables are initialized properly. I don't see evidence of this in the question so I am just checking.
// Instantiation
Mylocation listener;
String phone;
String message;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization
listener = new Mylocation(this);
phone = "";
message = "";
// These two lines aren't really necessary,
// this should be in your MyLocation class
//locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
// Add this line, we are going to initialize this class
// and make sure that address gets set
listener = new Mylocation();
String address1 = listener.getAddress();
try {
// If neither phone nor message is empty lets sendSms()
if (!phone.isEmpty() || !message.isEmpty()) {
sendSms(phone, message, false);
}
} catch (Exception e) {
Log.i("Error Is ", e.toString());
}
}
Change the String address to private and in the getter try return this.address;
class Mylocation implements LocationListener {
double lat, lon;
// Let's make this private so it can't be accessed directly,
// since you have the setter and getter.
private String address = "";
// Make sure you are overriding this method
#Override
public void onLocationChanged(Location location) {
/** ... */
lat = location.getLatitude();
lon = location.getLongitude();
address = GetAddressDetail(lat, lon);
Log.i("Messge is", address);
}
public String getAddress(){
return (address.isEmpty()) ? "Address not set" : this.address;
}
public String GetAddressDetail(Double lat2, Double lon2) {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
return ret;
}
}
Edit
I made changes to your code in my answer above, check the comments. I am also going to suggest additional methods for your MyLocation class:
class Mylocation implements LocationListener {
protected LocationManager locationManager;
private Context activityContext;
// The initializing method, this fires off first
// when a new instance of the class is created
public MyLocation(Context context) {
this.activityContext = context;
locationManager = (LocationManager) activityContext.getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);) {
locationManager.requestLocationUpdates(
NETWORK_PROVIDER,
MIN_TIME,
MIN_DISTANCE,
this
);
}
getLocation();
}
private double lat;
private double lon;
public double getLat() {
return this.lat;
}
public double getLng() {
return this.lng;
}
public void getLocation() {
if (location == null) {
locationManager.requestLocationUpdates(NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(NETWORK_PROVIDER);
if (location != null) {
// Set the coordinate variables
lat = location.getLatitude();
lon = location.getLongitude();
Log.i("Network", "Lat: " + latitude + " / Lng: " + longitude);
}
}
}
}
}
You are calling getAdress directly after you set the locationmanager to probe for a location. The onLocationChanged method probably hasn't been called yet when you call getAddress this way. I would recommend changing it to something like below to make sure it has been called:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listener = new Mylocation();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,new LocationListener(){
#Override
public void onLocationChanged(Location location) {
//...
long lat = location.getLatitude();
long lon = location.getLongitude();
String address = GetAddressDetail(lat, lon);
//Do whatever you want to do with the address here, maybe add them to the message or something like that.
sendSms(phone, message, false);
}
});
}
public String GetAddressDetail(Double lat2, Double lon2)
{
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
return ret;
}
so I am making an application to get current position. The code below is working fine
String stringAddress = "";
public void getLocation(View view){
final LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria kriteria = new Criteria();
kriteria.setAccuracy(Criteria.ACCURACY_FINE);
kriteria.setAltitudeRequired(false);
kriteria.setBearingRequired(false);
kriteria.setCostAllowed(true);
kriteria.setPowerRequirement(Criteria.POWER_LOW);
final String provider = lm.getBestProvider(kriteria, true);
final Location lokasi = lm.getLastKnownLocation(provider);
updateWithNewLocation(lokasi);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 5, ll);
edittext_position.setText(stringAddress);
}
private void updateWithNewLocation(Location
if(lokasi != null){
double lat = lokasi.getLatitude();
double lng = lokasi.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try{
List addresses = gc.getFromLocation(lat, lng, 1);
StringBuilder sb = new StringBuilder();
if(addresses.size()>0){
Address address = addresses.get(0);
sb.append(address.getAddressLine(0));
stringAddress= sb.toString();
}
} catch (Exception e){
}
}
}
private final LocationListener ll = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
}
but the problem is everytime I call getLocation() function, the application hang for a couple second before returning the result. I know to solve this problem using aSyncTask but I don't know how to start. Appreciate your help.
Thank you
It's snippet from my application:
public void getCurrentLocation(final ListenerGetCurrentLocation listenerGetCurrentLocation) {
new AsyncTask<Void, Void, List<Address>>() {
#Override
protected List<Address> doInBackground(Void... voids) {
Geocoder geo = new Geocoder(instance);
List<Address> listAddresses = null;
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
if (bestProvider == null) {
bestProvider = LocationManager.NETWORK_PROVIDER;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
try {
if (location != null) {
listAddresses = geo.getFromLocation(location.getLatitude(),
location.getLongitude(),
1);
}
} catch (IOException e) {
e.printStackTrace();
}
return listAddresses;
}
public void onPostExecute(List<Address> listAddresses) {
Address _address = null;
if ((listAddresses != null) && (listAddresses.size() > 0)) {
_address = listAddresses.get(0);
GeoPoint currentPosition = new GeoPoint(((int)(_address.getLatitude() * 1E6)),
((int)(_address.getLongitude() * 1E6)));
}
}
}.execute();
}
requestLocationUpdates() is asynchronous, it doesn't block your app. It polls the location in the background, then it calls the listener.
However, gc.getFromLocation() is not. This is probably the cause of your lag
Create a new AsyncTask, Eclipse will propose you to override those methods
#Override
protected List<String> doInBackground(String... params) {
// this is done in the background so it won't block the UI. The return type must be set to List<String> (I think default is just String)
return gc.getFromLocation()
}
#Override
protected void onPostExecute(List<String> adresses) {
// called when the GC work is finished. You can now use your list of addresses and display them
}
Don't forget to call execute() on your task.
I want to get the current location with name. I did coding for get current location (lat,lang), how can I show the relative place name?
(ie) 13.006389 - 80.2575 : Adyar,Chennai,India
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
// called when the location provider status changes. Possible status: OUT_OF_SERVICE, TEMPORARILY_UNAVAILABLE or AVAILABLE.
}
public void onProviderEnabled(String provider) {
// called when the location provider is enabled by the user
}
public void onProviderDisabled(String provider) {
// called when the location provider is disabled by the user. If it is already disabled, it's called immediately after requestLocationUpdates
}
public void onLocationChanged(Location location) {
double latitute = location.getLatitude();
double longitude = location.getLongitude();
// do whatever you want with the coordinates
}
});
This will convert the lat & lng into String Address and i have set it in the text field for your example. This is done by using the concept of Reverse Geocoding & there is a class called Geocoder in Android.
// Write the location name.
//
try {
Geocoder geo = new Geocoder(this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
if (addresses.isEmpty()) {
yourtextboxname.setText("Waiting for Location");
}
else {
yourtextboxname.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
}
}
Here is code to get current location and draw it on Google Maps
public class Showmap extends MapActivity {
private MapView mapView;
private MapController mapController;
private LocationManager locationManager;
private LocationListener locationListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showmap);
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
mapView = (MapView) findViewById(R.id.mapView);
// enable Street view by default
mapView.setStreetView(true);
// enable to show Satellite view
// mapView.setSatellite(true);
// enable to show Traffic on map
// mapView.setTraffic(true);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(16);
}
protected boolean isRouteDisplayed() {
return false;
}
private class GPSLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
mapController.animateTo(point);
mapController.setZoom(16);
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
String address = ConvertPointToLocation(point);
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT)
.show();
mapView.invalidate();
}
}
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(getBaseContext(),
Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0)
.getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
Log.i(address, address);
}
} catch (IOException e) {
e.printStackTrace();
}
return address;
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider,int status,Bundle extras){}
}
class MapOverlay extends Overlay {
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.marker);
// 24 is the height of image
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);
return true;
}
}
}
Use reverse geocoding,feed the latitude and longitude and get the address.
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
myAddress.setText(strReturnedAddress.toString());
}
else{
myAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
myAddress.setText("Canont get Address!");
}
The phrase you're looking for is "Reverse Geocoding". Another question on StackOverflow discusses the same topic- You can use that one's selected answer :)
This is only for Hint add your code !
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
System.out.println("in onlocationchanged");
String locationString=location.convert(location.getLatitude(),1);
Toast.makeText(this,"locationString=="+locationString, Toast.LENGTH_LONG).show();
double lat = location.getLatitude();
double lng = location.getLongitude();
String currentLocation = "The location is changed to Lat: " + lat + " Lng: " + lng;
Toast.makeText(this,currentLocation, Toast.LENGTH_LONG).show();
use this two method
public double getLattitude() {
return lattitude;
}
}
public double getLongitude() {
return longitude;
public class MainActivity extends AppCompatActivity {
double latitude, longitude;
private TextView tvLocation;
private Button btnGetLocation;
private FusedLocationProviderClient locationProviderClient;
private Geocoder geocoder;
private List<Address> addresses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
locationProviderClient = LocationServices.getFusedLocationProviderClient(this);
tvLocation = findViewById(R.id.tv_location);
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
btnGetLocation = findViewById(R.id.btn_location);
btnGetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationProviderClient.getLastLocation().addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
tvLocation.setText(location.toString());
latitude = location.getLatitude();
longitude = location.getLongitude();
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String addressLine1 = addresses.get(0).getAddressLine(0);
Log.e("line1", addressLine1);
String city = addresses.get(0).getLocality();
Log.e("city", city);
String state = addresses.get(0).getAdminArea();
Log.e("state", state);
String pinCode = addresses.get(0).getPostalCode();
Log.e("pinCode", pinCode);
String fullAddress = addressLine1 + ", " + city + ", " + state + ", " + pinCode;
tvLocation.setText(fullAddress);
} catch (IOException e) {
e.printStackTrace();
Log.e("MainActivity", e.getMessage());
}
}
}
});
}
});
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
}
}
Here Is my code to get the current country Name.
private String getCountry() {
String country_name = null;
LocationManager lm = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Geocoder geocoder = new Geocoder(getApplicationContext());
for(String provider: lm.getAllProviders()) {
#SuppressWarnings("ResourceType") Location location = lm.getLastKnownLocation(provider);
if(location!=null) {
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(addresses != null && addresses.size() > 0) {
country_name =addresses.get(0).getCountryName();
return country_name;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(getApplicationContext(), country_name, Toast.LENGTH_LONG).show();
return null;
}
But don't forget to add this permission in the manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
This question already has answers here:
Geocoder.getFromLocation throws IOException on Android emulator
(7 answers)
Closed 6 months ago.
In the code below, I am getting the following exception
NO SERVICE AVAIALBLE
public class ds extends Activity {
LocationManager locationManager;
double lati,longi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String location_context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(location_context);
testProviders();
}
public void testProviders() {
TextView tv = (TextView)findViewById(R.id.myTextView);
StringBuilder sb = new StringBuilder("Enabled Providers:");
List<String> providers = locationManager.getProviders(true);
for (String provider : providers)
{
locationManager.requestLocationUpdates(provider, 1000, 0,new LocationListener()
{
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider){}
public void onProviderEnabled(String provider){}
public void onStatusChanged(String provider, int status,
Bundle extras){}
});
sb.append("\n").append(provider).append(":");
Location location = locationManager.getLastKnownLocation(provider);
if (location != null)
{
double lat = location.getLatitude();
double lng = location.getLongitude();
sb.append(lat).append(",").append(lng);
lati=lat;
longi=lng;
Geocoder gcd = new Geocoder(ds.this, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(lati, longi, 1);
if (addresses.size() > 0)
} catch (IOException e) {
Toast.makeText(ds.this, "hi exception", 5000).show();
}
}
else {
sb.append("No Location");
}
}
tv.setText(sb);
}
}
Code for Reverse Geocoding , you can pass the lattitude and longitude according to your requirement......
public class MainActivity extends FragmentActivity {
static final LatLng DELHI = new LatLng(39.6985207, -104.8954315);
GoogleMap map;
Button btn_geo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activitymain);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
btn_geo=(Button)findViewById(R.id.btn_getAddress);
map.addMarker(new MarkerOptions().position(DELHI).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(DELHI, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
btn_geo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
if(myLocation.isPresent())
{
List<Address> addresses=null ;
addresses = myLocation.getFromLocation(39.6985207, -104.8954315, 1);
System.out.println(".................."+addresses);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0)
{
Address address = addresses.get(0);
sb.append(address.getAddressLine(0)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
Toast.makeText(getApplicationContext(), sb,Toast.LENGTH_LONG).show();
}
}
else
Toast.makeText(getApplicationContext(), "Not present",Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}