I want to know a way to search for current location limited by a timer.
During that timer, the app should search various possibilities for current location which they will be filtered to get the best estimation.
Basically, I'm trying to do this:
Enable GPS providers;
Inside a runnable code, request updates to location from them, and then execute some way to filtered and obtain the best estimation;
The runnable should execute during a predefined timer or if the user cancel the search, it should stop.
Anyone have any idea to do this? Thanks.
this is globle variable
Location loc;
double latitude;
double longitude;
LocationManager mLocationManager;
this is bind location manager
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
100, 3, mLocationListener);
this class
private final LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
// your code here
latitude = location.getLatitude();//set here your current location latitude & longitude.
longitude = location.getLongitude();
Log.e(KEY_TAG, "Lat " + latitude + "Long " + longitude);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
};
when user location is change that a time to you will get the new lat long.
Related
I am facing a problem, I am trying to show current location on map. When I use wifi, it works fine, but when I turn the GPS on, it stops showing it, again I turn off GPS it works.. what shall I do, I need to show my location as well as the GPS.
my code is:
SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_test);
// Getting Google Map
mGoogleMap = fragment.getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
mGoogleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
// TODO Auto-generated method stub
System.out.println("STREEEETTT111: "+db.getIdn(arg0.getTitle()));
Intent i=new Intent(MapTest.this,PharmacyDetails.class);
i.putExtra("name", arg0.getTitle());
startActivity(i);
}
});
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
and I want to attach the screenshots to make my question more clear:
When the GPS is off:
And when the GPS is on:
Please help, thankx
I am new in android developing, and so intrested in getting location of users!!!!!
You may know that we can access users location by two types:
GPS (ACCESS_FINE_LOCATON)
Network based (ACCESS_COARSE_LOCATION)
My Question is:
I Want to get the location(latittude & longitude) of user by GPS. But, if the user has turned GPS Off/GPS isn't supported, then i want to get user's location by Network, or, Network-based location
.
Hope you understood my question....
Any help is accepted
Try the following code:
LocationManager mlocManager;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
//if condition to check if GPS is available
if (mlocManager .isProviderEnabled(LocationManager.GPS_PROVIDER)) { mlocManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,
mlocListener, null);
}
else if (mlocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
mlocManager.requestSingleUpdate(
LocationManager.NETWORK_PROVIDER, mlocListener, null);
}
//this is the class to get the location.
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
try {
//you may store these values where ever required.
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
When you use the FusedLocationProviderApi as used in the getting the last known location training and receiving location updates training, it will automatically fall back to network location if GPS is not available.
Hope get GPS code helps you.
if (Common.getIsGPSEnabled()) {
final LocationManager locationManager = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener;
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
myLocation = locationManager.getLastKnownLocation(locationProvider);
Toast.makeText(c, "location changed, My location is removed to"
+ myLocation.getLatitude()+","+myLocation.getLongitude(), Toast.LENGTH_LONG).show();
Latitude = myLocation.getLatitude();
Longitude = myLocation.getLongitude();
}
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);
locationManager.requestLocationUpdates(locationProvider, (long)0, (float)0, locationListener);
myLocation = locationManager.getLastKnownLocation(locationProvider);
if(myLocation != null)
{
///
}
}
suppoose I have my current location which is changeable and I dont know the hard code value of the latitude and longitude. now I have a string from where I want to get the Address object from that string using getFromLocationName() method, I have used this code:
address = coder.getFromLocationName(strAddress, maxNum);
but this returns list of address from allover the globe, but I want the results near to my locations come first, and then rest of the world, how do I sort it? I have found another method like this:
getFromLocationName (String locationName, int maxResults, double lowerLeftLatitude, double lowerLeftLongitude, double upperRightLatitude, double upperRightLongitude);
but I dont know what to put in these latitude longitude parameters to fulfill my wish. Anyone?
/*********** Create class and implements with LocationListener ******/
public class GpsBasicsAndroidExample extends Activity implements LocationListener {
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps_basics_android_example);
/********** get Gps location service LocationManager object *****/
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
/* CAL METHOD requestLocationUpdates */
// Parameters :
// First(provider) : the name of the provider with which to register
// Second(minTime) : the minimum time interval for notifications,
// in milliseconds. This field is only used as a hint
// to conserve power, and actual time between location
// updates may be greater or lesser than this value.
// Third(minDistance) : the minimum distance interval for notifications, in meters
// Fourth(listener) : a {#link LocationListener} whose onLocationChanged(Location)
// method will be called for each location update
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,
3000, // 3 sec
10, this);
/********* After registration onLocationChanged method **/
/********* called periodically after each 3 sec *****/
}
/************* Called after each 3 sec ****/
#Override
public void onLocationChanged(Location location) {
String str = "Latitude: "+location.getLatitude()+"
Longitude: "+location.getLongitude();
Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
/******** Called when User off Gps ***/
Toast.makeText(getBaseContext(), "Gps turned off ", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
/******** Called when User on Gps ***/
Toast.makeText(getBaseContext(), "Gps turned on ", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
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) {
}
});
Inside
public class IAmHere extends Activity implements LocationListener {
i have
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
and
inside
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.iamhere);
i have
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
gpsString = (TextView)findViewById(R.id.gpsString);
String Data = "";
String koordinata1 = Double.toString(gps[0]);
String koordinata2 = Double.toString(gps[1]);
Data = Data + koordinata1 + " | " + koordinata2 + "\n";
gpsString.setText(String.valueOf(Data));
but seems it's not working? Why? I mean even emulator doesn't want to send GPS data - When I click "send" via UI or console, nothing happens...?
Thank you.
First, you implemented LocationListener on IAmHere, then did nothing with that interface.
Second, you are calling getLastKnownLocation(), but you are doing nothing to trigger Android to start collection location data on any provider.
These two problems are related.
Location services are off until something registers to get location data from them. Typically, this is via requestLocationUpdates() on LocationManager...which uses the LocationListener interface you implemented.
The recipe for using LocationManager is:
Register a LocationListener via requestLocationUpdates()
Unregister the LocationListener sometime (e.g., onDestroy()), so that you do not leak memory
When location fixes come into onLocationChanged(), do something useful
Here is a sample project that uses LocationManager and LocationListener in this fashion.