I want to calculate distance between two location one which is fixed and second one is user's location.
Here is my Activity where I want to calculate distance.
public class CalDist extends AsyncTask<String, Void, String> {
protected void onPreExecute(){
}
protected String doInBackground(String... arg0) {
StringBuilder stringBuilder = new StringBuilder();
Double dist = 0.0;
try {
//destinationAddress = destinationAddress.replaceAll(" ","%20");
//String url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+fromLatitude+","+fromLongitude+"&destination=" + toLatitude + "," + toLongitude + "&mode=driving&sensor=false&key=AIzaSyBpFhiStQvyV5dbVXmarXhzhvGgGFOfubM";
//String url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + fromLatitude + "," + fromLongitude + "&destination=" + toLatitude + "," + toLongitude + "&mode=driving&sensor=false&key=AIzaSyBpFhiStQvyV5dbVXmarXhzhvGgGFOfubM";
String url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+ fromLatitude + "," + fromLongitude + "&destinations=" + toLatitude + "," + toLongitude + "&mode=driving&sensor=false&key=HereIsMyAPIKey";
HttpPost httppost = new HttpPost(url);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
JSONArray array = jsonObject.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONObject distance = steps.getJSONObject("distance");
Log.i("Distance", distance.toString());
dist = Double.parseDouble(distance.getString("text").replaceAll("[^\\.0123456789]","") );
//Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Double.toString(dist);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(Payment.this, "ResultCalcDist:" +result, Toast.LENGTH_SHORT).show();
}
Here is how I am calling function.
new CalDist().execute();
Two points for distance calculation.
gps = new GPSTracker(Payment.this);
fromLatitude = gps.getLatitude();
fromLongitude = gps.getLongitude();
toLatitude = 23.1914909;
toLongitude = 72.630121;
Here is my GPS tracker from where I am getting latitude and longitude.
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
final private int REQUEST_LOCAION = 12;
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// 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;
// First get location from Network Provider
if (isNetworkEnabled) {
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) {
// 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.
android.support.v13.app.ActivityCompat.requestPermissions((Activity)getApplicationContext(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCAION);
}
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();
}
}
}
}
else
{
showSettingsAlert();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[],
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_LOCAION: {
if ((grantResults.length > 0) && (grantResults[0] +
grantResults[1]) == PackageManager.PERMISSION_GRANTED) {
//Call whatever you want
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
}
Please help me with this.
Related
Google map is not Displaying in the API level 23,24,25 but it is shown kitkat.Why is that Happening?
NearMe
public class NearMe extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
GpsLocation gpsLocation;
double longitude, latitude;
private ProgressDialog pDialog;
ArrayList<MySchool> al_school = new ArrayList<MySchool>();
ArrayList<MyCollege> al_college = new ArrayList<MyCollege>();
ArrayList<MyUniversity> al_university = new ArrayList<MyUniversity>();
private static final String TAG = NearMe.class.getSimpleName();
private static final String urlSchool = "http://www.myeducationhunt.com/api/v1/schools";
private static final String urlCollege = "http://www.myeducationhunt.com/api/v1/colleges";
private static final String urlUniversity = "http://www.myeducationhunt.com/api/v1/universities";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_near_me, container, false);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (isConnected()) {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(getContext(), "GPS is Enabled in your device", Toast.LENGTH_SHORT).show();
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
gpsLocation = new GpsLocation(getContext());
if (gpsLocation.canGetLocation()) {
longitude = gpsLocation.getLongitude();
latitude = gpsLocation.getLatitude();
Toast.makeText(getContext(), "latitude:" + latitude + "Longitude:" + longitude, Toast.LENGTH_LONG).show();
}
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Loading…");
pDialog.show();
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
LatLng schoollatlng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(schoollatlng).title("MyLocation"));
CameraPosition cameraPosition = new CameraPosition.Builder().target(schoollatlng).zoom(11).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
drawSchoolMarker();
drawCollegeMarker();
drawUniversityMarker();
}
});
}
else{
showGPSDisabledAlertToUser();
}
} else {
Toast.makeText(getContext(), "Please check your internet connection", Toast.LENGTH_LONG).show();
}
return v;
}
public boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
private void drawSchoolMarker() {
JsonArrayRequest schoolRequest = new JsonArrayRequest(urlSchool,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MySchool school = new MySchool();
school.setId("" + obj.getInt("id"));
school.setName("" + obj.getString("name"));
school.setLatitude(Double.parseDouble("" + obj.getDouble("latitude")));
school.setLongitude(Double.parseDouble("" + obj.getDouble("longitude")));
al_school.add(school);
} catch (JSONException e) {
e.printStackTrace();
}
}
//iterate from arraylist
for (MySchool school : al_school) {
View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker, null);
TextView numTxt = (TextView) marker.findViewById(R.id.num_txt);
numTxt.setText(school.getName());
LatLng latlng = new LatLng(school.getLatitude(), school.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker))).title(school.getName()));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(schoolRequest);
}
private void drawCollegeMarker() {
JsonArrayRequest collegeRequest = new JsonArrayRequest(urlCollege,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MyCollege college = new MyCollege();
college.setId("" + obj.getInt("id"));
college.setName("" + obj.getString("name"));
college.setLatitude(Double.parseDouble("" + obj.getDouble("latitude")));
college.setLongitude(Double.parseDouble("" + obj.getDouble("longitude")));
al_college.add(college);
} catch (JSONException e) {
e.printStackTrace();
}
}
//iterate from arraylist
for (MyCollege college : al_college) {
View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_college, null);
TextView numTxt = (TextView) marker.findViewById(R.id.txt_college);
numTxt.setText(college.getName());
LatLng latlng = new LatLng(college.getLatitude(), college.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker))).title(college.getName()));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(collegeRequest);
}
private void drawUniversityMarker() {
JsonArrayRequest uniRequest = new JsonArrayRequest(urlUniversity,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MyUniversity university = new MyUniversity();
university.setId("" + obj.getInt("id"));
university.setName("" + obj.getString("name"));
university.setLatitude(Double.parseDouble("" + obj.getDouble("latitude")));
university.setLongitude(Double.parseDouble("" + obj.getDouble("longitude")));
al_university.add(university);
} catch (JSONException e) {
e.printStackTrace();
}
}
//iterate from arraylist
for (MyUniversity university : al_university) {
View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_university, null);
TextView numTxt = (TextView) marker.findViewById(R.id.txt_university);
numTxt.setText(university.getName());
LatLng latlng = new LatLng(university.getLatitude(), university.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker))).title(university.getName()));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(uniRequest);
}
public static Bitmap createDrawableFromView(Context context, View view) {
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
private void showGPSDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
GpsLocation class
public class GpsLocation 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
double speed, direction;
// 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 GpsLocation(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;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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 TODO;
}
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) {
Log.d("Getting location", "Location found");
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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.removeUpdates(GpsLocation.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
public double getSpeed() {
return speed;
}
public double getDirection() {
return direction;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will launch Settings Options
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
speed = location.getSpeed();
direction = location.getBearing();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
is it showing ocean location.??
What is the exact issue i am not able to know and how can this be
resolved?
Your coordinates point to sea(check the values load them in browser and see where it points)? If yes the map might be opening in the ocean check your zoom level(zoom out a lot and see any change is there )
If not there is something wrong with your API Key double check that as well.
Further more go through Request runtime permissions
If you want an example check this > https://stackoverflow.com/a/34582595/5188159
i have develop app that when run take the city name by lat and long using a GPSTracker.java class and add this city name to url for retrive json data.
My code works very fine from API 18 to API 22 but now when i run my code on API 23 the geocoder doesn't work and city name is null
This is my code on Main Activity for retrive city name:
// To get City-Name from coordinates
GPSTracker gpsTracker = new GPSTracker(getActivity());
String cityName = null;
Geocoder gcd = new Geocoder(getContext(), Locale.ENGLISH);
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(gpsTracker.getLatitude(), gpsTracker.getLongitude(), 1);
if (addresses.size() > 0) {
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
Log.d("nome_cit", "debug_cit " + cityName);
// Controllo formattazione nomi Car2Go
if(cityName.equals("Rome")) {
nome_citta = "Roma";
}else if (cityName.equals("Florence")){
nome_citta = "Firenze";
}
else if (cityName.equals("Milan")){
nome_citta = "Milano";
}
else if (cityName.equals("Turin")){
nome_citta = "Torino";
}else if (cityName.equals("New York")){
nome_citta = "NewYorkCity";
}else if (cityName.equals("Los Angeles")){
nome_citta = "LosAngeles";
}
else if (cityName.equals("San Diego")){
nome_citta = "SanDiego";
}
else if (cityName.equals("Twin Cities")){
nome_citta = "TwinCities";
}
else if (cityName.equals("Vienna")) {
nome_citta = "wien";
}
else if (cityName.equals("Munich")) {
nome_citta = "München";
}
else if (cityName.equals("Osler")) {
nome_citta = "Rheinland";
}
// Controllo formattazione JCDecaux
else if (cityName.equals("Valencia")) {
nome_citta_test = "Valence";
}
else if (cityName.equals("Parigi")) {
nome_citta_test = "Paris";
}
else if (cityName.equals("Besançon")){
nome_citta_test = "Besancon";
}
else if (cityName.equals("Créteil")) {
nome_citta_test = "Creteil";
}
else {
nome_citta = cityName;
nome_citta_test = cityName;
}
}
else {
}
} catch (IOException e) {
e.printStackTrace();
}
on my map for my position i have set this permission:
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager
.PERMISSION_GRANTED && ActivityCompat
.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager
.PERMISSION_GRANTED) {
/*Toast.makeText(getActivity(),
"Need location permission for map.setMyLocationEnabled(true);",
Toast.LENGTH_LONG).show();*/
MultiplePermissionsListener snackbarMultiplePermissionsListener =
SnackbarOnAnyDeniedMultiplePermissionsListener.Builder
.with((ViewGroup) getView(), "La app ha bisogno di ablitare i permessi di localizzaione per mostrare la mappa")
.withOpenSettingsButton("Settings")
.withCallback(new Snackbar.Callback() {
#Override
public void onShown(Snackbar snackbar) {
// Event handler for when the given Snackbar has been dismissed
}
#Override
public void onDismissed(Snackbar snackbar, int event) {
// Event handler for when the given Snackbar is visible
}
})
.build();
Dexter.checkPermissions(snackbarMultiplePermissionsListener, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE, Manifest.permission.GET_ACCOUNTS);
return;
}
and this is my GPSTracker.java class:
public final class GPSTracker implements LocationListener {
private final Context mContext;
// flag for GPS status
public 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
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
/**
* Function to get the user's current location
*
* #return
*/
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.v("isGPSEnabled", "=" + isGPSEnabled);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.v("isNetworkEnabled", "=" + isNetworkEnabled);
if (isGPSEnabled == false && isNetworkEnabled == false) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
location=null;
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) {
location=null;
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();
// DecimalFormat latitude = new DecimalFormat("00.00");
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle(R.string.title);
// Setting Dialog Message
alertDialog
.setMessage(R.string.subtitle);
// On pressing Settings button
alertDialog.setPositiveButton(R.string.impostazioni,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton(R.string.cancella,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setCancelable(false);
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Also i have notice that using place picker on API 23 i recive this error:
Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
for this code:
if (resultCode == getActivity().RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(getActivity(), data);
String addresses = place.getAddress().toString();
if (addresses != null) {
puntoA.setText(addresses);
}if (addresses.isEmpty()){
addresses = "(" + place.getLatLng().latitude + "," + place.getLatLng().longitude + ")";
puntoA.setText("nessun indirizzo disponibile " + addresses);
}
//puntoA.setText(addresses);
// Recupero coordinate
Geocoder geocoder = new Geocoder(getActivity());
List<Address> address = null;
try {
address = geocoder.getFromLocationName(addresses, 1);
} catch (IOException e) {
e.printStackTrace();
}
if(address.size() > 0) {
Lat = address.get(0).getLatitude();
Lon = address.get(0).getLongitude();
}
else if (address.size() == 0) {
Lat = place.getLatLng().latitude;
Lon = place.getLatLng().longitude;
}
but also this function works very well on other API version
Any help please?
now my code works fine on API 23 and i use this code:
// To get City-Name from coordinates
GPSTracker gpsTracker = new GPSTracker(getActivity());
Double LatFab = gpsTracker.getLatitude();
Double LonFab = gpsTracker.getLongitude();
List<Address> geocodeMatchess = null;
String Country_;
try {
geocodeMatchess = new Geocoder(getActivity(), Locale.ENGLISH).getFromLocation(gpsTracker.getLatitude(), gpsTracker.getLongitude(), 1);
if (geocodeMatchess.isEmpty()) {
}else {
Country_ = geocodeMatchess.get(0).getLocality();
citta_fab = Country_;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hope this hel you
In my app I want to show user's current location and if location is changed it will show an alert message to change the location. The problem is that it shows location chahnge message even when the phone's GPS is off. What might be the reason?
Here's my code:
protected void onResume() {
/**
* get saved Location from shared preference
*
*/
SharedPreferences sPrefs = PreferenceManager
.getDefaultSharedPreferences(Activity_Home.this);
String getL = sPrefs.getString(Utility.KEY_USER_LAT, "0.000000");
String getLo = sPrefs.getString(Utility.KEY_USER_LONG, "0.000000");
getLat = Double.parseDouble(getL);
getLog = Double.parseDouble(getLo);
gps = new GpsTracker(Activity_Home.this);
/**
* Get user current latitude and longitude and match them to stored
* latitude and longitude if distance between these latitude then Pop up
* will be show
*
* #author Ankit
*/
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
System.out.println("Latitude is " + getLat);
if (getLat > 0.0) {
Location locationA = new Location("point A");
locationA.setLatitude(getLat);
locationA.setLongitude(getLog);
Location locationB = new Location("point B");
locationB.setLatitude(latitude);
locationB.setLongitude(longitude);
distance = locationA.distanceTo(locationB);
// Toast.makeText(Activity_Home.this,
// "Distance is :"+Double.toString(distance),
// Toast.LENGTH_LONG).show();
distance = distance / 1000000;
int getDistance = (int) (distance * 1000000);
System.out.println("Distance is " + getDistance);
if (getDistance > 100) {
showWarningMessage();
}
}
String lat = String.valueOf(latitude);
String lon = String.valueOf(longitude);
SharedPreferences sPref = PreferenceManager
.getDefaultSharedPreferences(Activity_Home.this);
SharedPreferences.Editor sEdit = sPref.edit();
sEdit.putString(Utility.KEY_USER_LAT, lat);
sEdit.putString(Utility.KEY_USER_LONG, lon);
sEdit.commit();
} else {
gps.showSettingsAlert();
}
super.onResume();
}
// Method for show an Alert dialog for user if user's location changed''
public void showWarningMessage() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
Activity_Home.this);
alertDialog.setCancelable(false);
// Setting Dialog Title
alertDialog.setTitle("Location Changed");
// Setting Dialog Message
alertDialog
.setMessage("It seems your location has changed, would you like to change the Branch now?");
// On pressing Settings button
alertDialog.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Activity_Home.this,
Activity_Settings.class);
startActivity(intent);
dialog.cancel();
}
});
// on pressing cancel button
alertDialog.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
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
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 100; // 100 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);
System.out.println("=====isGPSEnabled:
"+isGPSEnabled+"====isNetworkEnabled: "+isNetworkEnabled);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
System.out.println("=====notgps");
} else {
this.canGetLocation = true;
// First get location from Network Provider
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;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GpsTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setCancelable(false);
// Setting Dialog Title
alertDialog.setTitle("Enable GPS");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to
settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new
Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
// alertDialog.;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Here is one sample code for find location check this if it works for you
public static void LocationFind() {
try {
if (Skyhook) {
_xps.getXPSLocation(null,
// note we convert _period to seconds
(int) (_period / 1000), _desiredXpsAccuracy, _callback);
// _xps.getLocation(null, _streetAddressLookup, _callback);
} else {
Criteria criteria = new Criteria();
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
LocationManager locationManager = (LocationManager) mcontext.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
// Log.d("Network", "Network");
if (locationManager != null) {
lastknownlocations = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (lastknownlocations != null) {
lat = lastknownlocations.getLatitude();
lng = lastknownlocations.getLongitude();
}
}
}
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
// Log.d("Network", "Network");
if (locationManager != null) {
lastknownlocations = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastknownlocations != null) {
lat = lastknownlocations.getLatitude();
lng = lastknownlocations.getLongitude();
}
}
}
if (lat == 0.0 && lng == 0.0) {
lng = lastknownlocations.getLongitude();
lat = lastknownlocations.getLatitude();
}
getAddressFromLatLong(lat, lng);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Try out with this service class. This sends updates to method sendLocationDataToProcess(Location location) whenever there is a different of 10 meters with respect to last location
public class AppLocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener{
private LocationRequest locationRequest;
private GoogleApiClient googleApiClient;
private Context appContext;
private boolean currentlyProcessingLocation = false;
private int mInterval=0;
private final int CONNTIMEOUT=50000;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
appContext=getApplicationContext();
Toast.makeText(getBaseContext(), "Location Service Started", Toast.LENGTH_SHORT)
.show();
if (!currentlyProcessingLocation) {
currentlyProcessingLocation = true;
startTracking();
}
return START_STICKY;
}
private void startTracking() {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
Log.v(Constants.BLL_LOG, "ConnectionResult SUCCESS");
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (!googleApiClient.isConnected() || !googleApiClient.isConnecting()) {
googleApiClient.connect();
}else{
Log.v(Constants.BLL_LOG, "NOT connected googleApiClient.connect()");
}
} else {
Log.v(Constants.BLL_LOG, "unable to connect to google play services.");
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public AppLocationService() {
}
#Override
public void onConnected(Bundle bundle) {
Log.v(Constants.BLL_LOG,"onConnected");
locationRequest = LocationRequest.create();
locationRequest.setInterval(mInterval * 1000); // milliseconds
locationRequest.setFastestInterval(mInterval * 1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setSmallestDisplacement(MIN_DISTANCE_CHANGE_FOR_UPDATES);//dostance change
int permissionCheck = ContextCompat.checkSelfPermission(appContext, Manifest.permission.ACCESS_COARSE_LOCATION);
if (permissionCheck!= PackageManager.PERMISSION_DENIED)
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.v(Constants.BLL_LOG,"onConnectionSuspended");
}
#Override
public void onLocationChanged(Location location) {
Log.v(Constants.BLL_LOG, "onLocationChanged position: " + location.getLatitude() + ", " + location.getLongitude() + " accuracy: " + location.getAccuracy());
Log.v(Constants.BLL_LOG, "onLocationChanged position: location.getAccuracy()= "+location.getAccuracy());
sendLocationDataToProcess(location);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.v(Constants.BLL_LOG,"onConnectionFailed");
}
void sendLocationDataToProcess(Location location){
//Do your logic with Location data
}
#Override
public void onDestroy() {
super.onDestroy();
if (googleApiClient != null && googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
}
}
I have a GPSTracker file but in the android M iam geting a zero on the locations... i ask for your help to solve this problem...see the code below
Fragment with the location and a webview to google maps
public class ComoChegar extends Fragment {
EmpresaID item;
public ComoChegar() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View tela = inflater.inflate(R.layout.fragment_como_chegar, container, false);
Bundle id = getActivity().getIntent().getExtras();
String Filial = id.getString("filial");
if (isOnline()) {
item = new EmpresaID(Filial);
Autenticado(item);
}
else
{
android.app.AlertDialog.Builder alerta = new android.app.AlertDialog.Builder(getActivity());
alerta.setMessage("Você está sem Acesso a Internet por favor verifique suas configurações, ative o wi-fi ou seus dados móveis");
alerta.setPositiveButton("OK", null);
alerta.show();
}
return tela;
}
public void Autenticado(EmpresaID id)
{
ServerRequests server = new ServerRequests(getActivity());
server.getEmpresa(id, new GetEmpresaID() {
#Override
public void done(EmpresaID empresa) {
if(empresa == null) {
Erro();
}
else {
GPSTracker gps = new GPSTracker(getActivity());
List<Address> addresses;
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Geocoder geocoder;
geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
if(latitude == 0 && longitude == 0)
{
gps.showSettingsAlert();
}
else {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
String saida = "" + address + "," + city + "-" + postalCode;
String chegada = "" + empresa.endereco + " " + empresa.numero + "," + empresa.bairro + "-" + empresa.cidade;
WebView mapa = (WebView) getActivity().findViewById(R.id.mapa);
mapa.setWebViewClient(new WebViewClient());
mapa.getSettings().setJavaScriptEnabled(true);
String ida = saida.replace(" ", "+");
String trem = chegada.replace(" ", "+");
String Url = "https://www.google.com/maps/dir/" + latitude + "," + longitude + "/" + trem + "";
mapa.loadUrl(Url);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
private void Erro() {
android.support.v7.app.AlertDialog.Builder alerta = new android.support.v7.app.AlertDialog.Builder(getActivity());
alerta.setMessage("Erro ao Carregar dados do servidor");
alerta.setPositiveButton("OK", null);
alerta.show();
}
private boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
}
the GPSTracker class
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
// 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;
// First get location from Network Provider
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;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("Erro");
// Setting Dialog Message
alertDialog.setMessage("GPS não está ligado. Gostaria de Checar nas Configurações?");
// On pressing Settings button
alertDialog.setPositiveButton("Configurações", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Since your LocationListener tries to get location using only Network not GPS, with this code snippet: locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
probably you are getting latitude and longitude values but with a delay. I had the same problem then I begin to use new/latest Location service API and use:
GoogleApiClient.
First you need to implement
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
from you activity that want to fetch the location data.
Define
private GoogleApiClient mGoogleApiClient;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
If you haven't add
<uses-permission `android:name="android.permission.ACCESS_FINE_LOCATION"/>`
to the manifest file, add that.
For further documentation : https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient
I am currently developing an Android app which prompts the user to enable GPS if it's not on and I have used AlertDialog for this purpose. After I enable the GPS from settings and come back to my app by pressing back button, the mapView doesn't reflect my current location. Although If I have my GPS on before running the app, the app properly displays my location. I want to know to which method to use for this refresh user location after enabling GPS purpose. Any relevant article would really help.
Following is my code for the GPS part:
GPSTracker.java
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
// 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);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// If GPS enabled, get latitude/longitude 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;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app.
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/Wi-Fi enabled
*
* #return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog.
* On pressing the Settings button it will launch Settings Options.
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing the Settings button.
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// On pressing the cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
The following class makes use of above class to display location in a mapView
LocationActivity.java
public class LocationActivity extends Activity {
Button btnGPSShowLocation;
Button btnSendAddress;
Button find_rick;
TextView tvAddress;
AppLocationService appLocationService;
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
//Google maps implementation
GoogleMap googleMap;
private static final String TAG = LocationActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_layout);
createMapView();
btnShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
btnSendAddress = (Button) findViewById(R.id.btnSendAddress);
gps = new GPSTracker(LocationActivity.this);
// Check if GPS enabled and if enabled after popup then call same fn
MapMyCurrentLoction();
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MapMyCurrentLoction();
}
});
btnSendAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tag_string_req_send_data = "req_send";
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_AUTOWALA_DHUNDO, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Autowala Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
Log.d("Autowale ka data","success");
} else {
// Error occurred in data sending. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Data sending Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "data_send");
params.put("latitude", Double.toString(gps.getLatitude()));
params.put("longitude", Double.toString(gps.getLongitude()));
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req_send_data);
}
});
}
#Override
protected void onPause(){
super.onPause();
MapMyCurrentLoction();
//super.onResume();
}
#Override
protected void onResume(){
super.onResume();
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
addMarker(latitude,longitude);
//super.onResume();
}
private void createMapView(){
/**
* Catch the null pointer exception that
* may be thrown when initialising the map
*/
try {
if(null == googleMap){
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
googleMap.getUiSettings().setZoomGesturesEnabled(true);
/**
* If the map is still null after attempted initialisation,
* show an error to the user
*/
if(null == googleMap) {
Toast.makeText(getApplicationContext(),
"Error creating map",Toast.LENGTH_SHORT).show();
}
}
} catch (NullPointerException exception){
Log.e("mapApp", exception.toString());
}
}
/**
* Adds a marker to the map
*/
private void addMarker(double lat,double lng){
/** Make sure that the map has been initialised **/
if(null != googleMap){
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(lat,lng))
.title("Your Location")
.draggable(true)
);
//zooming to my location
float zoomLevel = 16.0F; //This goes up to 21
LatLng coordinate = new LatLng(lat, lng);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, zoomLevel);
googleMap.animateCamera(yourLocation);
}
}
private void MapMyCurrentLoction(){
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
addMarker(latitude,longitude);
/*------- To get city name from coordinates -------- */
String area = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addressList = null;
try {
addressList = gcd.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append("\n");
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
area = sb.toString();
}
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude + "\n"+area, Toast.LENGTH_SHORT).show();
} else {
// Can't get location.
// GPS or network is not enabled.
// Ask user to enable GPS/network in settings.
gps.showSettingsAlert();
//Again search and map my location after enabling gps
}
}
}
You just need to initialize this
gps = new GPSTracker(LocationActivity.this);
at onResume() and at onCreate() and if needed then at onRestart() too.
This is not the correct way but for making it working you can do this.
you`re probably interest in 'onResume' method. After getting back to Activity this one is invoked. Sho in there you should update the position