How to get current accurate location using GPS provider? - android

i need current location of user with the help of GPS provider.
Currently i'm getting GPS location, but in some devices i'm not getting location.
I also tried last known location and network location, but they are not accurate.
So please help by providing better solution.
My current code:
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
MapsInitializer.initialize(getActivity());
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
final double latitude = location.getLatitude();
final double longitude = location.getLongitude();
if (getActivity() == null){
return;
}
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
List<Address> fromLocation = geocoder.getFromLocation(latitude, longitude, 1);
Address address = null;
if (fromLocation != null && fromLocation.size() > 0) {
address = fromLocation.get(0);
final String locality = address.getLocality();
if (dataSend != null) {
dataSend.onDataSend(address);
}
fragmentMapBinding.map.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(latitude, longitude);
googleMap.clear();
CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 19, 0, 0));
googleMap.animateCamera(cameraUpdate);
googleMap.getUiSettings().setZoomGesturesEnabled(false);
googleMap.getUiSettings().setScrollGesturesEnabled(false);
googleMap.addMarker(new MarkerOptions().position(latLng).title("Your Location"));
}
});
}
} catch (IOException e) {
Log.e(TAG, "getMap", e);
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Toast.makeText(getActivity(), s + " : " + i, Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
}
};
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);

Related

Geocoder goes good in an Activity and in another returns null always

I am working in a app with maps, in the first activity I have a NavigationDrawer with differents fragments, in one of them I get the last Location every 10 seconds and with it set a TextView with the address of that location. Everything was going perfect since I create a new Activity for details of a Place with a MapView and when you put a Marker it get its address, but it always return null I don´t know why..
There is my code.
1rst Activity with Fragment
public void setLocationListeners() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSION_LOCATION);
} else {
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Location lastLocation = locationResult.getLastLocation();
Address address = getAddress(lastLocation.getLongitude(), lastLocation.getLatitude(), getContext());
myLocation = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());
if (address == null) {
((TextView) mView.findViewById(R.id.txtVosEstas)).setText(String.valueOf(
lastLocation.getLongitude() + " " + lastLocation.getLatitude()));
} else
((TextView) mView.findViewById(R.id.txtVosEstas)).setText(address.getAddressLine(0).split(",")[0]);
((TextView) mView.findViewById(R.id.txtBearing)).setText(String.valueOf(lastLocation.getBearing()));
((TextView) mView.findViewById(R.id.txtVelocidad)).setText(String.valueOf(lastLocation.getSpeed()));
}
};
}
}
"getAddress" is the static method in my MapHelper
public static Address getAddress(double lng, double lat, Context c) {
Geocoder geocoder = new Geocoder(c, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
return addresses.get(0);
} catch (IOException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException e) {
}
return null;
}
I call the same method in the other Activity when the map is ready.
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(latLng));
String lat = String.format("%.7f", latLng.latitude);
String lng = String.format("%.7f", latLng.longitude);
((TextView) findViewById(R.id.txtLat)).setText(lat);
((TextView) findViewById(R.id.txtLng)).setText(lng);
Address address = getAddress(Double.valueOf(lat), Double.valueOf(lng), getApplicationContext());
((MultiAutoCompleteTextView) findViewById(R.id.txtDireccion)).setText(address != null? address.getAddressLine(0) : "Sin dirección");
}
});
if (mLugar != null){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mLugar.getLatLng(), 15));
MarkerOptions marker = new MarkerOptions()
.position(mLugar.getLatLng())
.title(mLugar.getNombre());
mMap.addMarker(marker);
}
}
And in it I never get results.

No Location Provider Found in Lollipop and Marshmallow

I working with a project to find the address using latitude and longitude. I got answer in Jellybean but when comes to Lollipop and Marshmallow it only showing latitude and longitude, not getting address. It shows location provider is not found. Is there any error in my code?
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mprovider = locationManager.getBestProvider(criteria, false);
if (mprovider != null && !mprovider.equals("")) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(mprovider);
locationManager.requestLocationUpdates(mprovider,5000, 0,this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (location != null)
onLocationChanged(location);
else
Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onLocationChanged(Location location) {
TextView longitude = (TextView) findViewById(R.id.textView);
TextView latitude = (TextView) findViewById(R.id.textView1);
longitude.setText("Current Longitude:" + location.getLongitude());
latitude.setText("Current Latitude:" + location.getLatitude());
Geocoder geo = new Geocoder(getApplicationContext(), Locale.getDefault());
// String mylocation;
try {
List < Address > addresses = geo.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
address1.setText(address);
String city = addresses.get(0).getLocality();
textViewCity.setText(city);
String state = addresses.get(0).getAdminArea();
textViewState.setText(state);
String country = addresses.get(0).getCountryName();
textViewCountry.setText(country);
String postalCode = addresses.get(0).getPostalCode();
textViewPostal.setText(postalCode);
String knownName = addresses.get(0).getFeatureName();
System.out.println("Address >> " + address + " " +city+ " \n" + state + " \n" + country+ "\n"+postalCode+ "\n"+knownName);
}
} catch (IOException e) {
e.printStackTrace();
}
add this class.
public class SingleShotLocationProvider {
public static interface LocationCallback {
public void onNewLocationAvailable(GPSCoordinates location);
}
// calls back to calling thread, note this is for low grain: if you want higher precision, swap the
// contents of the else and if. Also be sure to check gps permission/settings are allowed.
// call usually takes <10ms
public static void requestSingleUpdate(final Context context, final LocationCallback callback) {
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestSingleUpdate(criteria, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}, null);
} else {
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestSingleUpdate(criteria, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
}
#Override public void onStatusChanged(String provider, int status, Bundle extras) { }
#Override public void onProviderEnabled(String provider) { }
#Override public void onProviderDisabled(String provider) { }
}, null);
}
}
}
// consider returning Location instead of this dummy wrapper class
public static class GPSCoordinates {
public float longitude = -1;
public float latitude = -1;
public GPSCoordinates(float theLatitude, float theLongitude) {
longitude = theLongitude;
latitude = theLatitude;
}
public GPSCoordinates(double theLatitude, double theLongitude) {
longitude = (float) theLongitude;
latitude = (float) theLatitude;
}
}
}
and use like this:
SingleShotLocationProvider.requestSingleUpdate(getActivity(),
new SingleShotLocationProvider.LocationCallback() {
#Override
public void onNewLocationAvailable(SingleShotLocationProvider.GPSCoordinates location) {
lat = location.latitude;
lag = location.longitude;
}
});
here you can get lat - lag if your device location is enable. so also check that is enable or not.
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showEnableLocationDialog();
} else {
SingleShotLocationProvider.requestSingleUpdate(getActivity(),
new SingleShotLocationProvider.LocationCallback() {
#Override
public void onNewLocationAvailable(SingleShotLocationProvider.GPSCoordinates location) {
lat = location.latitude;
lag = location.longitude;
}
});
}
public void showEnableLocationDialog() {
final android.app.AlertDialog.Builder builderDialog = new android.app.AlertDialog.Builder(getActivity());
builderDialog.setTitle("Enable Location");
builderDialog.setMessage("Please enable location for near by search");
builderDialog.setPositiveButton("Enable",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
});
builderDialog.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//fetchImages();
}
});
android.app.AlertDialog alert = builderDialog.create();
alert.show();
}
and i hope you are asking run-time permission for location first. otherwise you will never get location.

Google map to find current location and nearby places

I want to add a Google Maps plugin in my Android app to fetch the current location of a user and show nearby hospitals.
How to fetch the current location and nearby places? Could somebody give me a direction on it?
Please follow the following code you will get nearby hospitals it's working.:)
You Can change this type at your own will, e.g hospital, cafe, restaurant.... and see how it all works:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,
LocationListener {
private GoogleMap mMap;
LocationManager locationManager;
CoordinatorLayout mainCoordinatorLayout;
String type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable()) {
return;
}
setContentView(R.layout.activity_maps);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
type="hospital";
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mainCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.mainCoordinatorLayout);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showLocationSettings();
}
}
private void showLocationSettings() {
Snackbar snackbar = Snackbar
.make(mainCoordinatorLayout, "Location Error: GPS Disabled!",
Snackbar.LENGTH_LONG)
.setAction("Enable", new View.OnClickListener() {
#Override public void onClick(View v) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
snackbar.setActionTextColor(Color.RED);
snackbar.setDuration(Snackbar.LENGTH_INDEFINITE);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView
.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
showCurrentLocation();
}
private void showCurrentLocation() {
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
private void loadNearByPlaces(double latitude, double longitude) {
StringBuilder googlePlacesUrl =
new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=").append(latitude).append(",").append(longitude);
googlePlacesUrl.append("&radius=").append(PROXIMITY_RADIUS);
googlePlacesUrl.append("&types=").append(type);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + GOOGLE_BROWSER_API_KEY);
JsonObjectRequest request = new JsonObjectRequest(googlePlacesUrl.toString(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject result) {
Log.i(TAG, "onResponse: Result= " + result.toString());
parseLocationResult(result);
}
},
new Response.ErrorListener() {
#Override public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: Error= " + error);
Log.e(TAG, "onErrorResponse: Error= " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(request);
}
private void parseLocationResult(JSONObject result) {
String id, place_id, placeName = null, reference, icon, vicinity = null;
double latitude, longitude;
try {
JSONArray jsonArray = result.getJSONArray("results");
if (result.getString(STATUS).equalsIgnoreCase(OK)) {
mMap.clear();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject place = jsonArray.getJSONObject(i);
id = place.getString(SUPERMARKET_ID);
place_id = place.getString(PLACE_ID);
if (!place.isNull(NAME)) {
placeName = place.getString(NAME);
}
if (!place.isNull(VICINITY)) {
vicinity = place.getString(VICINITY);
}
latitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION)
.getDouble(LATITUDE);
longitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION)
.getDouble(LONGITUDE);
reference = place.getString(REFERENCE);
icon = place.getString(ICON);
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(latitude, longitude);
markerOptions.position(latLng);
markerOptions.title(placeName + " : " + vicinity);
mMap.addMarker(markerOptions);
}
Toast.makeText(getBaseContext(), jsonArray.length() + " Supermarkets found!",
Toast.LENGTH_LONG).show();
} else if (result.getString(STATUS).equalsIgnoreCase(ZERO_RESULTS)) {
Toast.makeText(getBaseContext(), "No Supermarket found in 5KM radius!!!",
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "parseLocationResult: Error=" + e.getMessage());
}
}
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title("My Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
loadNearByPlaces(latitude, longitude);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
}
Here is the xml file.
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<fragment android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</FrameLayout>
its workind at my side. please add the api key and enjoy it.Hope this help:)

Updating user's location

I'm having some trouble with Google Maps. I need to display user's location on the map and then update it. I'm using a default marker. However, the way my code is currently set up, it adds a new marker every time OnLocationChanged is called. I want it to just update that one marker or remove old one as it adds a new one with current location. Here's the code:
public class GoogleMapActivity extends FragmentActivity implements LocationListener {
Double longitude_user, latitude_user;
LatLng koordinate_user;
GoogleMap supportMap;
String title, address, type;
BitmapDescriptor bdf;
private LocationManager locationManager;
private String provider;
Location location;
Marker marker;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_googlemaps);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
supportMap = fm.getMap();
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.GPS_PROVIDER;
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
provider = locationManager.NETWORK_PROVIDER;
}
if (provider == null){
provider = locationManager.getBestProvider(criteria, false);
}
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Log.i("test", "Location not available");
}
location = locationManager.getLastKnownLocation(provider);
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 1000, 10, this);
//Log.i("test", "Provider: " + provider);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
latitude_user = location.getLatitude();
longitude_user = location.getLongitude();
if (latitude_user != null && longitude_user != null) {
koordinate_user = new LatLng(latitude_user, longitude_user);
marker = supportMap.addMarker(new MarkerOptions()
.position(koordinate_user));
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
Update your onLocationChanged method by this
#Override
public void onLocationChanged(Location location) {
latitude_user = location.getLatitude();
longitude_user = location.getLongitude();
if (latitude_user != null && longitude_user != null) {
if(marker != null)
marker.remove();
koordinate_user = new LatLng(latitude_user, longitude_user);
marker = supportMap.addMarker(new MarkerOptions()
.position(koordinate_user));
}
}
Hope this is what you wanted.
you can update user location onLocationchanged method....
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
if (latitude != null && longitude != null) {
if(marker != null)
marker.remove();
latlng = new LatLng(latitude, longitude);
marker = supportMap.addMarker(new MarkerOptions()
.position(latlng));
}
}

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