GPS: loc.getLatitude/Longitude always results in 0.0 - android

I used this tutorial to write my app. I use the DDMS Location Manager to change my location virtually.
Unfortunally I always get a location of 0.0 for long and lat. Even if I switch them later in the prog with locationchanged-method I get 0.0.
Code is this:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//---use the LocationManager class to obtain GPS locations---
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastLoc = lm.getLastKnownLocation("gps");
curLocation = "Standort: \nLatitude: " + lastLoc.getLatitude() + "\nLongitude: " + lastLoc.getLongitude();
upperText = (TextView) findViewById(R.id.TextView01);
upperText.setText(curLocation);
}
and
#Override
public void onLocationChanged(Location loc)
{
if (loc != null) {
Toast.makeText(getBaseContext(),
"Location changed : Lat: " + loc.getLatitude() +
" Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
}
if (loc != null)
{
upperText.setText(curLocation + "\n\nStandort: \nLatitude: " + loc.getLatitude()
+ "\nLongitude: " + loc.getLongitude());
}
}
Something's missing, but I don't know what... :/
I'd be really pleased if anyone could help =)!

go to maps default application and allow user to allow latitude and longitude option .In our application when the GPS signal blinks and when it stops we will get the latitude and longitude.It worked for me

Related

How to switch from Gps to network provider?

Need some help. I am making an app where i get location updates from either gps or network provider. If gps is not enabled then i gave the button to enable the gps. Now what i need to do is to take updates from gps, if the gps can't get a signal then i switch over to network provider and take location updates and as soon as gps is available the switch to gps again and calculate the distance the user has travelled. I got multiple questions.
What does the getProvider and getBestProvider methods do? I think it provides the best provider that is available to the phone (correct me if i am wrong) and how can i use it to get location updates.
I need to know what providers are enabled when the user launches the app. How can i do that? I used isProviderEnabled but got confused when enabling or disabling the wifi it gives me nothing.
I tried some conditions if gps not enabled then switch to network provider but this doesn't do anything. I read many posts regarding this but couldn't figure out how to use it in my code. Any help would be greatly appreciated. Thanks. Here is my code.
public class MainActivity extends Activity {
public boolean getLocation() {
try {
isGps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
isNetwork_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
//don't start listeners if no provider is enabled
if (!isGps_enabled && !isNetwork_enabled)
return false;
if (isGps_enabled)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
if (isNetwork_enabled)
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
accu = (TextView) findViewById(R.id.accu);
speed1 = (TextView)findViewById(R.id.speed);
t = (TextView)findViewById(R.id.t);
prevLatLon = (TextView) findViewById(R.id.prevLatLon);
distance = (TextView)findViewById(R.id.distance);
listView = (ListView)findViewById(R.id.listView);
listText = (TextView)findViewById(R.id.listText);
settings = (Button)findViewById(R.id.settings_button);
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
List<String> providers = locationManager.getProviders(criteria, true);
for (String provider: providers){
distance.setText("Providers: " + provider);
}
provider = locationManager.getBestProvider(criteria, false);
/*isGps_enabled = locationManager.isProviderEnabled(provider);
Toast.makeText(this, isGps_enabled + "", Toast.LENGTH_SHORT).show();
isNetwork_enabled = locationManager.isProviderEnabled(provider);
Toast.makeText(this, isNetwork_enabled + "", Toast.LENGTH_SHORT).show();*/
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location loc) {
//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
getLocation();
int accuracy = (int) loc.getAccuracy();
speed = (int) loc.getSpeed();
accu.setText("Accuracy: " + accuracy);
speed1.setText("Speed: " + speed);
t.setText("Time: " + loc.getTime());
listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.activity_simplelist, R.id.listText, list));
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date(loc.getTime());
String formatted = format.format(date);
if (flag == 0) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
speed = (int) loc.getSpeed();
time = formatted;
distanceInMeters = 0;
distanceTo = 0;
distanceBetween = 0;
timestamp = loc.getTime();
timestampmsec = 0;
hours = 0;
minutes = 0;
seconds = 0;
startTime = loc.getTime();
flag = 1;
list.add("latitude: " + latitude + " longitude: " + longitude +
" \nspeed: " + speed + " Time: " + time + "\nDistance: " + distanceInMeters + " meters"
+ "\ntimestamp: " + timestamp);
}
else {
prevLatitude = latitude;
prevLongitude = longitude;
prevSpeed = speed;
prevTime = time;
prevDistanceInMeters = distanceInMeters;
prevDistanceTo = distanceTo;
prevDistanceBetween = distanceBetween;
//prevTimestamp = timestamp;
prevTimestampmsec = timestampmsec;
prevHours = hours;
prevMinutes = minutes;
prevSeconds = seconds;
prevLatLon.setText("Previous Latitude: " + prevLatitude + "\nPrevious Longitude: " + prevLongitude +
" \nPrevious speed: " + prevSpeed + " \nTime: " + prevTime + "\nPrevious Timestamp: " + prevTimestamp);
latitude = loc.getLatitude();
longitude = loc.getLongitude();
speed = (int) loc.getSpeed();
time = formatted;
timestamp = loc.getTime();
if (loc.hasSpeed()) {
Toast.makeText(MainActivity.this, "true", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "false", Toast.LENGTH_SHORT).show();
}
getDistance();
distanceTo = androidDistanceTo(prevLatitude, prevLongitude, latitude, longitude);
Location.distanceBetween(prevLatitude, prevLongitude, latitude, longitude, results);
distanceBetween = results[0];
list.add("latitude: " + latitude + " longitude: " + longitude +
" \nspeed: " + speed + " Time: " + time + "\nDistance: " + distanceInMeters + " meters"
+ "\nTimestamp: " + timestamp);
speed = prevSpeed + speed;
distanceInMeters = prevDistanceInMeters + distanceInMeters;
distanceTo = prevDistanceTo + distanceTo;
distanceBetween = prevDistanceBetween + distanceBetween;
timestampmsec = (long) (timestamp - startTime);
seconds = TimeUnit.MILLISECONDS.toSeconds(timestampmsec);
if(seconds >= 60) {
minutes = (int) seconds / 60;
seconds = seconds % 60;
}
if(minutes >= 60){
hours = (int) minutes / 60;
minutes = minutes % 60;
}
}
distance.setText("Distance: " + distanceInMeters + " meters" + "\nDistanceTo: " + distanceTo + " meters" +
"\nDistanceBetween: " + distanceBetween + " meters" + "\nTime: " + hours + " hours " +
minutes + " minutes " + seconds + " seconds");
Toast.makeText(MainActivity.this, "Location Changed", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String arg0) {
//TODO auto generated method stub
Toast.makeText(MainActivity.this, provider + " disabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String arg0) {
//TODO auto generated method stub
Toast.makeText(MainActivity.this, provider + " enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
//TODO auto generated method stub
}
};
}
public void getDistance(){
double dLat = Math.toRadians(latitude - prevLatitude);
double dLon = Math.toRadians(longitude - prevLongitude);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(prevLatitude))
* Math.cos(Math.toRadians(latitude)) * Math.sin(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
distanceInMeters = (6372800 * c);
}
public static double androidDistanceTo(double lat_a, double lng_a, double lat_b, double lng_b) {
Location locationA = new Location("Point A");
locationA.setLatitude(lat_a);
locationA.setLongitude(lng_a);
Location locationB = new Location("Point B");
locationB.setLatitude(lat_b);
locationB.setLongitude(lng_b);
return (locationA.distanceTo(locationB));
}
public void resetButton(View view) {
list.clear();
listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.activity_simplelist, R.id.listText, list));
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 30000, 0, locationListener);
}
#Override
protected void onPause() {
super.onPause();
//locationManager.removeUpdates(locationListener);
}
getBestProvider does the following:
Returns the name of the provider that best meets the given criteria.
Only providers that are permitted to be accessed by the calling
activity will be returned. If several providers meet the criteria, the
one with the best accuracy is returned. If no provider meets the
criteria, the criteria are loosened in the following sequence: power requirement, accuracy, bearing, speed, altitude
getProvider does the following:
Returns the information associated with the location provider of the
given name, or null if no provider exists by that name.
In layman's terms you choose the provider with getProvider and the system chooses the provider with getBestProvider
You can find out what providers are enabled by looking at isProviderEnabled
Your code for starting the listeners looks fine. But you don't actually call getLocation() anywhere other than onResume() and onLocationChanged() You need to move that call out of onLocationChanged() and put it towards the end of onCreate()

saving the state of activity when the layout changes

i need to save my all variables and text views to display all values when i change my layout to landscape. can anybody help me out? i tried to save somethings in the onsavedInstanceState method but it won't save anything. here is my code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
accu = (TextView) findViewById(R.id.accu);
speed1 = (TextView)findViewById(R.id.speed);
t = (TextView)findViewById(R.id.t);
prevLatLon = (TextView) findViewById(R.id.prevLatLon);
listView = (ListView)findViewById(R.id.listView);
listText = (TextView)findViewById(R.id.listText);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onLocationChanged(Location loc) {
//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
accuracy = (int) loc.getAccuracy();
listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.activity_simplelist, R.id.listText, list));
accu.setText("Accuracy: " + accuracy);
speed1.setText("Speed: " + speed);
t.setText("Time: " + time);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date(loc.getTime());
String formatted = format.format(date);
if(flag == 0){
latitude = loc.getLatitude();
longitude = loc.getLongitude();
speed = (int) loc.getSpeed();
time = formatted;
flag = 1;
list.add("latitude: " + latitude + " longitude: " + longitude +
" \nspeed: " + speed + " Time: " +time);
}
else {
prevLatitude = latitude;
prevLongitude = longitude;
prevSpeed = speed;
prevTime = time;
prevLatLon.setText("Previous Latitude: " + latitude + "\nPrevious Longitude: " + longitude +
" \nPrevious speed: " + speed + " \nTime: " + time);
latitude = loc.getLatitude();
longitude = loc.getLongitude();
speed = (int) loc.getSpeed();
time = formatted;
list.add("latitude: " + latitude + " longitude: " + longitude +
" \nspeed: " + speed + " Time: " + time);
speed = prevSpeed + speed;
}
/*currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
currentLat = currentLocation.getLatitude();
currentLon = currentLocation.getLongitude();*/
//list.add("speed: " + speed + " accuracy: " + accuracy);
Toast.makeText(MainActivity.this, "Location Changed", Toast.LENGTH_SHORT).show();
}
i tried this
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
accu.setText("Accuracy: " + accuracy);
speed1.setText("Speed: " + speed);
t.setText("Time: " + time);
prevLatLon.setText("Previous Latitude: " + latitude + "\nPrevious Longitude: " + longitude +
" \nPrevious speed: " + speed + " \nTime: " + time);
savedInstanceState.putDouble("latitude", latitude);
savedInstanceState.putDouble("longitude", longitude);
savedInstanceState.putDouble("prevLatitude", prevLatitude);
savedInstanceState.putDouble("prevLongitude", prevLongitude);
savedInstanceState.putDouble("speed", speed);
savedInstanceState.putDouble("accuracy", accuracy);
// etc.
}
When you save something using the onSaveInstanceState you are supposed to retrieve them later on either on the onRestoreInstanceState or using the onCreate(Bundle).
On the onCreate of your activity do this code:
onCreate(Bundle bundle)
{
/* ... */
if (bundle == null)
{
//Initialize data
data = 0;
} else
{
//Load data from the bundle (the same way you saved them)
data = bundle.getInt("MY_DATA", 0); //0 is default value
}
}
Alternatively you can use the onRestoreInstanceState(Bundle) method which guarantees that bundle will always be non-null. I'm not sure which of the two is better for which case, but both work.

How to get location update for every half an hour android?

hi i have developed an android application for getting location and sending it to server it is working good but location update is not working it is currently running once i have to get location and send to server once in half an hour, and this process should run only for 9 hrs to 17 hrs how can i do it pls help me..!
my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) { // if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String providerName = manager.getBestProvider(new Criteria(),
true);
Location location = manager.getLastKnownLocation(providerName);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation loc = (GsmCellLocation) mTelephonyManager
.getCellLocation();
String networkOperator = mTelephonyManager
.getNetworkOperator();
Log.d("CID", Integer.toString(loc.getCid()));
Log.d("LAC", Integer.toString(loc.getLac()));
int mcc = Integer.parseInt(networkOperator.substring(0, 3));
int mnc = Integer.parseInt(networkOperator.substring(3));
TextView tv1 = (TextView) findViewById(R.id.locationResults);
if (loc != null) {
tv1.setText("Cell ID: " + loc.getCid() + " , "
+ "Lac: " + loc.getLac() + "mcc : " + mcc
+ "mnc : " + mnc);
}
// manager.requestLocationUpdates(providerName, 1000 * 60 *
// 2, 0,this);
}
}
else {
String providerName = manager.getBestProvider(new Criteria(),
true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView) findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, "
+ location.getLongitude() + " longitude");
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();
String imei = telephonyManager.getDeviceId();
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyyMMdd_HHmmss");
String cdt = sdf.format(new Date());
double latitude = location.getLatitude();
double longitude = location.getLongitude();
String lat = Double.toString(latitude);
String lon = Double.toString(longitude);
String locations = Double.toString(latitude) + ","
+ Double.toString(longitude);
// manager.requestLocationUpdates(providerName, 1000 * 60 *
// 2, 0,this);
}
else {
TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation loc = (GsmCellLocation) mTelephonyManager
.getCellLocation();
String networkOperator = mTelephonyManager
.getNetworkOperator();
Log.d("CID", Integer.toString(loc.getCid()));
Log.d("LAC", Integer.toString(loc.getLac()));
int mcc = Integer.parseInt(networkOperator.substring(0, 3));
int mnc = Integer.parseInt(networkOperator.substring(3));
// TextView tv1 = (TextView)
// findViewById(R.id.locationResults);
if (loc != null) {
tv.setText("Cell ID: " + loc.getCid() + " , " + "Lac: "
+ loc.getLac() + "mcc : " + mcc + "mnc : "
+ mnc);
}
}
manager.requestLocationUpdates(providerName, 1000 * 60 * 10, 1,
this);
}
}
}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
// sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt(((lat - curStatLat) * (lat - curStatLat))
+ ((lon - curStatLon) * (lon - curStatLon)));
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView) findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, "
+ location.getLongitude() + " longitude");
} else {
tv.setText("Problem getting gps NETWORK ID : ");
}
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
You can use requestLocationUpdates of LocationManager Class
requestLocationUpdates (long minTime, float minDistance, Criteria
criteria, PendingIntent intent)
So, the first param you can specify as 30 mins according to your requirement.
To keep track of hours elapsed, you can have something like :
var1 = System.CurrentTimeMillis(); //Get time when service started
In onLocationChanged()
var2 = System.CurrentTimeMillis();
Now calculate var2-var1 to get elapsed time. if >17 hrs, removeUpdates from locationManager
I have a similar project going on, I am using a Service for this, fired by an AlarmManager.
Check here for more info.
The approach provided by Schaemelhout and the approach taken by library referred to in the comments is the only workable solution I have found.
Using an AlarmManager to wake your service guarantees the service is periodically invoked/restarted. This serves to counteract any power saving actions that the OS/phone might hit your service with in the mean time.
Registering a location listener from your alarm BroadcastReceiver wakes up the GPS (the GPS would not normally be running if the phone is asleep). In your alarm BroadcastReceiver you will need to take and hold a WakeLock and stay awake until results are passed back to the listener.
The down side to this approach is that it takes a while for a location to be available and the accuracy may be bad. Your service might have to wait a while until acceptable accuracy is achieved (the Location accuracy value can be wrong, so it might be be best to wait for a few samples). The whole approach will need to be tuned to your required update frequency and accuracy requirements. If you need very frequent and accurate updates I suspect holding a wake-lock and keeping the GPS alive might be the only way to go.
I also tried using the lm.requestLocationUpdates() using a PendingIntent. This did faithfully wake up my service and pass it an Intent, but if the GPS was sleeping prior to the wake up the Intent lacked a location.

Location changed notification android

I am just testing out the onLocationChanged method in Android , I have implemented a way that when I click a button the app returns a String with the new lat and lng values. But now I am trying to show the results automatically every time the location changes. This is what I have so far to do so:
location manager
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
int minTime = 30000;
LocationManager locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
MyLocationListener myLocListener = new MyLocationListener();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setSpeedRequired(false);
String bestProvider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(bestProvider, minTime, 1, myLocListener );
onlocationchanged
public void onLocationChanged(Location loc) {
if(loc != null){
lat1 = loc.getLatitude();
lng1 = loc.getLongitude();
currentlocation = "Location changed to lat: " + lat + "" + "lng: " + lng1 ;
Context context = getApplicationContext();
CharSequence text = currentlocation;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
I have set the requestlocationupdates method to request and update every 60000 millseconds
My problem is that the application never toasts the lat and lng values when the location changes. I have tested the app with the emulator and tried telneting the lat and lng values. And I have also drove around in my car to see if the values change.
Try:
currentlocation = "Location changed to lat: " + String.valueOf(lat1) + "" + "lng: " + String.valueOf(lng1) ;
and for test you can just use:
requestLocationUpdates(LocationManager.GPS_PROVIDER...

how to find longitude and latitude of particular location?

How to find Longitude and Latitude of Particular location?
the location is entered by user in edittext & click on search button then the location is display in googlemap.
i used following code for that but this is give error "Service not Available"
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
try {
address=geoCoder.getFromLocationName(txtlocation.getText().toString(), 1).get(0);
double longi=address.getLongitude();
double latit=address.getLatitude();
System.out.println("longitude:--- " +longi);
System.out.println("latitude:---" +latit);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MapRouteActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
try to use
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); double longitude = location.getLongitude(); double latitude = location.getLatitude();
The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { longitude = location.getLongitude(); latitude = location.getLatitude(); } }
lm.requestLocationUpdates(LocationManager.GPS, 2000, 10, locationListener);
You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.
You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.
try this code
public static String getLatLng(Context context,String addr){
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String add = "";
try{
List<Address> addresses = geocoder.getFromLocationName(addr, 5);
for(int i=0;i<1;i++){
Address obj = addresses.get(i);
for(int j=0;j<obj.getMaxAddressLineIndex();j++){
add = obj.getAddressLine(j);
add = add + "\nCountryName " + obj.getCountryName();
add = add + "\nCountryCode " + obj.getCountryCode();
add = add + "\nAdminArea " + obj.getAdminArea();
add = add + "\nPostalCode " + obj.getPostalCode();
add = add + "\nSubAdminArea " + obj.getSubAdminArea();
add = add + "\nFeatureName " + obj.getFeatureName();
add = add + "\nLocality " + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();
add = add + "\nurl " + obj.getUrl();
add = add + "\nLatitude " + obj.getLatitude();
add = add + "\nLongitude " + obj.getLongitude();
}
add = add+"\n";
}
Log.v("IGA", "Address" + add);
}catch(Exception e){
e.printStackTrace();
add = e.toString();
}
return add;
}

Categories

Resources