Android geocoding api can't return addressess - android

I'm having some trouble geocoding locations, i guess i've implemented everything. I've registered a google api, i've recieved a working google Api key, i also turned on google maps and geocoding services, but i can't get any locations associated with some hardcoded longitudes and latitudes.
Here's the code:
My AppLocationService
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#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;
}
}
My LocationAddress class
public class LocationAddress {
private static final String TAG = "LocationAddress";
public static void getAddressFromLocation(final double latitude, final double longitude,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> addressList = geocoder.getFromLocation(
latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append("\n");
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
result = sb.toString();
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n\nAddress:\n" + result;
bundle.putString("address", result);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n Unable to get address for this lat-long.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
Somewhere deep in my mainActivity:
appLocationService = new AppLocationService(
ServerInterface.this);
Location location = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
double latitude = 47.162494;
double longitude = 19.503304;
LocationAddress locationAddress = new LocationAddress();
LocationAddress.getAddressFromLocation(latitude, longitude,
getApplicationContext(), new GeocoderHandler());
}
Thanks,

I think you can take look at this. I tried and it worked.
Hope it hopes.

Related

how to retrieve user selection from settings in the device

my application is using GPS services now i in case the GPS is off the user have the option to navigate to the device settings and set the GPS on.
now i would like to handle the user selection,
in case the user turn on the GPS the app should run again the getLocation function other wise do nothing.
but i do not know how can i handle the result of the new activity because i run it from non activity class. the relevant method is LocationAlertDialog
this is my class code:
public class GPSportLocationManager {
private boolean gpsEnabled,networkEnabled,isLocationUpdating,tryLocating = true;
private LocationManager locationManager;
private Location currentLoc=null;
private Context context;
private OnLocationFoundListener listener;
private int networkLocCount=0,gpsLocCount=0;
public GPSportLocationManager(Context ctx,OnLocationFoundListener mListener){
this.context = ctx;
this.listener = mListener;
}
/**
* method which finding the device location.
*/
public void getLocation(){
listener.getLocationInProccess();
try {
locationManager = (LocationManager) this.context.getSystemService(Context.LOCATION_SERVICE);
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!gpsEnabled && !networkEnabled){
LocationAlertDialog();
}else{
if(gpsEnabled){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
Constants.GPS_MIN_TIME_BETWEEN_UPDATE,Constants.GPS_MIN_DISTANCE_CHANGE,gpsListener);
}if(networkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
Constants.NETWORK_MIN_TIME_BETWEEN_UPDATE,Constants.NETWORK_MIN_DISTANCE_CHANGE,networkListener);
}
}
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Runnable() {
#Override
public void run() {
if(currentLoc == null){
if(gpsEnabled){
currentLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}else if(networkEnabled){
currentLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(currentLoc != null && listener !=null){
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
listener.onLocationFound(currentLoc);
}
}
}
},30, TimeUnit.SECONDS);
}catch (Exception e){
Toast.makeText(context,"Error while getting location"+e.getMessage(),Toast.LENGTH_LONG).show();
}
}
/**
* GPS location listener handle the callbacks.
*/
private LocationListener gpsListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(gpsLocCount != 0 && !isLocationUpdating){
isLocationUpdating = true;
currentLoc = location;
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
isLocationUpdating = false;
if(currentLoc != null && listener !=null){
listener.onLocationFound(currentLoc);
}
}
gpsLocCount++;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
private LocationListener networkListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(networkLocCount != 0 && !isLocationUpdating){
isLocationUpdating = true;
currentLoc = location;
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
isLocationUpdating = false;
if(currentLoc != null && listener !=null){
listener.onLocationFound(currentLoc);
}
}
networkLocCount++;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
public void LocationAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Location settings");
alertDialog
.setMessage("We cannot retrieve your location. Please click on Settings and make sure your GPS is enabled");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
tryLocating =false;
listener.onLocationFound(currentLoc);
dialog.cancel();
}
});
alertDialog.show();
}
/**
* this function get Longitude and Latitude coordinates and send back the real street address.
* #param LATITUDE
* #param LONGITUDE
* #param ctx
* #return
*/
public String getCompleteAddressString(double LATITUDE, double LONGITUDE, Context ctx) {
String strAdd = "";
Geocoder geocoder = new Geocoder(ctx, 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();
Log.w("My Current location address", "" + strReturnedAddress.toString());
} else {
Log.w("My Current location address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current location address", "Can not get Address!");
}
return strAdd;
}
/**
* this function convert real address to geographical coordinates.
* #param strAddress -real address
* #return LatLng object which contain the coordinates
*/
public LatLng getLocationFromAddress(String strAddress) {
Geocoder coder = new Geocoder(context);
List<Address> address;
LatLng p1 = null;
try {
address = coder.getFromLocationName(strAddress, 5);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new LatLng(location.getLatitude(), location.getLongitude() );
Log.d("coordinates",p1.latitude+""+p1.longitude);
} catch (Exception ex) {
Log.d("Location Exception", "error converting address");
ex.printStackTrace();
}
return p1;
}
public boolean isTryLocating() {
return tryLocating;
}
}

How to get the data from the BroadcastReceiver to another class BroadcastReceiver

I am using the BroadcastReceiver in my application ,here i am receiving the current location and place in this class.hence i am getting the current location,hence my question is how to send this location string from this class to another class .i have to load this string data in the listview in another class so how can do this please help thanks in advance. My code is
public class AlarmReceiver extends BroadcastReceiver implements LocationListener {
MyTrip trip_method;
double latitude, longitude;
Context context;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
protected LocationManager locationManager;
Location location;
#Override
public void onReceive(Context context, Intent intent) {
trip_method = new MyTrip();
this.context = context;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Find_location();
// For our recurring task, we'll just display a message
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
public void Find_location() {
// Location nwLocation;
try {
location = getLocation(LocationManager.NETWORK_PROVIDER);
System.out.println("nwLocation-------" + location);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
System.out.println("latitude-------" + latitude + "longitude-----" + longitude);
Toast.makeText(
context,
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
// To display the current address in the UI
(new GetAddressTask()).execute(location);
} else {
trip_method.showSettingsAlert("NETWORK");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
/* *//**//*
* Following is a subclass of AsyncTask which has been used to get
* address corresponding to the given latitude & longitude.
*//**//**/
private class GetAddressTask extends AsyncTask<Location, Void, String> {
Context mContext;
/* public GetAddressTask(Context context) {
super();
mContext = context;
}*/
/* *//**//*
* When the task finishes, onPostExecute() displays the address.
*//**//**/
#Override
protected void onPostExecute(String address) {
// Display the current address in the UI
Toast.makeText(context.getApplicationContext(),
"address---" + address,
Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Location... params) {
String Address = null;
String Location = null;
Geocoder geocoder;
List<android.location.Address> addresses;
geocoder = new Geocoder(context, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
Address = addresses.get(0).getAddressLine(0) + ", " + addresses.get(0).getAddressLine(1) + ", " + addresses.get(0).getAddressLine(2);
Location = addresses.get(0).getAddressLine(2);
System.out.println("Location----" + Location);
//This "Location" value i have to send to another activity
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Return the text
return Address;
/* } else {
return "No address found";
}*/
}
}// AsyncTask class
}
Use this in your code as appropriate:
In your First class:
Intent intent = new Intent(this, another_activity.class);
intent.putExtra("Location", Location.toString);
startService(intent)
In your Second class:
String Location = getActivity().getIntent.getStringExtra("Location")
Now you have passed string from one class to another. Use the Location variable where you need it.

Using Google Play location API in a seperated class?

In the Android Developer guide, Google showed how to use the Google Play Services API in an activity class. What is the best way to offload the API calls into a separate class?
public class GPSresource implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
private GoogleApiClient mGAC;
private Context mContext;
public static final String TAG = "GPSresource";
public GPSresource(Context c)
{
mContext = c;
try {
buildGoogleApiClient();
mGAC.connect();
}
catch(Exception e)
{
Log.d(TAG,e.toString());
}
}
protected synchronized void buildGoogleApiClient() {
mGAC = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
#Override
public void onConnected(Bundle bundle) {
location = LocationServices.FusedLocationApi.getLastLocation(mGAC);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
The code I wrote above does not work since onConnected is never called since this is not an activity. Is there a better way to separate the GPS services from the Main Activity or is that the only option(If so, is there a reason as to why?) Perhaps making a thread in the main activity to run in the background?
Thanks!
onConnected is called, I made a mistake with reading the logs!
Here is an example :
public class LocationManager implements LocationListener {
private LocationManager locationManager;
public LocationManager()
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
Location mobileLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mobileLocation != null)
{
onLocationChanged(mobileLocation);
}
Location netLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (netLocation != null)
{
onLocationChanged(netLocation);
}
}
#Override
public void onLocationChanged(Location loc) {
String longitude = "Longitude: " + loc.getLongitude();
//Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
// Log.v(TAG, latitude);
/*------- To get city name from coordinates -------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
// Log.e(TAG, "addr : " + addresses.toString());
if (addresses.size() > 0)
cityName = addresses.get(0).getLocality();
}
catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Current City is: " + cityName;
Log.e(TAG, "location : " + s);
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude", "disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
public void pause() {
if (locationManager != null)
{
locationManager.removeUpdates(this);
locationManager = null;
}
}
public void destroy() {
if (locationManager != null)
{
locationManager.removeUpdates(this);
locationManager = null;
}
}
}

Trouble calling and getting location in oncreate method from location listener android

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;
}

How to use locationManager?

I try to add a location from the GPS but i always get null. Can you please help and show me what I did wrong?
I would like to always receive the location in onCreate. If no location is received
"No provider received" appears instead of the location. The problem is i always get the message.
//Location variables
private TextView gps;
private LocationManager locationManager;
private String locationProvider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_draw);
initializeData();
}
private void initializeData()
{
gps = (TextView) findViewById(R.id.GPS);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationProvider = locationManager.getBestProvider(new Criteria(), true);
if(locationProvider!=null)
{
gps.setText("Upload image location: "+ locationProvider);
}
else
{
gps.setText("Upload image location: No provider Found" );
}
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
private void showLocation(Location location)
{
if(location==null)
gps.append("\nUnknown location");
else
{
double lat = location.getLatitude();
double lng = location.getLongitude();
gps.append("\n\nLocation lat: " +lat+
", long: " + lng+"\n"
+ getAddress(lat, lng));
}
}
public void onLocationChanged(Location location) {
showLocation(location);
}
public void onProviderDisabled(String provider) {
gps.append("\nProvider Disabled: " +provider);
}
public void onProviderEnabled(String provider) {
gps.append("\nProvider Enabled: " +provider);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
gps.append("\nProvider Status Changed: " + provider+ ",status: "+
status);
}
public String getAddress(double lat, double lng)
{
Geocoder geocoder = new Geocoder(this);
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String str = obj.getCountryName();
str+="\n" + obj.getCountryCode();
str+="\n" + obj.getLocality(); //current city
str+="\n" + obj.getAddressLine(0);
return str;
}
catch (IOException e) {
return "Error: " +e.getMessage();
}
}
1)You need to request updates from provider:
newLocation = requestUpdatesFromProvider(
LocationManager.GPS_PROVIDER, "error string");
2)Register a Listener:
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//Do something
} );}

Categories

Resources