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
Related
How can I refresh the marker position (for example, when user is moving) on Android maps?
I set up the refresh time for 3 seconds in locationManager.requestLocationUpdates but it seems that it's not working.
Here is my 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 = 50; // 3 seconds
// 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;
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
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;
}
}
And here is my Maps Activity where I create map and add a marker to it:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private final static int REQUEST_CODE_ASK_PERMISSIONS = 1;
private static final String[] REQUIRED_SDK_PERMISSIONS = new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_NETWORK_STATE};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
checkPermissions();
// 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;
mapsCreate();
}
public void mapsCreate() {
GPSTracker tracker = new GPSTracker(MapsActivity.this);
double lat = tracker.getLatitude();
double lng = tracker.getLongitude();
// Add a marker for current location and move the camera
LatLng currentLocation = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location Marker"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
}
protected boolean checkPermissions() {
final List<String> missingPermissions = new ArrayList<String>();
// check all required dynamic permissions
for (final String permission : REQUIRED_SDK_PERMISSIONS) {
final int result = ContextCompat.checkSelfPermission(this, permission);
if (result != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(permission);
}
}
if (!missingPermissions.isEmpty()) {
// request all missing permissions
final String[] permissions = missingPermissions
.toArray(new String[missingPermissions.size()]);
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_ASK_PERMISSIONS);
} else {
final int[] grantResults = new int[REQUIRED_SDK_PERMISSIONS.length];
Arrays.fill(grantResults, PackageManager.PERMISSION_GRANTED);
onRequestPermissionsResult(REQUEST_CODE_ASK_PERMISSIONS, REQUIRED_SDK_PERMISSIONS,
grantResults);
return true;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[],
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
for (int index = permissions.length - 1; index >= 0; --index) {
if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {
// exit the app if one permission is not granted
Toast.makeText(this, "Required permission '" + permissions[index]
+ "' not granted, exiting", Toast.LENGTH_LONG).show();
finish();
return;
}
}
// all permissions were granted
break;
}
}
Any help would be much appreciated! Thank you
Save the marker object after adding to maps.
myMarker = mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location Marker"));
After getting new location in location updates callback update marker's position.
.....
myMarker.setPosition(newLatLng);
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.
I am working on maps in my application. In which i used InfoWindowAdapter. I am having image view in that. But on opening the info window image is not display.
The xml of infoWindow is as follow:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp"
card_view:contentPadding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/imageView_infoWindow"
android:layout_width="80dp"
android:layout_height="80dp"
android:scaleType="fitXY"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textView_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView_location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
And the Activity code is as follow:
public class LocationActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationChangeListener, GoogleMap.OnMyLocationButtonClickListener {
private GoogleMap mMap;
public LatLng MOUNTAIN_VIEW;
int METERS = 20000;
final private int PERMISSION_REQUEST_CODE_FOR_ACCESS_LOCATION = 123;
List<MarkerOptions> markerOptionsList;
ArrayList<ModelLocation> modelLocation;
protected LocationManager locationManager;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
ImageLoader mImageLoader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setElevation(2);
actionBar.setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);
actionBar.setTitle("Location");
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setIndoorLevelPickerEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
if (checkPermission()) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
} else {
requestPermission();
}
CameraPosition cameraPosition = new CameraPosition.Builder().target(MOUNTAIN_VIEW)
.zoom(17)
.bearing(360)
.tilt(45)
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
final LatLng latLng = cameraPosition.target;
final Location location = new Location("Camera_Location");
location.setLatitude(latLng.latitude);
location.setLongitude(latLng.longitude);
final ProgressDialog progressDialog = new ProgressDialog(LocationActivity.this, R.style.ProgressBarTansparent);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
progressDialog.setContentView(R.layout.custom_progressbar_layout);
String url = "My URL To Get Data";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("Key","Value");
} catch (JSONException e) {
e.printStackTrace();
}
final JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArrayUserList = response.getJSONArray("ABC");
modelLocation = new ArrayList<>();
int size = jsonArrayUserList.length();
if (size > 0) {
for (int count = 0; count < size; count++) {
JSONObject jsonObject = jsonArrayUserList.getJSONObject(count);
int userID = jsonObject.getInt("userID");
String Name = jsonObject.getString("address");
String address = jsonObject.getString("ADD");
float latitude = Float.parseFloat(jsonObject.getString("latitude"));
float longitude = Float.parseFloat(jsonObject.getString("longitude"));
String image = jsonObject.getString("image");
ModelLocation modelLocation1 = new ModelLocation(userID, Name, address, latitude, longitude, image);
modelLocation.add(modelLocation1);
}
Location target = new Location("target");
for (ModelLocation modelLocation1 : modelLocation) {
target.setLatitude(modelLocation1.latitude);
target.setLongitude(modelLocation1.longitude);
LatLng point = new LatLng(modelLocation1.latitude, modelLocation1.longitude);
MarkerOptions markerOptions = new MarkerOptions().title(modelLocation1.Name).snippet(modelLocation1.address).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_pin)).anchor(0.0f, 1.0f).position(point);
if (location.distanceTo(target) < METERS) {
if (isMarkerOnArray(markerOptionsList, markerOptions)) {
} else {
markerOptionsList.add(markerOptions);
Marker marker = mMap.addMarker(markerOptions);
dropic_pinEffect(marker);
}
}
}
}
progressDialog.dismiss();
} catch (Exception e) {
}
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
Volley.newRequestQueue(LocationActivity.this).add(postRequest);
}
});
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View view = getLayoutInflater().inflate(R.layout.info_window_layout, null);
LatLng latLng = marker.getPosition();
for (int count = 0; count < modelLocation.size(); count++) {
double currentLat = modelLocation.get(count).getLatitude();
double currentLng = modelLocation.get(count).getLongitude();
if ((currentLat == latLng.latitude) && (currentLng == latLng.longitude)) {
TextView textViewTitle = (TextView) view.findViewById(R.id.textView_title);
TextView textViewAddress = (TextView) view.findViewById(R.id.textView_address);
TextView textViewLocation = (TextView) view.findViewById(R.id.textView_location);
final NetworkImageView imageViewUserImage = (NetworkImageView) view.findViewById(R.id.imageView_infoWindow);
textViewTitle.setText("" + modelLocation.get(count).getName());
textViewAddress.setText("" + modelLocation.get(count).getAddress());
textViewLocation.setText(currentLat + ", " + currentLng);
mImageLoader = VolleySingletonClass.getInstance(LocationActivity.this).getImageLoader();
String url = "My URL Of Image";
imageViewUserImage.setImageUrl(url, mImageLoader);
imageViewUserImage.setDefaultImageResId(R.drawable.ic_user_default);
imageViewUserImage.setErrorImageResId(R.drawable.ic_user_default);
}
}
return view;
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Intent intent = new Intent(LocationActivity.this, Activity2.class);
startActivity(intent);
finish();
}
});
}
static boolean isMarkerOnArray(List<MarkerOptions> listMarkerOptions, MarkerOptions markerOptions) {
for (int count = 0; count < listMarkerOptions.size(); count++) {
MarkerOptions current = listMarkerOptions.get(count);
if ((current.getPosition().latitude == markerOptions.getPosition().latitude) && (current.getPosition().longitude == markerOptions.getPosition().longitude))
return true;
}
return false;
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(LocationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(LocationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(LocationActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, PERMISSION_REQUEST_CODE_FOR_ACCESS_LOCATION);
}
}
#SuppressLint("NewApi")
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE_FOR_ACCESS_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
mMap.setOnMyLocationButtonClickListener(this);
} else {
Toast.makeText(LocationActivity.this, "Permission Denied", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(LocationActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, PERMISSION_REQUEST_CODE_FOR_ACCESS_LOCATION);
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void dropic_pinEffect(final Marker marker) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final long duration = 1000;
final Interpolator interpolator = new BounceInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = Math.max(1 - interpolator.getInterpolation((float) elapsed / duration), 0);
marker.setAnchor(0.5f, 1.0f + 7 * t);
if (t > 0.0) {
handler.postDelayed(this, 15);
} else {
}
}
});
}
#Override
public void onMyLocationChange(Location location) {}
#Override
public boolean onMyLocationButtonClick() {
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onResume() {
super.onResume();
getLocation();
if (canGetLocation()) {
double lat = getLatitude();
double lng = getLongitude();
MOUNTAIN_VIEW = new LatLng(lat, lng);
markerOptionsList = new ArrayList<MarkerOptions>();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
} else {
showSettingsAlert();
}
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public Location getLocation() {
try {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this);
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;
}
public double getLatitude() {
double lati = 0;
if (location != null) {
lati = location.getLatitude();
}
return lati;
}
public double getLongitude() {
double longi = 0;
if (location != null) {
longi = location.getLongitude();
}
return longi;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent = new Intent(LocationActivity.this, Activity1.class);
startActivity(intent);
finish();
}
});
alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
dialog.dismiss();
Intent intent = new Intent(LocationActivity.this, Activity1.class);
startActivity(intent);
finish();
}
});
alertDialog.show();
}
}
I searched on Google that why image is not display, So i got to know that i need to refresh info window adapter may be. Or is it Volley implementation issue?
Please suggest me That my implementation is right or not and what step should i perform to Display Image in image view on window open
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
I am developing an app which asks users to enable the GPS if not on and then maps user location on Map. The problem I am facing is that after user enables the GPS from settings and presses back button, the Dialog box is shown saying "Location user location" but the app fails to get the longitude and latitude. Although if at this stage if I exit the app and start it again and access the same activity where the user location will be shown on map, then it works fine.
Following are the files used by me:
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;
}
}
LocationActivity.java
public class LocationActivity extends Activity {
Button btnGPSShowLocation;
Button btnSendAddress;
Button find_rick;
TextView tvAddress;
private ProgressDialog pDialog;
int progressBarStatus=0;
boolean shouldExecuteOnResume;
Handler progressBarHandler = new Handler();
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);
shouldExecuteOnResume=false;
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
pDialog.setMessage("Locating your location");
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setProgress(0);
pDialog.setMax(100);
progressBarStatus = 0;
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
Log.d("OnCreate","OnCreate");
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
} 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();
}
#Override
protected void onResume(){
super.onResume();
if(shouldExecuteOnResume)
{
pDialog.show();
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
progressBarStatus = getULocation();
try {
Thread.sleep(7000);
} catch (InterruptedException e) {
e.printStackTrace();
}
progressBarHandler.post(new Runnable() {
public void run() {
pDialog.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= 100) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
pDialog.dismiss();
}
}
}).start();
//super.onResume();
}
else{
shouldExecuteOnResume=true;
}
/*pDialog.setMessage("Locating your location");
showDialog();*/
/*while(gps.getLatitude()==0.0 && gps.getLongitude()==0.0)
{
}*/
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
addMarker(latitude, longitude);
//super.onResume();
}
private int getULocation()
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Location location;
// The minimum distance to change Updates in meters
final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
boolean flag=gps.canGetLocation();
LocationManager locationManager = (LocationManager) this
.getSystemService(LOCATION_SERVICE);
location=locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Getting GPS status
boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(latitude > 0.0 && longitude > 0.0)
{
return 100;
}
else
{
return 0;
}
}
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
}
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
When the app starts it's execution from onResume() method after user enables GPS from settings, even though isGPSEnabled returns true, I cannot get longitude or latitude and the dialog stays on screen until the app is closed.
I am new to Android Development so many of this things are a bit confusing to me at this stage so it will be very useful if I can get a solution for the problem as soon I can.
EDIT
Problem:
I am using AsyncTask now for my purpose and I have taken out the getLocation() method out of the constructor. However now the dialog "Searching GPS.." is shown continuously because of the while loop used in doInBackground() method I guess.
Here is my class which uses AsyncTask
private class InsertDataTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(LocationActivity.this);
#Override
protected Void doInBackground(Void... params) {
Log.d("Before getLocation=",String.valueOf(gps._isGPSEnabled));
gps.getLocation(LocationActivity.this);
Log.d("After getLocation=", String.valueOf(gps._isGPSEnabled));
while(gps.getLatitude()==0.0){
//do nothing
}
return null;
}
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Searching GPS...");
this.dialog.show();
}
// can use UI thread here
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
addMarker(gps.getLatitude(),gps.getLongitude());
}
}
Since ur calling getLocation() in constructor of GPS tracker class the method getLocation() gets executed only once (in this method only ur updating the status of the boolean canGetLocation) So when u execute the program without turning ON GPS it will update the status of canGetLocation to false and as ur saying when u turn it ON it will never update the status because u are not calling the method getLocation from ur Activity anywhere(like on a button click). Instead ur just checking the boolean value which is always false until u exit ur App and come back(until u create a new object;i.e calling the constructor). So dont call the method getLocation from constructor instead call it on a Button click, so the boolean value will get updated as u turn ON the GPS.