Android location updates Google Maps every second - android

I want to display location updates every second in android. The problem is that with this code on one mobile phone the location is updated every 30-40 seconds and on another one every 5-6 seconds. How can i solve the problem to update every second? What is wrong in my code? I have the following code
private LocationManager mLocationManager = null;
private String provider = LocationManager.GPS_PROVIDER;
private void locateCurrentPosition() {
int status = getActivity().getPackageManager().checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
getActivity().getPackageName());
if (status == PackageManager.PERMISSION_GRANTED) {
Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (ApplicationState.choice_gps_loc == 0&&location!=null) {
ApplicationState.latitude = String.valueOf(location.getLatitude());
ApplicationState.longitude = String.valueOf(location.getLongitude());
addBoundaryToCurrentPosition(Double.parseDouble(ApplicationState.latitude)
, Double.parseDouble(ApplicationState.longitude), map);
}
Log.e("Location", "nuuuu");
// mLocationManager.addGpsStatusListener(this);
long minTime = 1000;// ms
float minDist = 1.0f;// meter
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
this);
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
}
private boolean isProviderAvailable() {
mLocationManager = (LocationManager) getActivity().getSystemService(
Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
provider = mLocationManager.getBestProvider(criteria, true);
if (mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
return true;
}
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
return true;
}
if (provider != null) {
return true;
}
return false;
}
private void updateWithNewLocation(Location location) {
if (location != null && provider != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
Log.e("alta", lng + " " + lat);
if (ApplicationState.choice_gps_loc == 0)
addBoundaryToCurrentPosition(lat, lng, map);
// CameraPosition camPosition = new CameraPosition.Builder()
// .target(new LatLng(lat, lng)).zoom(10f).build();
if (ApplicationState.choice_gps_loc == 0) {
ApplicationState.latitude = String.valueOf(lat);
ApplicationState.longitude = String.valueOf(lng);
}
if (myMarker != null) myMarker.remove();
myMarker = map.addMarker(new MarkerOptions()
.title("My position/my future destination")
.position(new LatLng(Double.parseDouble(ApplicationState.latitude),
Double.parseDouble(ApplicationState.longitude)))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
//if (map != null)
// map.animateCamera(CameraUpdateFactory
// .newCameraPosition(camPosition));
} else {
Log.d("Location error", "Something went wrong");
}
}
public void addBoundaryToCurrentPosition(double lat, double lang, GoogleMap map1) {
if (updatecerc == 0) {
if (mOptions != null) mOptions.visible(false);
mOptions = new CircleOptions()
.center(new LatLng(lat, lang)).radius(Integer.parseInt(ApplicationState.radius) * 1000)
.strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF);
map1.addCircle(mOptions);
updatecerc++;
}
}
#Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
#Override
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
case LocationProvider.AVAILABLE:
break;
}
}

Related

Fetching latitude and longitude programmaticaly in android always getting GPS LastKnownLocation null

Hello all i know this question is too old and there are many of them but none of the solution is working for me. I am fetching latitude and longitude programmaticaly i tried below code but what is happening is for GPS every time i am getting LastKnownLocation = null also my GPS is enabled on my device, i tried this code on different devices where on some of them i am able to get latitude and longitude from GPS but for most of them it is showing null. I don't know why this code is failing for most of the cases, if any one of you know anything about this or any better way of doing it then please tell me i have spent almost a week digging what's wrong in the above code but nothing help me out.
UPDATE- Is google's FusedLocationApi free or there is limited requests per day ??
public class GPSTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isGPSEnabled) {
Log.d("gps", "gpsenabled");
if (location == null) {
Log.d("gps", "location is null");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
Log.d("gps", "locationManager is not null");
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Log.d("gps", "location is not null");
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("gps", "lat: " + latitude + ", lon: " + longitude);
}
}
}
}
if (isNetworkEnabled) {
Log.d("gps", "networkenabled");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
Log.d("gps", "locationManager is not null");
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.d("gps", "location is not null");
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("gps", "lat: " + latitude + ", lon: " + longitude);
}
}
}
//
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = lm.getBestProvider(criteria, false);
Log.d("gps", "bestProvider: " + bestProvider);
Location location = lm.getLastKnownLocation(bestProvider);
Log.d("gps", "lat: " + location.getLatitude() + ", lon: " + location.getLongitude());
//
}
} catch (Exception e) {
}
return location;
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
latitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to setttings menu ?");
alertDialog.setPositiveButton("Setting", 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) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
this.location = location;
latitude = getLatitude();
longitude = getLongitude();
Log.d("gps", "onLocationChanged");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}

Can't Get Location using LocationManager in Background Service

I have created an application that stores your location in database at periodic time in Background service but, it doesn't get location. my code is...
public class LocationService extends Service {
private Double myLat, myLong;
private Location location;
private LocationManager locManager;
private LocationListener locationListener;
private boolean NETWORK_ENABLED, GPS_ENABLED, PASSIVE_ENABLED;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(getApplicationContext(), "Service Created", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
myLat = 0.00;
myLong = 0.00;
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LocationService.this.location = location;
LocationService.this.myLat = location.getLatitude();
LocationService.this.myLong = location.getLongitude();
Toast.makeText(getApplicationContext(), "onLocationChanged", Toast.LENGTH_LONG).show();
insertToDatabase();
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {}
};
getMyCurrentLocation();
}
private void getMyCurrentLocation() {
location = null;
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
NETWORK_ENABLED = false; GPS_ENABLED = false; PASSIVE_ENABLED = false;
NETWORK_ENABLED = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (NETWORK_ENABLED) {
Toast.makeText(getApplicationContext(), "Network Provider", Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 45 * 1000l, 1f, locationListener);
}
if (location == null) {
//setGPSOn();
GPS_ENABLED = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(GPS_ENABLED) {
Toast.makeText(getApplicationContext(), "GPS Provider", Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0l, 1f, locationListener);
}
//setGPSOff();
}
if (location == null) {
PASSIVE_ENABLED = locManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
if(PASSIVE_ENABLED) {
Toast.makeText(getApplicationContext(), "Passive Provider", Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0l, 1f, locationListener);
}
}
try {
location = locManager.getLastKnownLocation(locManager.getBestProvider(new Criteria(), true));
} catch(NullPointerException e) {}
if (location != null) {
myLat = location.getLatitude();
myLong = location.getLongitude();
insertToDatabase();
} else {
Location loc = null;
try {
loc = getLastKnownLocation(this);
} catch(NullPointerException e) {}
if (loc != null) {
myLat = loc.getLatitude();
myLong = loc.getLongitude();
insertToDatabase();
}
}
locManager.removeUpdates(locationListener);
}
private Location getLastKnownLocation(Context context) {
Location location = null;
LocationManager locationmanager = (LocationManager)context.getSystemService("location");
List<?> list = locationmanager.getAllProviders();
boolean i = false;
Iterator<?> iterator = list.iterator();
do {
if(!iterator.hasNext())
break;
String s = (String)iterator.next();
if(i != false && !locationmanager.isProviderEnabled(s))
continue;
Location location1 = locationmanager.getLastKnownLocation(s);
if(location1 == null)
continue;
else {
float f = location.getAccuracy();
float f1 = location1.getAccuracy();
if(f >= f1) {
long l = location1.getTime();
long l1 = location.getTime();
if(l - l1 <= 600000L)
continue;
}
}
location = location1;
i = locationmanager.isProviderEnabled(s);
} while (true);
return location;
}
}
this doesn't give me any location.... and my app is also doesn't Crash or gives any Exception.
I have properly register all permissions in Manifest file...
ACCESS_COARSE_LOCATION
ACCESS_FINE_LOCATION
I can't find what to do?
any help will be appreciated
thanks in advance for Help...
I think your problem is that you remove the listener right away:
locManager.removeUpdates(locationListener); // comment this one out
in getMyCurrentLocation();
You should try to remove your listener in some other places.

Getting Longitude and Latitude using Google maps v2

How do i get longitude longitude of my current phone location using Google maps v2?
I use this method to zoom on my device place:
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
Now how do i get the coordinates?
I know this method to get an area:
double left = vr.latLngBounds.southwest.longitude;
double top = vr.latLngBounds.northeast.latitude; ...
You can get the center Lat and Lng values from google maps via this code
LatLng latLng = map.getCameraPosition().target;
double lat = latLng.latitude;
double lng = latLng.longitude;
The Google Maps API location has listeners, for example:
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new
GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = gMap.addMarker(new MarkerOptions().position(loc));
if(gMap != null){
gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
and then set the listener for the map:
gMap.setOnMyLocationChangeListener(myLocationChangeListener);
This will get called when the map first finds the location.
try this code.
Use This:
private boolean gps_enabled = false;
private boolean network_enabled = false;
private Location location;
private void getMyCurrentLocation() {
Double MyLat = null, MyLong = null;
String CityName = "";
String StateName = "";
String CountryName = "";
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locListener = new MyLocationListener();
try {
gps_enabled = locManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
// if(!gps_enabled && !network_enabled)
// return false;
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locListener);
}
if (gps_enabled) {
location = locManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if (network_enabled && location == null) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
0, 0, locListener);
}
if (network_enabled && location == null) {
location = locManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location != null) {
MyLat = location.getLatitude();
MyLong = location.getLongitude();
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
MyLat, MyLong), 15));
} else {
Location loc = getLastKnownLocation(this);
if (loc != null) {
MyLat = loc.getLatitude();
MyLong = loc.getLongitude();
}
}
locManager.removeUpdates(locListener); // removes the periodic updates
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
if (location != null) {
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
public static Location getLastKnownLocation(Context context) {
Location location = null;
LocationManager locationmanager = (LocationManager) context
.getSystemService("location");
List list = locationmanager.getAllProviders();
boolean i = false;
Iterator iterator = list.iterator();
do {
if (!iterator.hasNext())
break;
String s = (String) iterator.next();
if (i != false && !locationmanager.isProviderEnabled(s))
continue;
Location location1 = locationmanager.getLastKnownLocation(s);
if (location1 == null)
continue;
if (location != null) {
float f = location.getAccuracy();
float f1 = location1.getAccuracy();
if (f >= f1) {
long l = location1.getTime();
long l1 = location.getTime();
if (l - l1 <= 600000L)
continue;
}
}
location = location1;
i = locationmanager.isProviderEnabled(s);
} while (true);
return location;
}

jumping location on google maps by gps. (inaccurate distance)

my app should display the distance and location in real time when the user walked, but there are errors with my output.
the distance did not start immediately but when it start it increase a lot until it slows down a bit.
the red marker and blue dot should be together according to one example I've seen but they are separate in my app. both of them point my current location right?
both red marker and blue dot jumps around in a short time that i was not moving that is away from my true location. which i believe lead to the inaccuracy of the distance as well.
please see my output for more details
java code
public class MainActivity extends FragmentActivity implements LocationListener{
protected LocationManager locationManager;
private GoogleMap googleMap;
Button btnStartMove,btnPause,btnResume,btnStop;
static double n=0;
Long s1,r1;
double dis=0.0;
Thread t1;
EditText userNumberInput;
boolean bool=false;
int count=0;
double speed = 1.6;
double lat1,lon1,lat2,lon2,lat3,lon3,lat4,lon4;
double dist = 0;
TextView distanceText;
float[] result;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES =1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 3000; //in milliseconds
boolean startDistance = false;
boolean firstTime = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
if(isGooglePlay())
{
setUpMapIfNeeded();
}
distanceText=(TextView)findViewById(R.id.Distance);
btnStartMove=(Button)findViewById(R.id.Start);//start moving
//prepare distance...........
Log.d("GPS Enabled", "GPS Enabled");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
Location location=locationManager.getLastKnownLocation(provider);
btnStartMove.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
startDistance = true;
// lat3 = location.getLatitude();
// lon3 = location.getLongitude();
}
});
if(location!= null)
{
//Display current location in Toast
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(MainActivity.this, message,
Toast.LENGTH_LONG).show();
//Display current location in textview
//latitude.setText("Current Latitude: " + String.valueOf(location.getLatitude()));
//longitude.setText("Current Longitude: " + String.valueOf(location.getLongitude()));
//lat3 = location.getLatitude();
//lon3 = location.getLongitude();
}
else if(location == null)
{
Toast.makeText(MainActivity.this,
"Location is null",
Toast.LENGTH_LONG).show();
}
}
private void setUpMapIfNeeded() {
if(googleMap == null)
{
Toast.makeText(MainActivity.this, "Getting map",
Toast.LENGTH_LONG).show();
googleMap =((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.displayMap)).getMap();
if(googleMap != null)
{
setUpMap();
}
}
}
private void setUpMap()
{
//Enable MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
//Get locationManager object from System Service LOCATION_SERVICE
//LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
if(provider == null)
{
onProviderDisabled(provider);
}
//set map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Get current location
Location myLocation = locationManager.getLastKnownLocation(provider);
if(myLocation != null)
{
onLocationChanged(myLocation);
}
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
private boolean isGooglePlay()
{
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status == ConnectionResult.SUCCESS)
{
Toast.makeText(MainActivity.this, "Google Play Services is available",
Toast.LENGTH_LONG).show();
return(true);
}
else
{
GooglePlayServicesUtil.getErrorDialog(status, this, 10).show();
}
return (false);
}
#Override
public void onLocationChanged(Location myLocation) {
System.out.println("speed " + myLocation.getSpeed());
// if(myLocation.getSpeed() > speed)
// {
//show location on map.................
//Get latitude of the current location
double latitude = myLocation.getLatitude();
//Get longitude of the current location
double longitude = myLocation.getLongitude();
//Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
//Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!"));
//show distance............................
if(startDistance == true)
{
Toast.makeText(MainActivity.this,
"Location has changed",
Toast.LENGTH_LONG).show();
if(myLocation != null)
{
//latitude.setText("Current Latitude: " + String.valueOf(loc2.getLatitude()));
//longitude.setText("Current Longitude: " + String.valueOf(loc2.getLongitude()));
float[] results = new float[1];
Location.distanceBetween(lat3, lon3, myLocation.getLatitude(), myLocation.getLongitude(), results);
System.out.println("Distance is: " + results[0]);
dist += results[0];
DecimalFormat df = new DecimalFormat("#.##"); // adjust this as appropriate
if(count==1)
{
distanceText.setText(df.format(dist) + "meters");
}
lat3=myLocation.getLatitude();
lon3=myLocation.getLongitude();
count=1;
}
}
startDistance=true;
//}
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
}}
there seem to be no way to solve my error.i was recommeded to use location.getSpeed but it returns 0.

How to get complete details of current location using GPS & Location Manager

I am using GPS to get longitude and latitude of a location, but now I want to get each and every detail of location like: country, city, state, zip code, street number and so on.
Maximum details of current location.
Code:
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
String country;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled
(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation
(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation
(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
private void initmainIntent() {
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
if (location != null) {
Geocoder gcd = new Geocoder(getApplicationContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
if (addresses.size() > 0) {
String s = "Address Line: "
+ addresses.get(0).getAddressLine(0) + "\n"
+ addresses.get(0).getFeatureName() + "\n"
+ "Locality: "
+ addresses.get(0).getLocality() + "\n"
+ addresses.get(0).getPremises() + "\n"
+ "Admin Area: "
+ addresses.get(0).getAdminArea() + "\n"
+ "Country code: "
+ addresses.get(0).getCountryCode() + "\n"
+ "Country name: "
+ addresses.get(0).getCountryName() + "\n"
+ "Phone: " + addresses.get(0).getPhone()
+ "\n" + "Postbox: "
+ addresses.get(0).getPostalCode() + "\n"
+ "SubLocality: "
+ addresses.get(0).getSubLocality() + "\n"
+ "SubAdminArea: "
+ addresses.get(0).getSubAdminArea() + "\n"
+ "SubThoroughfare: "
+ addresses.get(0).getSubThoroughfare()
+ "\n" + "Thoroughfare: "
+ addresses.get(0).getThoroughfare() + "\n"
+ "URL: " + addresses.get(0).getUrl();
locationNotFound.setVisibility(View.GONE);
locationFound.setVisibility(View.VISIBLE);
foundLocationText.setText(s);
}
} catch (IOException e) {
e.printStackTrace();
}
background(location.getLatitude(), location.getLongitude());
}
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);
}
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled = false;
boolean network_enabled = false;
public boolean getLocation(Context context, LocationResult result) {
// I use LocationResult callback class to pass location value from
// MyLocation to user code.
locationResult = result;
if (lm == null)
lm = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
// exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled)
return false;
if (gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationListenerGps);
if (network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
if (location != null) {
System.out.println(location.getLatitude());
}
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
}
Here is the Tutorial to Get Current location and City name using GPS
Once you get GPS co-ordinates
By using Geocoder class you can every details
See below code snip is for getting Current City Same way you can go for other details also.
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(
getBaseContext(),
"Location changed : Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
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);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Currrent City is: "
+ cityName;
editLocation.setText(s);
}
#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
}
}
Update (as per comment)
If you want to send this details to any contact via SMS.
I would say this page may help you
Using this code you can find the address like street, State, Country and Pin.
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geoCoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
String address = "";
if (addresses != null && addresses.size() >= 0) {
address = addresses.get(0).getAddressLine(0);
if (addresses != null && addresses.size() >= 1) {
address += ", " + addresses.get(0).getAddressLine(1);
}
if (addresses != null && addresses.size() >= 2) {
address += ", " + addresses.get(0).getAddressLine(2);
}
}
And you need to run this code in separate thread or in AsyncTask because it will internally call the network connection.
I somehow spent many hours to complete this task. In the below code the onMapReady device location is detected and shows a marker at that location. On click on the marker the location address is shown.
public class StoreFinder extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentUserLocationMarker;
private static final int Request_User_Location_Code = 99;
private double latitude;
double longitude;
private int ProximityRadius = 10000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_location);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkUserLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
public boolean checkUserLocationPermission()
{
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
}
return false;
}
else
{
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
switch (requestCode)
{
case Request_User_Location_Code:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
if (googleApiClient == null)
{
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}
else
{
Toast.makeText(this, "Permission Denied...", Toast.LENGTH_SHORT).show();
}
return;
}
}
protected synchronized void buildGoogleApiClient()
{
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
lastLocation = location;
if (currentUserLocationMarker != null)
{
currentUserLocationMarker.remove();
}
/*----------to get City-Name from coordinates ------------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(latitude, latitude, 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getAddressLine(0);
} catch (IOException e) {
e.printStackTrace();
}
String s = cityName;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(s);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
currentUserLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(16));
if (googleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle)
{
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, (LocationListener) this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}

Categories

Resources