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
Related
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)
{
///
}
}
i am trying to get location from both network provider and gps.By using the returned latitude and longitude i am placing markers on map. When i tried with network provider app is working fine.But when i tried to get location from gps, for the first time it is returning null. After that it is giving me exact location result. How to get rid from this.?
I think some minor changes i have to made, please suggest me in fixing this.
this is how i am doing this.
public class MapActivity extends Activity implements LocationListener {
private GoogleMap gMap;
private LocationManager locationManager;
private String provider;
boolean gps_enabled = false;
boolean netwrk_enabled = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
gMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
//Focussing india on starting map
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
23.40276491, 77.51953125), 5));
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 10F, this);
gps_enabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
netwrk_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (gps_enabled)
provider = LocationManager.GPS_PROVIDER;
else
provider = LocationManager.NETWORK_PROVIDER;
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
CameraPosition cp = new CameraPosition(new LatLng(
location.getLatitude(), location.getLongitude()), 14, 40, 90);
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cp), 4000,
null);
gMap.addMarker(new MarkerOptions().position(
new LatLng(location.getLatitude(), location.getLongitude()))
.title("I am here"));
if (location != null) {
if (provider == LocationManager.GPS_PROVIDER)
Toast.makeText(getApplicationContext(), "taking from gps",
Toast.LENGTH_SHORT).show();
else if (provider == LocationManager.NETWORK_PROVIDER)
Toast.makeText(getApplicationContext(), "taking from network",
Toast.LENGTH_SHORT).show();
new HttpGetTask().execute();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub18d1:d002
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
private class HttpGetTask extends AsyncTask<Void, Void, String> {
//Passing latitude and longitude here to get lat longs from my remote server.
// using json parsing i am placing multiple markers here.
}
}
Everything you code is write, But you are not calling LocationManager on starting of Application. Just un comment the following line from your code from your onCreate() method.
//Location location = locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 10F, this);
Uncomment above line and make following change for provider
Location location = locationManager.requestLocationUpdates(provider, 5000L, 10F, this);
I'm trying to get the current location and sending its LAt and LON to another class.But my application is not getting the current location it is showing the LAST LOCATION.Please help me out how to get the current location using GPS and NETWORK provider.
Below is the code:
public class location implements LocationListener
{
private LocationManager mgr;
private String best;
Location location;
public static double myLocationLatitude;
public static double myLocationLongitude;
public void locUpdate(Context context)
{
mgr = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
// criteria.setAccuracy(Criteria.ACCURACY_COARSE);
best = mgr.getBestProvider(criteria, true);
mgr.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,0,0,this);
try{
Location location = mgr.getLastKnownLocation(best);
Intent i = new Intent();
i.setClass(context,sentsms.class);
i.putExtra("latitude", location.getLatitude());
i.putExtra("longitude", location.getLongitude());
i.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Launch the new activity and add the additional flags to the intent
context.getApplicationContext().startActivity(i);
}
catch(Exception e)
{
}
}
public void onLocationChanged(Location location) {
dumpLocation(location);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
protected void onPause()
{
// super.onPause();
mgr.removeUpdates(this);
}
protected void onResume() {
// super.onResume();
mgr.requestLocationUpdates(best, 15000, 10, this);
}
private void dumpLocation(Location l) {
if (l != null){
myLocationLatitude = l.getLatitude();
myLocationLongitude = l.getLongitude();
}
}
}
From the docs for getLastKnownLocation():
Returns a Location indicating the data from the last known location
fix obtained from the given provider.
This can be done without starting the provider. Note that this
location could be out-of-date, for example if the device was turned
off and moved to another location.
If the provider is currently disabled, null is returned.
This means getLastKnownLocation() will retrieve the Location based on the last fix of the Provider. If you want updated Locations, use the Location received in onLocationChanged()
Please try this way
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);
if (provider != null) {
location = locationManager.getLastKnownLocation(provider);
// locationManager.requestLocationUpdates(provider, 1000*60*60,
// 1000, this);
// update only in 1 hour and 1 km of distance
locationManager.requestLocationUpdates(provider, 100, 1, this);
}
I'm tring to get the location from the gps/netwrok by best provider but always it's return the same location, also i can see that on google map there is a sign to my right location.
please anyone can tell me what i'm doing wrong?
My activity is:
public class MainMenu2 extends Activity implements LocationListener, OnClickListener
on my onCreate i have:
if(isGooglePlay()){
setContentView(R.layout.menu_2);
setUpMapIfNeeded();
}
isGooglePlay method:
private boolean isGooglePlay() { // looks if googlemaps is available
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(status == ConnectionResult.SUCCESS){
return true;
}
else{
((Dialog) GooglePlayServicesUtil.getErrorDialog(status, this, 10)).show();
//Toast.makeText(this, "Google Play is not available", Toast.LENGTH_SHORT).show();
return(false);
}
}//isGooglePlay
setUpMapIfNeeded method:
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.menu_map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
// The Map is verified. It is now safe to manipulate the map.
mMap.setMyLocationEnabled(true);
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(ACCURACY_FINE);
provider = locationManager.getBestProvider(criteria, true);
if (provider == null){
onProviderDisabled(provider);
}
locationManager.requestLocationUpdates(provider, 100, 1, this);
loc = locationManager.getLastKnownLocation(provider);
//---here the privider is "gps" but always the same location---//
if (loc != null){
onLocationChanged(loc);
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); // set Map Type
}
}
}//setUpMap
and override methods:
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng latlng = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
double pLong = location.getLongitude();
double pLat = location.getLatitude();
Latstr = String.valueOf(pLong);
Lngstr = String.valueOf(pLat);
latitude = pLat;
longitude = pLong;
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Please turn ON the GPS", Toast.LENGTH_SHORT).show();
}
#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
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
myLatLng = new LatLng(latitude,longitude);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(myLatLng, 15);
mMap.animateCamera(update);
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude,longitude )).title("Find me here!"));
}
i also tried to search here for similer problem but i didn't got nothing..
There is a bug with LocationProvider on some platforms like Samsung, custom Android build. You need to call this code (which actually does nothing), which triggers the phone's background cache to update its current location.
If you dont believe me, change your Gps position to a different location about 200m away, load your app, you dont notice the location gps change. Now, just load Maps app on your phone and suddenly your app will show current location.
To do this trigger programmatically put these lines just before your getLastKnownLocation call.
HomeScreen.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) {
}
});
Edit
OR
Use the new api's LocationClient instead of LocationProvider.
I am using location listener in my app.
I have the code like:
public void startlistning()
{
locationListener = new LocationListener() {
#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
Toast.makeText( getApplicationContext(),"Gps Enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Disabled", Toast.LENGTH_SHORT ).show();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
location.getLatitude();
location.getLongitude();
}
};
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
But don't know why the method onLocationChanged did not call when I restart device 1st time (without cellular data (no simcard) available). however, I am using best provider in my app.
Please look into matter. Thanks
Location listener method call when you change the location of device . Its not start when you restart device . If you want to invoke onLocationChanged method you have to change the location of device .
Please try this to get last known location.
LocationManager 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 location = locationManager.getLastKnownLocation(providerName);
Log.i("--- Latitude",""+location.getLatitude());
Log.i("--- Latitude",""+location.getLongitude());