I am trying to get latitude and longitude but sometime network is available but I am not getting value of latitude and longitude. I am using MyLocationListener class and put condition all but some time value is not getting.
protected void showCurrentLocation()
{
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null)
{
counter++;
latitude=location.getLatitude();
longitude=location.getLongitude();
altitude=location.getAltitude();
}
}
private class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location)
{
counter++;
latitude=location.getLatitude();
longitude=location.getLongitude();
altitude=location.getAltitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle b)
{
}
#Override
public void onProviderDisabled(String s)
{
}
#Override
public void onProviderEnabled(String s)
{
}
}
Here Best way to get Longitude Latitude:
/** PROCESS for Get Longitude and Latitude **/
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d("msg", "changed Loc : "+longitude + ":"+latitude);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if(isGPSEnabled){
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d("msg", "Loc : "+longitude + ":"+latitude);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}else
{
/*
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(true);
String provider = locationManager.getBestProvider(criteria, true);
*/
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null)
{
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}else
{
longitude = "0.00";
latitude = "0.00";
}
}
}
if device is not able to get currentLocation using GPS then it'll be take fron NetworkProvider or else it'll take 0,0 as my requirement but you can modify as per your requirement
May it'll helpful to you.
Happy Coding :D
See, this is a very common problem. In order to have exact Latitude and Longitude ,You must use GPS also it must me activated on the mobile device but GPS too have some limitations. GPS works most efficiently under open sky. you will not have a clear range inside a building. So try your code under open sky and check the response.
Related
How i am getting location details:
AppLocationService appLocationService = new AppLocationService(getApplicationContext());
Location nwLocation= appLocationService.getLocation(LocationManager.NETWORK_PROVIDER);
nwLocation.getLatitude();
nwLocation.getLongitude();
What is happening since my code has llast known location .... its giving me the last location that was updated say now its evening. its giving me the location updated during morning
What i want:: how can i make a fresh network request to get the current location at my position
AppLocationService.java
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 0;
private static final long MIN_TIME_FOR_UPDATE = 0;
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;
}
}
Your code is registering to receive location updates and also returns the last known location. What happens is expected because you didn't wait to receive an updated one.
Once the method "onLocationChanged" was called by the system you'll have the new one. You can then send a broadcast from the service.
You are trying to get the current location in a synchronous mode which is not possible as it takes some time to lookup the updated one.
The primary reason why you aren't getting updated location information quickly is that you're relying on the NETWORK_PROVIDER.
You should instead use this
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
How to call Explicitly onLocationChanged
public void locationlist()
{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER,
50, 0, this);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {}
if(location == null)
{
}
else{
lat = (double) (location.getLatitude());
lng = (double) (location.getLongitude());
}
}
now call the method locationlist where you want like in a timer.
Use onLocationChanged method and get the longitude and latitude from the parametr location
Code:
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = new Location(location);
latitude=mCurrentLocation .getLatitude();
longitude=mCurrentLocation .getLongitude();
}
I have a simple class GPSListener which gets the GPS coordinates:
public class GPSListener implements LocationListener {
public static double latitude;
public static double longitude;
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.d("GPSLISTENER ", "lat: "+latitude+" long:"+longitude);
} ...
Then trying to make use of this class in my activity, I simply invoke the class in my onCreate() function in my activity:
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new GPSListener();
Criteria criteria = new Criteria();
String bestProvider = mlocManager.getBestProvider(criteria, false);
mlocManager.requestLocationUpdates(bestProvider, 0, 0, mlocListener);
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
lat = GPSListener.latitude;
lon = GPSListener.longitude;
Log.d("GPS", "lat: "+lat+" long:"+lon);
} else {
// TODO: GPS not enabled
Log.d("GPSERROR", "GPS not enabled");
}
But whenever I run the application, lat and lon in my activity are always zero. I'm not quite sure how to get around this issue.
When logging:
Log.d("GPSLISTENER ", "lat: "+latitude+" long:"+longitude);
It returns the correct latitude and longitude, it just takes a second or two after the activity starts.
Log.d("GPSSUCCESS", "lat: "+lat+" long:"+lon);
Just returns 0.0 for both. I was under the impression that .requestLocationUpdates would pass the value to lat and lon before the if statement is executed. How can I accomplish this?
You are using public static field for latitude, longitude.
Please change it to non static and using setter, getter with instant object:
lat = mlocListener.getLatitude();
lon = mlocListener.getLongitude();
Google updated its location handling logic. It is now easier to listen location updates with fused location provider. You can implement your location listener in 5 min. Take a look.
Methods for getting the most accurate location
You are listening only gps provider and it is not ready(on waiting for location status) yet and then it does not return any location. Just take a look at fused location provider and write your location listener again.
try this...
mGoogleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick()
{
try
{
Location myLocation = mGoogleMap.getMyLocation();
onLocationChanged(myLocation);
}
catch (Exception e)
{
Log.getStackTraceString(e);
}
return false;
}
});
user this Handler to get Location
private Handler customHandler = new Handler();
private Runnable updateTimerThread = new Runnable() {
#Override
public void run()
{
try
{
Location myLocation = mGoogleMap.getMyLocation();
secndLocationListener.onLocationChanged(myLocation);
}
catch (Exception e)
{
Log.getStackTraceString(e);
}
}
};
to run this
customHandler.postDelayed(updateTimerThread , 1000);
LocationManager uses the last known location from the cache. The cache is updated when you load google maps. Try this out, go out in the open and check your location. Move to a different location about 200m and check your location again. It will be same as the old one. Now, load google maps, you will notice that you application magically now has the new location.
You need to programmatically kick that cache to the latest location. The only way to do that is
YOUR_APPLICATION_CONTEXT.getLocationManager().requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(final Location location) {
}
});
This is my code. Please tell me y it is not able to calculate the distance.. In this code res is a long variable which is supposed to store the total distance covered. This code is supposed to calculate distance based on GPS as soon as there is a change in the latitude and longitude..
String serviceString = Context.LOCATION_SERVICE;
LocationManager locationManager;
locationManager= (LocationManager)getSystemService(serviceString);
String provider = LocationManager.GPS_PROVIDER;
final Location loc1=locationManager.getLastKnownLocation(provider);
//Location loc1=new Location("");
String netprovider=LocationManager.NETWORK_PROVIDER;
lat1=loc1.getLatitude();
lon1=loc1.getLongitude();
LocationListener myLocationListener = new LocationListener()
{
public void onLocationChanged(Location loc1)
{
Location loc2=new Location("");
lat2=loc2.getLatitude();
lon2=loc2.getLongitude();
dtvalue.setText(lat1+","+lon1+","+lat2+","+lon2);
Location.distanceBetween(lat1,lon1,lat2,lon2,dist);
res=res+(long)dist[0];
lat1=lat2;
lon1=lon2;
}
public void onProviderDisabled(String provider)
{
// Update application if provider disabled.
}
public void onProviderEnabled(String provider)
{
// Update application if provider enabled.
}
public void onStatusChanged(String provider, int status,
Bundle extras)
{
// Update application if provider hardware status changed.
}
};
locationManager.requestLocationUpdates(provider, 5000, 1, myLocationListener);
locationManager.requestLocationUpdates(netprovider, 5000, 1, myLocationListener);
The problem that you are defining an empty location Location loc2=new Location(""); and then using it.
You can define lat1 and lon1 in your class.
public void onLocationChanged(Location loc1)
{
if(lat1 != 0 && long1 != 0) {
Location.distanceBetween(lat1,lon1,loc1.getLatitude(),loc1.getLongitude(),dist);
res+=(long)dist[0];
}
lat1=loc1.getLatitude();
lon1=loc1.getLongitude();
}
I have implemented sample application for get the current location latitude longitude.If i lunch my application in emulator and i am sending latitude and longitude from Emulator Controls at eclipse then i am getting current location latitude and longitude which from emulator controls.If i lunch the same application in real device then i am not able to get current location latitude and longitude
I have implemented code for get the current location latitude and longitude as follows:
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 11, 11, mlocListener);
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
Log.v("11111","Latitude :"+loc.getLatitude());
Log.v("22222","Longitude :"+ loc.getLongitude());
}
}
From the above code i am not getting current location latitude and longitude in real android device.
How can i get current location latitude and longitude of real device?
please any body help me
GPS_PROVIDER does not work in bound place. So if gps_provider is enabled but you get null location you can replace provider from gps to NETWORK_PROVIDER.
prasad try this code ..by using this i am successfully getting lat long
private Location location = null;
private LocationManager locationManager = null;
locationManager = (LocationManager) context.getSystemService (Context.LOCATION_SERVICE);
Criteria locationCritera = new Criteria();
locationCritera.setAccuracy(Criteria.ACCURACY_FINE);
locationCritera.setAltitudeRequired(false);
locationCritera.setBearingRequired(false);
locationCritera.setCostAllowed(true);
locationCritera.setPowerRequirement(Criteria.NO_REQUIREMENT);
String providerName = locationManager.getBestProvider(locationCritera,
true);
location = locationManager.getLastKnownLocation(providerName);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
currentLocation = context.getSharedPreferences(PREFS_NAME, 0);
editor = currentLocation.edit();
}
public String getCurrentLatitude() {
try {
if (!currentLocation.getString("currentLatitude", "")
.equalsIgnoreCase(""))
return currentLocation.getString("currentLatitude", "");
else if (location.getLatitude() != 0.0)
return Double.toString(location.getLatitude());
else
return "0.0";
} catch (Exception e) {
e.printStackTrace();
}
return "0.0";
}
public String getCurrentLongitude() {
try {
if (!currentLocation.getString("currentLongitude", "")
.equalsIgnoreCase(""))
return currentLocation.getString("currentLongitude", "");
else if (location.getLongitude() != 0.0)
return Double.toString(location.getLongitude());
else
return "0.0";
} catch (Exception e) {
e.printStackTrace();
}
return "0.0";
}
are you trying on emulator or device. if you are trying in device then your device should have to be near window or in open place.
override these methods in your MyLocationListener. so that you can track your GPS status. check and see if you can get whats the problem
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Disabled",
Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
On a real device, you will have to be patient and wait for a fix from the satellites. This can take several minutes, even with a clear view of the sky.
For testing outside, you would be better advised to have a simple text box in your app, initialise it to something like "No GPS fix yet", then send a string comprised of the lat/long coordinates to it when the location changes.
Maybe this is more clear. I will change the conditional to something more efficient later if it is possible
double longitude = 0;
double latitude = 0;
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) != null) {
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
} else {
Location location = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
}
There are two types of location providers,
GPS Location Provider
Network Location Provider
package com.shir60bhushan.gpsLocation;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.util.Log;
public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
#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");
}
}
This Link can help you for more information
http://androidtutorials60.blogspot.in/2013/09/gps-current-location-of-device.html
I tried to implement the code found in this link location find
The truth is I want to get my location using network or GPS, ( I tested it on Network)
private Location getCurrentLocation(){
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
myGeoPoint = GeoTools.makeGeoPoint(mLatitude, mLongitude);
mapController.animateTo(myGeoPoint);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
String locationProvider = LocationManager.NETWORK_PROVIDER;
// Or use LocationManager.GPS_PROVIDER
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if(lastKnownLocation==null){
locationProvider = LocationManager.GPS_PROVIDER;
// Or use LocationManager.GPS_PROVIDER
lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
}
return lastKnownLocation;
}
How to return the result:
myLocation = getCurrentLocation();
if(myLocation != null)
{
mLatitude = myLocation.getLatitude();
mLongitude = myLocation.getLongitude();
myGeoPoint = GeoTools.makeGeoPoint(mLatitude, mLongitude);
mapController.animateTo(myGeoPoint);
}else {
mLatitude = 36.859502;
mLongitude = 10.168097;
myGeoPoint = GeoTools.makeGeoPoint(mLatitude, mLongitude);
mapController.animateTo(myGeoPoint);}
This wasn't the only code i tried and i dont found any result on a android 2.2 phone.
Any idea about how can i fix it
i check most of the tutorials on the net!!
First check whether did you add the following permissions or not.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
The second thing is that you should give some time to locate location info.You can do that using timer task or posDelayed.
private Location getCurrentLocation(){
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
t.cancel();
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
myGeoPoint = GeoTools.makeGeoPoint(mLatitude, mLongitude);
mapController.animateTo(myGeoPoint);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
Location lastKnownLocation;
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
this.cancel();
lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if(lastKnownLocation==null){
locationProvider = LocationManager.GPS_PROVIDER;
// Or use LocationManager.GPS_PROVIDER
lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
return lastKnownLocation;
}
},30000);
}
it will give you results after 30seconds.
After a long research, I found my pleasur Here :)
Hope this will help someone.