i'm new to google maps and need to display the users country in a textView.
At the moment my app is displaying Latitude, Longitude and address..now I need the Country.
I have declared the following:
private LocationManager locationManager;
private Location myLocation;
And under OnCreate
lblAddress = (TextView) findViewById(R.id.tvAddress);
To get the Address I used;
private String getCompleteAddressString(double LATITUDE, double LONGITUDE, int x)
{
String strAdd = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try
{
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null)
{
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++)
{
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
}
}
catch (Exception e)
{
lblAddress.setText("Your address cannot be determined");
}
return strAdd;
}
Now how do I get the country in the same way?
You already have the Address, you can just call the getCountryName() method on it.
What I would do is create a POJO class so that you can return both the Address and Country from the method:
class MyLocation {
public String address;
public String country;
}
Then, make your method call return an instance of MyLocation, and populate both the Address and the Country before returning:
private MyLocation getCompleteAddressString(double LATITUDE, double LONGITUDE, int x)
{
String strAdd = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
MyLocation myLocation = new MyLocation(); //added
try
{
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null)
{
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
myLocation.country = returnedAddress.getCountryName(); //added
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++)
{
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
myLocation.address = strAdd; //added
}
}
catch (Exception e)
{
lblAddress.setText("Your address cannot be determined");
}
return myLocation; //modified
}
Be sure to do null checks on the return values.
MyLocation loc = getCompleteAddressString(lat, lon, x);
if (loc.address != null) {
//use to populate Address TextView
}
if (loc.country != null) {
//use to populate Country TextView
}
Related
I have latlng values in String .I want to convert That String into LatLng objects. likeLatLng latlng = new LatLng(lat, lng);
This is my data :
String latlan ="
[[13.041695199971244, 77.61311285197735],
[13.042000923637021, 77.61313531547785],
[13.041830750574812, 77.61335827410221],
[13.041507062142946, 77.61269208043814]]
";
Thanks in advance
Parse your data as follows:
List<LatLng> coordinates = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(latlan);
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray latLong = jsonArray.getJSONArray(i);
double lat = latLong.getDouble(0);
double lon = latLong.getDouble(1);
coordinates.add(new LatLng(lat, lon));
}
} catch (JSONException e) {
e.printStackTrace();
}
System.err.println(Arrays.toString(coordinates.toArray()));
for (LatLng latLng : coordinates) {
//use the coordinates.
}
I would just use a bunch of splits and replaceAlls to divide it up and then use the LatLan constructor in a foreach loop.
String latlng = "[[13.041695199971244, 77.61311285197735], [13.042000923637021, 77.61313531547785], [13.041830750574812, 77.61335827410221], [13.041507062142946, 77.61269208043814]]";
String[] latlngParts = latlng.split("\\], \\[");
for (String ll: latlngParts) {
String llReplaced = ll.replaceAll("\\[", "").replaceAll("\\]", "");
String[] llReplacedParts = llReplaced.split(", ");
LatLng latlngObj = new LatLng(llReplacedParts[0], llReplacedParts[1]);
// Then add latlngObj to some collection of LatLng objects
}
private void doConvertToLatLan(){
String latlan = "[[13.041695199971244, 77.61311285197735], [13.042000923637021, 77.61313531547785], [13.041830750574812, 77.61335827410221], [13.041507062142946, 77.61269208043814]]";
latlan = latlan.replace("[[","[");
latlan = latlan.replace("]]","]");
latlan = latlan.replace("[","");
latlan = latlan.replace("],","#");
String[] latlanDParts = latlan.split("#");
ArrayList<LatLan> data = new ArrayList<>();
for (String value: latlanDParts) {
String[] llReplacedParts = value.split(",");
data.add(new LatLan(llReplacedParts[0], llReplacedParts[1]));
}
Log.d("Data",data.toString());
}
private class LatLan{
private String lat,lan;
public LatLan(String lat, String lan) {
this.lat = lat;
this.lan = lan;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLan() {
return lan;
}
public void setLan(String lan) {
this.lan = lan;
}
};
I hope this will helpful!
I followed an example from Android Geocoding to Get Latitude Longitude for an Address tutorial, it worked but I want to fetch the longitude and latitude coordinates separately but could not.
Here is my code:
public class MainActivity extends AppCompatActivity {
Button addressButton;
TextView addressTV;
TextView latLongTV;
static TextView txtLatitude;
TextView txtLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addressTV = (TextView) findViewById(R.id.addressTV);
latLongTV = (TextView) findViewById(R.id.latLongTV);
txtLatitude = (TextView) findViewById(R.id.txtLatitude);
txtLatitude= (TextView) findViewById(R.id.txtLongitude);
addressButton = (Button) findViewById(R.id.addressButton);
addressButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText editText = (EditText) findViewById(R.id.addressET);
String address = editText.getText().toString();
GeocodingLocation locationAddress = new GeocodingLocation();
locationAddress.getAddressFromLocation(address,
getApplicationContext(), new GeocoderHandler());
}
});
}
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
String locationAddress,latitude ,longitude ;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationAddress = bundle.getString("address");
latitude = bundle.getString("latitude");
longitude = bundle.getString("longitude");
break;
default:
locationAddress = null;
latitude = null;
longitude= null;
}
latLongTV.setText(locationAddress);
txtLatitude.setText(latitude);
// txtLongitude.setText(longitude);
}
}
private static class GeocodingLocation {
private static final String TAG = "GeocodingLocation";
public void getAddressFromLocation(final String locationAddress,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
String strLatitude = null, strLongitude = null;
try {
List<Address> addressList = geocoder.getFromLocationName(locationAddress, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
double latitude = address.getLatitude();
double longitude = address.getLongitude();
StringBuilder sb = new StringBuilder();
sb.append(address.getLatitude()).append("\n");
sb.append(address.getLongitude()).append("\n");
result = sb.toString();
strLatitude = String.valueOf(latitude);
strLongitude= String.valueOf(longitude);
}
} catch (IOException e) {
Log.e(TAG, "Unable to connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n\nLatitude and Longitude :\n" + result;
bundle.putString("address", result);
bundle.putString("Latitude", strLatitude);
bundle.putString("Longitude", strLongitude);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n Unable to get Latitude and Longitude for this address location.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
According to this answer, bundle keys are case-sensitive. You set the strings with:
bundle.putString("Latitude", strLatitude);
bundle.putString("Longitude", strLongitude);
But then get them with:
latitude = bundle.getString("latitude");
longitude = bundle.getString("longitude");
Notice you put with a capital L, but get with a lower-case l.
This problem may sound a little weird, but whenever I run the app it crashes and when I change the name of LatLang variable in the function private LatLng getCurrentLocation(), It starts working. But when I change anything(even in any other file) it crashes and I have to keep changing the variable names to keep it running.
I am sure of the problem, it is something related to LatLang variable.
GetApproxTimeMaps.java
public class GetApproxTimeMaps extends FragmentActivity {
private static double destiLatitude;
private static double destiLongitude;
GoogleMap mMap;
GMapV2Direction md;
LatLng userLocation;
LatLng destination;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_approx_time_maps);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
userLocation = getCurrentLocation();
double lati = userLocation.latitude;
double longi = userLocation.longitude;
JSONObject jasonObject = getLocationInfo("Infosys");
boolean value = getLatLong(jasonObject);
System.out.println("value is: "+ value);
destination = new LatLng(destiLatitude, destiLongitude);
System.out.println("destination latitude :" + destiLatitude);
System.out.println("destination longitude :" + destiLongitude);
md = new GMapV2Direction();
mMap = ((SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
double toZoomLat = (destination.latitude + userLocation.latitude)/2;
double toZoomLon = (destination.longitude + userLocation.longitude)/2;
LatLng coordinates = new LatLng(toZoomLat, toZoomLon);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 12));
mMap.addMarker(new MarkerOptions().position(userLocation).title("Start"));
mMap.addMarker(new MarkerOptions().position(destination).title("End"));
Document doc = md.getDocument(userLocation, destination, GMapV2Direction.MODE_DRIVING);
int duration = md.getDurationValue(doc);
String distance = md.getDistanceText(doc);
String start_address = md.getStartAddress(doc);
String copy_right = md.getCopyRights(doc);
System.out.println(duration);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.BLUE);
for(int i = 0 ; i < directionPoint.size() ; i++) {
rectLine.add(directionPoint.get(i));
}
mMap.addPolyline(rectLine);
}
private LatLng getCurrentLocation(){
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = service.getLastKnownLocation(provider);
LatLng userlocat = new LatLng(location.getLatitude(),location.getLongitude());
return userlocat;
}
public static JSONObject getLocationInfo(String address) {
StringBuilder stringBuilder = new StringBuilder();
try {
address = address.replaceAll(" ","%20");
HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
public static boolean getLatLong(JSONObject jsonObject) {
try {
destiLongitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
destiLatitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
} catch (JSONException e) {
return false;
}
return true;
}
Update, please see below.
How do I return my class LocationData and my ArrayList listOfObjects to the onPostExecute()? I want to use it in my UI and right now it is in the background in an AsyncTask. Also I want to add markers with:
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lati, longi))
.title(name));
so that I can add each new location to the map after each loop.
Do I place the above in the onPostExecute after returning the LocationData class?
try {
String apples = endpoint.listContactInfo().execute().toString();
JSONObject jObject = new JSONObject(apples);
JSONArray jsonArr = jObject.getJSONArray("items");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj1 = jsonArr.getJSONObject(i);
// Storing each json item in variable
String id = jsonObj1.getString(TAG_ID);
String nameFirst1 = jsonObj1.getString(TAG_FIRSTNAME);
String nameLast1 = jsonObj1.getString(TAG_LASTNAME);
String emailAddress1 = jsonObj1.getString(TAG_EMAIL);
String streetAddress1 = jsonObj1.getString(TAG_ADDRESS);
String phone1 = jsonObj1.getString(TAG_PHONE);
// test to see if made it to string
Log.d("YOUR_TAG", "First Name: " + nameFirst1 + " Last Name: "
+ nameLast1);
address = coder.getFromLocationName(streetAddress1, 5);
Address location1 = address.get(0);
// SET LAT LNG VALUES FOR MARKER POINT
lati = location1.getLatitude();
longi = location1.getLongitude();
Log.d("Location", "Location:" + lati + " " + longi);
class LocationData {
private double lat;
private double longitude;
private String name;
public LocationData(double lat, double longitude,
String name) {
this.lat = lat;
this.longitude = longitude;
this.name = name;
}
public void setLat(double lat) {
this.lat = lat;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLat() {
return lat;
}
public double getLongitude() {
return longitude;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
ArrayList<LocationData> listOfObjects = new ArrayList<LocationData>();
listOfObjects.add(new LocationData(lati, longi, nameFirst1));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (long) 0;
}
// WHAT DO I PUT HERE TO RETURN LocationData Class here
// ADD MARKER TO MAP UI
protected void onPostExecute() {
// mMap.addMarker(new MarkerOptions()
// .position(new LatLng(lati, longi))
// .title("Hello world"));
This may seem elementary but I've created this method:
public ArrayList getLocationData() {
ArrayList<LocationData> listOfObjects = new ArrayList<LocationData>();
listOfObjects.add(new LocationData(lati, longi, nameFirst1));
return listOfObjects;
}
within my LocationData class. I then placed LocationData.getLocationData(); with the onPostExecute and I get the LocationData can't be resolved. The code together looks like this at the moment:
try {
String apples = endpoint.listContactInfo().execute().toString();
JSONObject jObject = new JSONObject(apples);
JSONArray jsonArr = jObject.getJSONArray("items");
for(int i =0 ; i<jsonArr.length() ;i++ ){
JSONObject jsonObj1 = jsonArr.getJSONObject(i);
// Storing each json item in variable
String id = jsonObj1.getString(TAG_ID);
final String nameFirst1 = jsonObj1.getString(TAG_FIRSTNAME);
String nameLast1 = jsonObj1.getString(TAG_LASTNAME);
String emailAddress1 = jsonObj1.getString(TAG_EMAIL);
String streetAddress1 = jsonObj1.getString(TAG_ADDRESS);
String phone1 = jsonObj1.getString(TAG_PHONE);
//test to see if made it to string
Log.d("YOUR_TAG", "First Name: " + nameFirst1 + " Last Name: " + nameLast1);
address = coder.getFromLocationName(streetAddress1,5);
Address location1 = address.get(0);
// SET LAT LNG VALUES FOR MARKER POINT
lati = location1.getLatitude();
longi = location1.getLongitude();
Log.d("Location", "Location:" + lati + " " + longi);
class LocationData {
private double lat;
private double longitude;
private String name;
public LocationData(double lat, double longitude, String name) {
this.lat = lat;
this.longitude = longitude;
this.name = name;
}
public void setLat(double lat) {
this.lat = lat;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLat() {
return lat;
}
public double getLongitude() {
return longitude;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public ArrayList<LocationData> getLocationData() {
ArrayList<LocationData> listOfObjects = new ArrayList<LocationData>();
listOfObjects.add(new LocationData(lati, longi, nameFirst1));
return listOfObjects;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (long) 0;
}
//WHAT DO I PUT HERE TO RETURN LocationData Class here
// ADD MARKER TO MAP UI
protected void onPostExecute(Long result ) {
//CANT BE RESOLVED
LocationData.getLocationData();
//mMap.addMarker(new MarkerOptions()
//.position(new LatLng(lati, longi))
// .title("Hello world"));
Here are my changes based upon #Sustain recommendations. I seem to not be getting any map markers now. Anyone see anything?
public class FinderActivity extends Activity implements LocationListener {
GoogleMap mMap;
Location myLocation;
EditText length;
String lengthString;
LocationManager locationmanager;
double lati;
double longi;
String nameFirst1;
//Spinner s;
List<Address> address;
Geocoder coder = new Geocoder(this);
private static final String TAG_ID = "id";
private static final String TAG_FIRSTNAME = "nameFirst";
private static final String TAG_LASTNAME = "nameLast";
private static final String TAG_EMAIL = "emailAddress";
private static final String TAG_ADDRESS = "streetAddress";
private static final String TAG_STATE = "state";
private static final String TAG_PHONE = "phone";
JSONArray contacts = null;
private static class LocationData {
private double lat;
private double longitude;
private String name;
public LocationData(double lat, double longitude, String name) {
this.lat = lat;
this.longitude = longitude;
this.name = name;
}
public void setLat(double lat) {
this.lat = lat;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLat() {
return lat;
}
public double getLongitude() {
return longitude;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (mMap!= null) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomBy(17));
}
LocationManager locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria cr = new Criteria();
String provider = locationmanager.getBestProvider(cr, true);
Location location = locationmanager.getLastKnownLocation(provider);
locationmanager.requestLocationUpdates(provider, 20, 0, (LocationListener) this);
mMap.moveCamera(CameraUpdateFactory.newLatLng((new LatLng(location.getLatitude(), location.getLongitude()))));
new EndpointsTask().execute(getApplicationContext());
}
public class EndpointsTask extends AsyncTask<Context, LocationData, Long> {
private List<LocationData> locationList = new ArrayList<LocationData>();
public Long doInBackground(Context... contexts) {
Contactinfoendpoint.Builder endpointBuilder = new Contactinfoendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) { }
});
Contactinfoendpoint endpoint = CloudEndpointUtils.updateBuilder(
endpointBuilder).build();
try {
String apples = endpoint.listContactInfo().execute().toString();
JSONObject jObject = new JSONObject(apples);
JSONArray jsonArr = jObject.getJSONArray("items");
for(int i =0 ; i<jsonArr.length() ;i++ ){
JSONObject jsonObj1 = jsonArr.getJSONObject(i);
// Storing each json item in variable
String id = jsonObj1.getString(TAG_ID);
String nameFirst1 = jsonObj1.getString(TAG_FIRSTNAME);
String nameLast1 = jsonObj1.getString(TAG_LASTNAME);
String emailAddress1 = jsonObj1.getString(TAG_EMAIL);
String streetAddress1 = jsonObj1.getString(TAG_ADDRESS);
String phone1 = jsonObj1.getString(TAG_PHONE);
//test to see if made it to string
Log.d("YOUR_TAG", "First Name: " + nameFirst1 + " Last Name: " + nameLast1);
address = coder.getFromLocationName(streetAddress1,5);
Address location1 = address.get(0);
// SET LAT LNG VALUES FOR MARKER POINT
lati = location1.getLatitude();
longi = location1.getLongitude();
Log.d("Location", "Location:" + lati + " " + longi);
LocationData data = new LocationData(lati, longi, nameFirst1);
locationList.add(data);
publishProgress(data);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (long) 0;
}
protected void onProgressUpdate(LocationData data) {
// Add Marker on Map using data. This is called by
// publishProgress(LocationData) on the UI Thread.
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lati, longi))
.title(nameFirst1));
Log.d("bananas", lati + longi + nameFirst1);
}
//WHAT DO I PUT HERE TO RETURN LocationData Class here
// ADD MARKER TO MAP UI
protected void onPostExecute() {
}
}
The class LocationData is defined inside an unreachable scope. Instead, define it in it's own .java file like so:
class LocationData {
// final Fields
// Constructor
// Getters
}
or as a private static class of your outermost class if you don't use it anywhere else.
Then for your subclass of AsyncTask you could have something like:
private class AsyncJsonTask extends AsyncTask<Param, LocationData, Void>
{
private List<LocationData> locationList = new ArrayList<LocationData>();
// ...
protected void doInBackground(Param) {
// ...
for (int i = 0; i < jsonArr.length(); i++) {
// Do your stuff with JSon Objects
// ...
// Instanciate a new LocationData and pass it as progress:
LocationData data = new LocationData(latitude, longitude, name);
locationList.add(data);
publishProgress(data);
}
}
protected void onProgressUpdate(LocationData data) {
// Add Marker on Map using data. This is called by
// publishProgress(LocationData) on the UI Thread.
mMap.addMarker(/* marker */);
}
protected void onPostExecute() {
// Assign outer class member field the value of the builded list
// for future reference.
mLocationList = locationList;
}
}
This way, you can publish each marker individually on the map before fetching the next one.
As a side note, you should investigate the meaning of static methods and fields; your call to LocationData.getLocationData() would not be valid.
onPostExecute runs in the UI thread. So any changes in the UX can be done here, in your case, adding markers to the map.
onPostExecute takes in the Result parameter returned from doInBackground().
You can learn more about AsyncTask from http://developer.android.com/reference/android/os/AsyncTask.html
It got a nice example as well.
I am making an application in which i have to display the the name of the current location. I am getting latitude and longitude but cannot get the name of the location.
The code I am trying to do this is:
context = getApplicationContext();
Location location;
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
double lon, lat;
try
{
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lon = location.getLongitude();
lat = location.getLatitude();
Toast.makeText(context, "Lat: "+lat+"\nLon: "+lon, Toast.LENGTH_LONG).show();
List<Address> mAddresses = null;
Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
try
{
mAddresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
}
catch (IOException e)
{
e.printStackTrace();
}
#SuppressWarnings("unchecked")
String cityName = (mAddresses != null) ? ((List<Address>) mAddresses).get(0)
.getLocality() : TimeZone.getDefault().getID();
#SuppressWarnings("unchecked")
String countryName = (mAddresses != null) ? ((List<Address>) mAddresses).get(0)
.getCountryName() : Locale.getDefault().getDisplayCountry()
.toString();
try
{
lm.clearTestProviderLocation(LocationManager.GPS_PROVIDER);
}
catch(Exception e)
{}
Toast.makeText(context, "Using GPS Provider", Toast.LENGTH_SHORT).show(); }
catch(Exception exp1){
try
{
location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
lon= location.getLongitude();
lat = location.getLatitude();
Toast.makeText(context, "Lat: "+lat+"\nLon: "+lon, Toast.LENGTH_LONG).show();
List<Address> mAddresses = null;
Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
try
{
mAddresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
}
catch (IOException e)
{
e.printStackTrace();
}
#SuppressWarnings("unchecked")
String cityName = (mAddresses != null) ? ((List<Address>) mAddresses).get(0).getLocality() : TimeZone.getDefault().getID();
#SuppressWarnings("unchecked")
String countryName = (mAddresses != null) ? ((List<Address>) mAddresses).get(0).getCountryName() : Locale.getDefault().getDisplayCountry().toString();
try
{
lm.clearTestProviderLocation(LocationManager.NETWORK_PROVIDER);
}
catch(Exception e)
{}
Toast.makeText(context, "Using Network Provider", Toast.LENGTH_SHORT).show();
}
It is better to do it in Async task like
private class LocationTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... parms) {
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);
// 1000).show();
return _Location;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return " ";
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onPostExecute(String locOutcome) {
//Use locOutcome here
}
}
Don't forget to add permission
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />