I am using a plasio turbo x to test my osmdroid sample. I am also testing using a moto g. In moto g the map rotation which is according to the compass head up is working fine, but in plasio one the compass starts to spin and map also spins, they don't get stable. You can see the logcat here(it is very big, stackoverflow not letting me add it here).
Following is my class in which I have used compass:
public class MainActivity extends FragmentActivity implements LocationListener, IOrientationConsumer,MapEventsReceiver {
private CompassOverlay mCompassOverlay = null;
private MyLocationNewOverlay mLocationOverlay;
IOrientationProvider compass = null;
int deviceOrientation = 0;
MapView mMapView;
float gpsspeed;
float gpsbearing;
float lat = 0;
float lon = 0;
float alt = 0;
long timeOfFix = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
final double lat1 = Double.parseDouble(intent.getStringExtra("lat1"));
final double long1 = Double.parseDouble(intent.getStringExtra("long1"));
final double lat2 = 25.633;
final double long2 = 71.094;
//important! set your user agent to prevent getting banned from the osm servers
org.osmdroid.tileprovider.constants.OpenStreetMapTileProviderConstants.setUserAgentValue(BuildConfig.APPLICATION_ID);
mMapView = (MapView) findViewById(R.id.map);
mMapView.setTileSource(TileSourceFactory.MAPNIK);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
mCompassOverlay = new CompassOverlay(this, new InternalCompassOrientationProvider(this),
mMapView);
mCompassOverlay.enableCompass();
mMapView.getOverlays().add(this.mCompassOverlay);
addOverlays();
GeoPoint startPoint = new GeoPoint(lat1, long1);
IMapController mapController = mMapView.getController();
mapController.setZoom(9);
mapController.setCenter(startPoint);
Marker startMarker = new Marker(mMapView);
startMarker.setPosition(startPoint);
startMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
mMapView.getOverlays().add(startMarker);
RoadManager roadManager = new OSRMRoadManager(this);
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
waypoints.add(startPoint);
GeoPoint endPoint = new GeoPoint(lat2, long2);
Marker endMarker = new Marker(mMapView);
endMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
mMapView.getOverlays().add(endMarker);
waypoints.add(endPoint);
Road road = roadManager.getRoad(waypoints);
Polyline roadOverlay = RoadManager.buildRoadOverlay(road);
mMapView.getOverlays().add(roadOverlay);
mMapView.invalidate();
}
public void addOverlays() {
mLocationOverlay = new MyLocationNewOverlay(mMapView);
mLocationOverlay.setEnableAutoStop(false);
mLocationOverlay.enableFollowLocation();
mLocationOverlay.enableMyLocation();
this.mMapView.getOverlayManager().add(mLocationOverlay);
mMapView.setBuiltInZoomControls(true);
mMapView.setMultiTouchControls(true);
mMapView.setTilesScaledToDpi(true);
}
#Override
protected void onResume() {
super.onResume();
//lock the device in current screen orientation
int orientation;
int rotation = ((WindowManager) this.getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
switch (rotation) {
case Surface.ROTATION_0:
orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
this.deviceOrientation = 0;
break;
case Surface.ROTATION_90:
this.deviceOrientation = 90;
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
break;
case Surface.ROTATION_180:
this.deviceOrientation = 180;
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
break;
default:
this.deviceOrientation = 270;
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
break;
}
this.setRequestedOrientation(orientation);
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, (LocationListener) this);
} catch (Exception ex) {
}
compass = new InternalCompassOrientationProvider(this);
compass.startOrientationProvider(this);
mMapView.getController().zoomTo(14);
}
#Override
public void onLocationChanged(Location location) {
if (mMapView == null)
return;
//after the first fix, schedule the task to change the icon
//mMapView.getController().setCenter(new GeoPoint(location.getLatitude(), location.getLongitude()));
mMapView.invalidate();
gpsbearing = location.getBearing();
gpsspeed = location.getSpeed();
lat = (float) location.getLatitude();
lon = (float) location.getLongitude();
alt = (float) location.getAltitude(); //meters
timeOfFix = location.getTime();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
protected void onPause() {
super.onPause();
compass.stopOrientationProvider();
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
lm.removeUpdates(this);
} catch (Exception ex) {
}
//unlock the orientation
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
Float trueNorth = 0f;
#Override
public void onOrientationChanged(final float orientationToMagneticNorth, IOrientationProvider source) {
GeomagneticField gf = new GeomagneticField(lat, lon, alt, timeOfFix);
trueNorth = orientationToMagneticNorth + gf.getDeclination();
gf=null;
synchronized (trueNorth) {
if (trueNorth > 360.0f) {
trueNorth = trueNorth - 360.0f;
}
//use gps bearing instead of the compass
if (gpsspeed > 0.01f) {
float t = (360 - gpsbearing - this.deviceOrientation);
if (t < 0) {
t += 360;
}
if (t > 360) {
t -= 360;
}
mMapView.setMapOrientation(t);
} else {
//this part adjusts the desired map rotation based on device orientation and compass heading
float t = (360 - trueNorth - this.deviceOrientation);
if (t < 0) {
t += 360;
}
if (t > 360) {
t -= 360;
}
mMapView.setMapOrientation(t);
}
this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (this!=null ) {
Toast.makeText(MainActivity.this, "GPS Speed: " + gpsspeed + "m/s GPS Bearing: " + gpsbearing +
"\nDevice Orientation: " + (int) deviceOrientation + " Compass heading: " + (int) orientationToMagneticNorth + "\n" +
"True north: " + trueNorth.intValue() + " Map Orientation: " + (int) mMapView.getMapOrientation() + "\n", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public boolean singleTapConfirmedHelper(GeoPoint geoPoint) {
return false;
}
#Override
public boolean longPressHelper(GeoPoint geoPoint) {
return false;
}
}
Related
I am trying a map application like ola. I did drawn a polyline but i cant update the camera while marker is moving. Also i didnt get proper solution for animating the marker along with polyline. Do suggest me a proper solution for both of my problem.
Here is the code:
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, View.OnClickListener {
private Context context;
GoogleMap googleMap;
Button btn_start;
Marker marker;
Polyline line;
List<LatLng> list;
LatLng startLatLng = new LatLng(43.182821, -99.292304);
LatLng endLatLng = new LatLng(44.959263, -97.580412);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
btn_start = (Button) findViewById(R.id.btn_start);
String urlTopass = makeURL(startLatLng.latitude,
startLatLng.longitude, endLatLng.latitude,
endLatLng.longitude);
new connectAsyncTask(urlTopass).execute();
btn_start.setOnClickListener(this);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(startLatLng, 9);
googleMap.animateCamera(cameraUpdate);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start:
setAnimation(googleMap, list, ResourceUtils.getBitmap(context, R.drawable.ic_car_yellow_btg));
break;
default:
break;
}
}
private class connectAsyncTask extends AsyncTask<Void, Void, String> {
private ProgressDialog progressDialog;
String url;
connectAsyncTask(String urlPass) {
url = urlPass;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
return jParser.getJSONFromUrl(url);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if (result != null) {
drawPath(result);
}
}
}
public String makeURL(double sourcelat, double sourcelog, double destlat,
double destlog) {
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString.append(Double.toString(sourcelog));
urlString.append("&destination=");// to
urlString.append(Double.toString(destlat));
urlString.append(",");
urlString.append(Double.toString(destlog));
urlString.append("&sensor=true&mode=driving&alternatives=true");
Log.e("url ", " " + urlString);
return urlString.toString();
}
public class JSONParser {
InputStream is = null;
JSONObject jObj = null;
String json = "";
public JSONParser() {
}
public String getJSONFromUrl(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
public void drawPath(String result) {
if (line != null) {
googleMap.clear();
}
googleMap.addMarker(new MarkerOptions().position(startLatLng).icon(
BitmapDescriptorFactory.fromBitmap(ResourceUtils.getBitmap(context, R.drawable.ic_car_yellow_btg))));
/*googleMap.addMarker(new MarkerOptions().position(startLatLng).icon(
BitmapDescriptorFactory.fromResource(R.drawable.car_red)));*/
try {
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes
.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
list = decodePoly(encodedString);
for (int z = 0; z < list.size() - 1; z++) {
LatLng src = list.get(z);
LatLng dest = list.get(z + 1);
line = googleMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude),
new LatLng(dest.latitude, dest.longitude))
.width(10).color(Color.BLUE).geodesic(true));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)), (((double) lng / 1E5)));
poly.add(p);
Log.e("coords", "LatLng " + p);
}
return poly;
}
public static void setAnimation(GoogleMap myMap, final List<LatLng> directionPoint, final Bitmap bitmap) {
Marker marker = myMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromBitmap(bitmap))
.position(directionPoint.get(0))
.flat(true));
/*PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
myMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 50));*/
animateMarker(myMap, marker, directionPoint, false);
}
private static void animateMarker(GoogleMap myMap, final Marker marker, final List<LatLng> directionPoint,
final boolean hideMarker) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = myMap.getProjection();
final long duration = 60000;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
int i = 0;
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
if (i < directionPoint.size())
marker.setPosition(directionPoint.get(i));
i++;
if (t < 1.0) {
handler.postDelayed(this, 24);
} else {
if (hideMarker) {
marker.setVisible(false);
} else {
marker.setVisible(true);
}
}
}
});
}
}
First of all you need this class:
public interface LatLngInterpolator {
LatLng interpolate(float fraction, LatLng a, LatLng b);
class Linear implements LatLngInterpolator {
#Override
public LatLng interpolate(float fraction, LatLng a, LatLng b) {
double lat = (b.latitude - a.latitude) * fraction + a.latitude;
double lng = (b.longitude - a.longitude) * fraction + a.longitude;
return new LatLng(lat, lng);
}
}
class LinearFixed implements LatLngInterpolator {
#Override
public LatLng interpolate(float fraction, LatLng a, LatLng b) {
double lat = (b.latitude - a.latitude) * fraction + a.latitude;
double lngDelta = b.longitude - a.longitude;
// Take the shortest path across the 180th meridian.
if (Math.abs(lngDelta) > 180) {
lngDelta -= Math.signum(lngDelta) * 360;
}
double lng = lngDelta * fraction + a.longitude;
return new LatLng(lat, lng);
}
}
class Spherical implements LatLngInterpolator {
/* From github.com/googlemaps/android-maps-utils */
#Override
public LatLng interpolate(float fraction, LatLng from, LatLng to) {
// http://en.wikipedia.org/wiki/Slerp
double fromLat = toRadians(from.latitude);
double fromLng = toRadians(from.longitude);
double toLat = toRadians(to.latitude);
double toLng = toRadians(to.longitude);
double cosFromLat = cos(fromLat);
double cosToLat = cos(toLat);
// Computes Spherical interpolation coefficients.
double angle = computeAngleBetween(fromLat, fromLng, toLat, toLng);
double sinAngle = sin(angle);
if (sinAngle < 1E-6) {
return from;
}
double a = sin((1 - fraction) * angle) / sinAngle;
double b = sin(fraction * angle) / sinAngle;
// Converts from polar to vector and interpolate.
double x = a * cosFromLat * cos(fromLng) + b * cosToLat * cos(toLng);
double y = a * cosFromLat * sin(fromLng) + b * cosToLat * sin(toLng);
double z = a * sin(fromLat) + b * sin(toLat);
// Converts interpolated vector back to polar.
double lat = atan2(z, sqrt(x * x + y * y));
double lng = atan2(y, x);
return new LatLng(toDegrees(lat), toDegrees(lng));
}
private double computeAngleBetween(double fromLat, double fromLng, double toLat, double toLng) {
// Haversine's formula
double dLat = fromLat - toLat;
double dLng = fromLng - toLng;
return 2 * asin(sqrt(pow(sin(dLat / 2), 2) +
cos(fromLat) * cos(toLat) * pow(sin(dLng / 2), 2)));
}
}
}
Then you can use this class to animate markers:
public class MarkerAnimation {
private static final String TAG = MarkerAnimation.class.getSimpleName();
public static ArrayList<GetDirectionsAsync> getDirectionsAsyncs = new ArrayList<>();
static boolean isAnimationRunning = false;
public static void animateMarkerToGB(final Marker marker, final LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {
final LatLng startPosition = marker.getPosition();
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final Interpolator interpolator = new AccelerateDecelerateInterpolator();
final float durationInMs = 3000;
handler.post(new Runnable() {
long elapsed;
float t;
float v;
#Override
public void run() {
// Calculate progress using interpolator
elapsed = SystemClock.uptimeMillis() - start;
t = elapsed / durationInMs;
v = interpolator.getInterpolation(t);
marker.setPosition(latLngInterpolator.interpolate(v, startPosition, finalPosition));
// Repeat till progress is complete.
if (t < 1) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void animateMarkerToHC(final Marker marker, final LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {
final LatLng startPosition = marker.getPosition();
ValueAnimator valueAnimator = new ValueAnimator();
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float v = animation.getAnimatedFraction();
LatLng newPosition = latLngInterpolator.interpolate(v, startPosition, finalPosition);
marker.setPosition(newPosition);
}
});
valueAnimator.setFloatValues(0, 1); // Ignored.
valueAnimator.setDuration(3000);
valueAnimator.start();
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void animateMarkerToICS(Marker marker, LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {
// List<LatLng> list = new ArrayList<>();
// list.add(finalPosition);
// animateMarkerToICSRecursive(marker, list, latLngInterpolator, true);
try {
animateMarkerToICSRecursive(marker, finalPosition, latLngInterpolator, true);
//if(MapUtils.distance(marker.getPosition(), finalPosition)
//< 100
// || MapUtils.distance(marker.getPosition(),
//finalPosition) > 500){
// List<LatLng> list = new ArrayList<>();
// animateMarkerToICSRecursive(marker, finalPosition,
//latLngInterpolator, true);
// }
// else{
// getDirectionsAsyncs.add(new
//GetDirectionsAsync(marker, finalPosition, latLngInterpolator));
// if(getDirectionsAsyncs.size() == 1){
// getDirectionsAsyncs.get(0).execute();
// }
// }
} catch (Exception e) {
e.printStackTrace();
try {
marker.setPosition(finalPosition);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
private static void checkAndExecute() {
if (getDirectionsAsyncs.size() > 0) {
getDirectionsAsyncs.get(0).execute();
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void animateMarkerToICSRecursive(final Marker marker, final List<LatLng> list,
final LatLngInterpolator latLngInterpolator, final boolean rotation) {
if (list.size() > 0) {
final LatLng finalPosition = list.remove(0);
TypeEvaluator<LatLng> typeEvaluator = new TypeEvaluator<LatLng>() {
#Override
public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) {
return latLngInterpolator.interpolate(fraction, startValue, endValue);
}
};
Property<Marker, LatLng> property = Property.of(Marker.class, LatLng.class, "position");
ObjectAnimator animator = ObjectAnimator.ofObject(marker, property, typeEvaluator, finalPosition);
animator.setDuration((long) (10.0d * MapUtils.distance(marker.getPosition(), finalPosition)));
animator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animator) {
isAnimationRunning = true;
}
#Override
public void onAnimationEnd(Animator animator) {
marker.setPosition(finalPosition);
isAnimationRunning = false;
if (list.size() > 0) {
animateMarkerToICSRecursive(marker, list, latLngInterpolator, rotation);
}
}
#Override
public void onAnimationCancel(Animator animator) {
}
#Override
public void onAnimationRepeat(Animator animator) {
}
});
if (rotation) {
//marker.setRotation((float) MapUtils.getBearing(marker.getPosition(), finalPosition));
MapUtils.rotateMarker(marker, (float) MapUtils.getBearing(marker.getPosition(), finalPosition));
}
if (!isAnimationRunning) {
animator.start();
}
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void animateMarkerToICSRecursive(final Marker marker, final LatLng finalPosition,
final LatLngInterpolator latLngInterpolator, final boolean rotation) {
TypeEvaluator<LatLng> typeEvaluator = new TypeEvaluator<LatLng>() {
#Override
public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) {
return latLngInterpolator.interpolate(fraction, startValue, endValue);
}
};
Property<Marker, LatLng> property = Property.of(Marker.class, LatLng.class, "position");
ObjectAnimator animator = ObjectAnimator.ofObject(marker, property, typeEvaluator, finalPosition);
animator.setDuration((long) (1000));
animator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animator) {
isAnimationRunning = true;
}
#Override
public void onAnimationEnd(Animator animator) {
marker.setPosition(finalPosition);
isAnimationRunning = false;
}
#Override
public void onAnimationCancel(Animator animator) {
}
#Override
public void onAnimationRepeat(Animator animator) {
}
});
if (rotation) {
//marker.setRotation((float) MapUtils.getBearing(marker.getPosition(), finalPosition));
MapUtils.rotateMarker(marker, (float) MapUtils.getBearing(marker.getPosition(), finalPosition));
}
if (!isAnimationRunning) {
animator.start();
}
}
static class GetDirectionsAsync extends AsyncTask<String, String, String> {
LatLng source, destination;
Marker marker;
LatLngInterpolator latLngInterpolator;
public GetDirectionsAsync(Marker marker, LatLng destination, LatLngInterpolator latLngInterpolator) {
this.source = marker.getPosition();
this.destination = destination;
this.marker = marker;
this.latLngInterpolator = latLngInterpolator;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
Response response = RestClient.getGoogleApiServices().getDirections(source.latitude + "," + source.longitude,
destination.latitude + "," + destination.longitude, false, "driving", false);
String responseStr = new String(((TypedByteArray) response.getBody()).getBytes());
return responseStr;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
final List<LatLng> list = MapUtils.getLatLngListFromPath(result);
animateMarkerToICSRecursive(marker, list, latLngInterpolator, true);
}
getDirectionsAsyncs.remove(0);
checkAndExecute();
}
}
}
You need to pass the list of all the LatLng's of the path in the above class like this:
MarkerAnimation.animateMarkerToICS(driverLocationMarker, destinationLatLng, new LatLngInterpolator.Spherical());
Hope this helps
EDIT :
This is the code for the marker rotation:
d
public static void rotateMarker(final Marker marker, final float toRotation) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = marker.getRotation();
final long duration = 700;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed / duration);
float rot = t * toRotation + (1 - t) * startRotation;
marker.setRotation(-rot > 180 ? rot / 2 : rot);
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
}
Android compass showing only view but not moving as expected on a few devices.
This is getting frustrating now. I just completed an app which shows a compass. It was working fine on my Samsung s4 and a few other devices, but when I send the apk file for testing the worst just came out that compass is not working on a few devices, including client device. Till then, I have tried 2, 3 different type of codes which I found on stackoverflow and a few other sites. All of them are working fine on my s4 but not on the client's device.
I'm sharing this code.
I've tested this code in some android 6.0 devices too and it was working just fine. I'm totally not getting where's the error.
Any help will be highly appreciated
public class QiblaActivity extends AppCompatActivity implements SensorEventListener {
private ImageView qiblaNSEW, qiblaIcon;
private float currentDegree = 0f;
private float currentDegree1 = 0f;
RelativeLayout back_Rel, bulb_Rel;
// device sensor manager
private SensorManager mSensorManager;
TextView degreeTV;
AdRequest adRequest;
double angle;
GPSTracker gpsTracker;
Location location;
private static final int PERMS_REQUEST_CODE = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qibla);
Utils.statusBarColor(getWindow(), QiblaActivity.this);
back_Rel = (RelativeLayout) findViewById(R.id.back_Rel);
bulb_Rel = (RelativeLayout) findViewById(R.id.bulb_Rel);
bulb_Rel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(QiblaActivity.this, QuranBulbActivity.class);
startActivity(intent);
}
});
back_Rel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
}
);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (hasPermissions())
{
gpsTracker = new GPSTracker(this);
if (gpsTracker.canGetLocation()) {
startQibla();
}
}
else
{
requestPerms();
}
} else {
gpsTracker = new GPSTracker(this);
if (gpsTracker.canGetLocation()) {
startQibla();
} else {
gpsTracker.showSettingsAlert();
}
}
}
private void startQibla() {
qiblaNSEW = (ImageView) findViewById(R.id.qibla_n_s_e_w);
qiblaIcon = (ImageView) findViewById(R.id.qibla_icon);
degreeTV = (TextView) findViewById(R.id.degree_TV);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
setAds();
angle = getAngle();
gpsTracker = new GPSTracker(this);
location = gpsTracker.getLocation();
Log.d("angle", angle + "");
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_GAME);
/* mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE),
SensorManager.SENSOR_DELAY_NORMAL);*/
}
#Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
float degree = Math.round(sensorEvent.values[0]);
degreeTV.setText((Float.toString(Math.round(degree - angle)) + "").replace(".0", "").replace("-", ""));
// create a rotation animation (reverse turn degree degrees)
RotateAnimation ra = new RotateAnimation(
currentDegree,
-degree,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF,
0.5f);
// how long the animation will take place
ra.setDuration(210);
// set the animation after the end of the reservation status
ra.setFillAfter(true);
// Start the animation
qiblaNSEW.startAnimation(ra);
currentDegree = -degree;
float tempDegreeNorth = degree;
if (tempDegreeNorth > 180) {
tempDegreeNorth = 360 - tempDegreeNorth;
} else {
tempDegreeNorth = 0 - tempDegreeNorth;
}
Log.d(" north - angle - total", tempDegreeNorth + " - " + angle + " - " + Math.round(tempDegreeNorth + angle));
RotateAnimation raa = new RotateAnimation(
Math.round(tempDegreeNorth + angle),
0.0f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF,
0.5f);
// how long the animation will take place
raa.setDuration(210);
// set the animation after the end of the reservation status
raa.setFillAfter(true);
qiblaIcon.startAnimation(raa);
currentDegree1 = -tempDegreeNorth;
}
private double getAngle() {
GPSTracker gpsTracker = new GPSTracker(this);
double lat1 = toRad(gpsTracker.getLocation().getLatitude());
double lat2 = toRad(21.4266700);
double lon1 = toRad(gpsTracker.getLocation().getLongitude());
double lon2 = toRad(39.8261100);
double dLon = (lon2 - lon1);
double y = sin(dLon) * cos(lat2);
double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
double brng = Math.toDegrees(atan2(y, x));
brng = (brng + 360);
brng = (brng > 360) ? (brng - 360) : brng;
return brng;
}
double toRad(double value) {
value = value * Math.PI / 180;
return value;
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
private void setAds() {
final AdView adViews = (AdView) this.findViewById(R.id.adView);
adRequest = new AdRequest.Builder()
.addTestDevice("253A8ECF2C80597926D6578953E69959").build();
adViews.loadAd(adRequest);
}
private boolean hasPermissions() {
int res = 0;
//string array of permissions,
String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
for (String perms : permissions) {
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)) {
return false;
}
}
return true;
}
private void requestPerms() {
String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissions, PERMS_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode) {
case PERMS_REQUEST_CODE:
for (int res : grantResults) {
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed) {
//user granted all permissions we can perform our task.
} else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
Toast.makeText(this, "GPS Permissions denied.", Toast.LENGTH_SHORT).show();
}
}
}
}
}
I am working on a project in which I am showing two random location and the path between them.I have used this tutorial to accomplish.
Now i want to show the moving image from one location to another.I have already put markers on that two locations.and also I have saved the position in an arraylist.
I had found some similar posts but couldn't solve my issue.
Here is my code for moving the drawable:
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
final Handler handler = new Handler();
int i = 0;
#Override
public boolean onMarkerClick(Marker marker) {
// System.out.println("Marker size:- " + MarkerPoints.size());
handler.post(new Runnable() {
#Override
public void run() {
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.truck_16);
while (i < MarkerPoints.size()) {
MarkerOptions markerOptions = new MarkerOptions().position(MarkerPoints.get(i))
.title("Current Location")
icon(icon);
System.out.println(MarkerPoints.get(i));
mMap.addMarker(markerOptions);
i++;
handler.postDelayed(this, 3000);
}
}
});
return true;
}
});
private double bearingBetweenLocations(LatLng latLng1, LatLng latLng2) {
final double PI = 3.14159;
final double lat1 = latLng1.latitude * PI / 180;
final double long1 = latLng1.longitude * PI / 180;
final double lat2 = latLng2.latitude * PI / 180;
final double long2 = latLng2.longitude * PI / 180;
final double dLon = (long2 - long1);
final double y = Math.sin(dLon) * Math.cos(lat2);
final double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
* Math.cos(lat2) * Math.cos(dLon);
double brng = Math.atan2(y, x);
brng = Math.toDegrees(brng);
brng = (brng + 360) % 360;
return brng;
}
Suppose you have current and destination co-ordinates like below.
private LatLng CURRENT_LOC = new LatLng(23.013171, 72.522300);
private LatLng DESTINATION_LOC = new LatLng(23.013481, 72.522496);
After that add marker on google map
if (googleMap != null)
{
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.truck_16);
MarkerOptions current = new MarkerOptions().position(CURRENT_LOC).title("Current Point");
current_marker = googleMap.addMarker(current);
current_marker.setIcon(icon);
current_marker.setFlat(true);
MarkerOptions destination = new MarkerOptions().position(DESTINATION_LOC).title("Destination Point");
destination_marker = googleMap.addMarker(destination);
destination_marker.setFlat(true);
}
And move marker on click
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.btn_move:
float rotate = (float) bearingBetweenLocations(CURRENT_LOC, DESTINATION_LOC);
rotateMarker(rotate);
break;
}
}
below all are methods that move marker from current location to destnation
private double bearingBetweenLocations(LatLng latLng1,LatLng latLng2)
{
double PI = 3.14159;
double lat1 = latLng1.latitude * PI / 180;
double long1 = latLng1.longitude * PI / 180;
double lat2 = latLng2.latitude * PI / 180;
double long2 = latLng2.longitude * PI / 180;
double dLon = (long2 - long1);
double y = Math.sin(dLon) * Math.cos(lat2);
double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
* Math.cos(lat2) * Math.cos(dLon);
double brng = Math.atan2(y, x);
brng = Math.toDegrees(brng);
brng = (brng + 360) % 360;
return brng;
}
public void rotateMarker(float rotate)
{
if (current_marker != null)
{
//final LatLngInterpolator latLngInterpolator = new LatLngInterpolator.LinearFixed();
ValueAnimator valueAnimator = new ValueAnimator();
//final LatLng startPosition = current_marker.getPosition();
final float startRotation = current_marker.getRotation();
final float angle = 180 - Math.abs(Math.abs(startRotation - rotate) - 180);
final float right = WhichWayToTurn(startRotation, rotate);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
{
#Override
public void onAnimationUpdate(ValueAnimator animation)
{
try
{
if (current_marker == null) // oops... destroying map during animation...
{
return;
}
float v = animation.getAnimatedFraction();
//newPosition = latLngInterpolator.interpolate(v, startPosition, toLatLng(location));
float rotation = startRotation + right * v * angle;
current_marker.setRotation(rotation);
//current_marker.setPosition(newPosition);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
valueAnimator.addListener(new AnimatorListenerAdapter()
{
#Override
public void onAnimationEnd(Animator animation)
{
//current_marker.setPosition(newPosition);
animateMarker(current_marker, DESTINATION_LOC, false);
}
});
valueAnimator.setFloatValues(0, 1);
valueAnimator.setDuration(1000);
valueAnimator.start();
}
}
public void animateMarker(final Marker marker, final LatLng toPosition, final boolean hideMarker)
{
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = googleMap.getProjection();
Point startPoint = proj.toScreenLocation(marker.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 5000;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed / duration);
double lng = t * toPosition.longitude + (1 - t) * startLatLng.longitude;
double lat = t * toPosition.latitude + (1 - t) * startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
if (hideMarker) {
marker.setVisible(false);
} else {
marker.setVisible(true);
}
}
}
});
}
private float WhichWayToTurn(float currentDirection, float targetDirection)
{
float diff = targetDirection - currentDirection;
if (Math.abs(diff) == 0)
{
return 0;
}
if(diff > 180)
{
return -1;
}
else
{
return 1;
}
}
Hope this would help you.
Finally I found a way to accomplish this.May be this is not the best way but it solves the problem.I am posting this so in future if someone needs to do stuff like that,It can be helpful.
I have store all the points in an ArrayList called MarkerPoints that we get from the API and use it to draw the image on ever point.
Here is the code:
public class MyActivity extends FragmentActivity implements Runnable
{
private Thread thread = null;
volatile boolean isRunning;
private ArrayList<LatLng> MarkerPoints; //This arrayList contains all points that are on the route
int i = 0;
Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_on_trip_maps);
isRunning = true;
}
#Override
public void run() {
while (isRunning) {
runOnUiThread(new Runnable() {
#Override
public void run() {
update();
}
});
control();
}
}
public void update() {
if (marker != null) {
marker.remove();
}
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.truck_16);
marker = mMap.addMarker(new MarkerOptions().position(MarkerPoints.get(i))
.title("Current Location")
.icon(icon));
System.out.println(MarkerPoints.get(i));
i++;
if (i > MarkerPoints.size() - 1) {
isRunning = false;
}
}
public void control() {
try {
thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
This will give the moving effect.
I have an array list, ArrayList(), which is used to save lat and lng. I want to get the element inside this array, in order to calculate the distance.
private void whereAmI(){
Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateWithNewLocation(location);
//GPS Listener
manager.addGpsStatusListener(gpsListener);
//Location Listener
int minTime = 0;//ms
int minDist = 0;//meter
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDist, locationListener);
}
GpsStatus.Listener gpsListener = new GpsStatus.Listener() {
#Override
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_STARTED:
Log.d("x=", "GPS_EVENT_STARTED");
Toast.makeText(MapsActivity.this, "GPS_EVENT_STARTED", Toast.LENGTH_SHORT).show();
break;
case GpsStatus.GPS_EVENT_STOPPED:
Log.d("x=", "GPS_EVENT_STOPPED");
Toast.makeText(MapsActivity.this, "GPS_EVENT_STOPPED", Toast.LENGTH_SHORT).show();
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
Log.d("x=", "GPS_EVENT_FIRST_FIX");
Toast.makeText(MapsActivity.this, "GPS_EVENT_FIRST_FIX", Toast.LENGTH_SHORT).show();
break;
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
Log.d("x=", "GPS_EVENT_SATELLITE_STATUS");
break;
}
}
};
LocationListener locationListener = new LocationListener(){
#Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
#Override
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
Log.v("x=", "Status Changed: Out of Service");
Toast.makeText(MapsActivity.this, "Status Changed: Out of Service", Toast.LENGTH_SHORT).show();
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.v("x=", "Status Changed: Temporarily Unavailable");
Toast.makeText(MapsActivity.this, "Status Changed: Temporarily Unavailable", Toast.LENGTH_SHORT).show();
break;
case LocationProvider.AVAILABLE:
Log.v("x=", "Status Changed: Available");
Toast.makeText(MapsActivity.this, "Status Changed: Available", Toast.LENGTH_SHORT).show();
break;
}
}
};
private void showMarkerMe(double lat, double lng){
if (markerMe != null) {
markerMe.remove();
}
MarkerOptions markerOpt = new MarkerOptions();
markerOpt.position(new LatLng(lat, lng));
markerOpt.title("I am here!");
markerMe = mMap.addMarker(markerOpt);
//Toast.makeText(this, "lat:" + lat + ",lng:" + lng, Toast.LENGTH_SHORT).show();
}
private void cameraFocusOnMe(double lat, double lng){
CameraPosition camPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lng))
.zoom(16)
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(camPosition));
}
private void trackToMe(double lat, double lng){
if (traceOfMe == null) {
traceOfMe = new ArrayList<LatLng>();
}
traceOfMe.add(new LatLng(lat, lng));
calculateDistance(traceOfMe);
PolylineOptions polylineOpt = new PolylineOptions();
for (LatLng latlng : traceOfMe) {
polylineOpt.add(latlng);
}
polylineOpt.color(Color.RED);
Polyline line = mMap.addPolyline(polylineOpt);
line.setWidth(10);
}
private void calculateDistance(ArrayList<LatLng> points) {
for (int i =0; i < points.size() -1; i++) {
LatLng pointA = points.get(i);
LatLng pointB = points.get(i + 1);
float[] results = new float[3];
Location.distanceBetween (pointA.latitude, pointA.longitude, pointB.latitude, pointB.longitude, results);
totalD += results[0];
}
}
private void updateWithNewLocation(Location location) {
String where = "";
if (location != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
float speed = location.getSpeed();
long time = location.getTime();
String timeString = getTimeString(time);
speedList.add(""+ speed);
where = "Lng: " + lng +
" Lat: " + lat +
" Speed: " + speed +
"\nTime: " + timeString +
" Provider: " + "gps" +
" Distance: " + totalD ;
showMarkerMe(lat, lng);
cameraFocusOnMe(lat, lng);
trackToMe(lat, lng);
}else{
where = "No location found.";
}
txt.setText(where);
}
I use the codes above to track the route, i want to calculate the total distance, using distanceBetween, but i don't know how to do it.
You have to go through all the point of your trajectory.
And call distanceBetween for each segment of your path.
The distanceBetween method take a float[] paramters and store the results in it.
results[0] = the distance between the two points in meters.
results1 = the initial bearing (Seems it is not always set)
results[2] = the final bearing (Seems it is not always set)
For more information see the documentation there
So Something like that should do the job
private float calculateDistance(ArrayList<LatLng> points) {
float totalDistance = 0f;
for (int i =0; i < points.size() -1; i++ {
LatLng pointA = points.get(i);
LatLng pointB = points.get(i + 1);
float[] results = new float[3];
Location.distanceBetween (pointA.latitude, pointA.longitude, pointB.latitude, pointB.longitude, results);
totalDistance += results[0];
}
return totalDistance;
}
Here is a more optimised solution :
In your activiy you store two variables
LatLng previousLocation
float totalDistance
then in your onLocationChanged method. You call the addToDistance method like that
// Goes inside your Location listener
#Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
addToDistance(location);
}
// Goes inside your activity
public void addToDistance(LatLng newPoint) {
if (previousLocation != null) {
float[] results = new float[3];
Location.distanceBetween (previousLocation.latitude, previousLocation.longitude, newPoint.latitude, newPoint.longitude, results);
totalDistance += results[0];
}
previousLocation = newPoint;
}
I get an error when I click on my action button . I take two coordinates from a class called " GPSTracker " and I return to my class with methods " getLatitude " and " getLongitude " . If I click on my action button I get this error :
09-12 17:07:46.898 24575-24575/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.application.marcoopsone.centrocommercialecampania, PID: 24575
java.lang.NumberFormatException: Invalid double: "4782877,28"
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.initialParse(StringToReal.java:164)
at java.lang.StringToReal.parseDouble(StringToReal.java:282)
at java.lang.Double.parseDouble(Double.java:301)
at com.application.marcoopsone.centrocommercialecampania.FragmentCar.getFila(FragmentCar.java:177)
at com.application.marcoopsone.centrocommercialecampania.FragmentCar$1.onClick(FragmentCar.java:95)
at android.view.View.performClick(View.java:5254)
at android.view.View$PerformClick.run(View.java:21174)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6862)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
if I do run the application on the emulator genymotion , all right ! if I use my samsung tablet I get the error . how do I fix ?
GPSTracker
import ...
public class GPSTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (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 (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, 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 void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if(location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if(location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Fragment Car
public class FragmentCar extends android.support.v4.app.Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private TextView textFila;
private Button btn;
//VARIABILI GPS
GPSTracker gps;
static final int RAGGIO = 6371;
static final double PIGRECO = Math.PI;
double f1_latitudine = 41.00413;
double f1_longitudine = 14.32642;
double f2_latitudine = 41.00399;
double f2_longitudine = 14.32643;
double f3_latitudine = 41.00385;
double f3_longitudine = 14.32645;
double f4_latitudine = 41.0037;
double f4_longitudine = 14.32647;
double f5_latitudine = 41.00359;
double f5_longitudine = 14.32648;
double p_latitudine = 41.00388;
double p_longitudine = 14.32584;
double ps_latitudine = 41.00402;
double ps_longitudine = 14.3248;
private FloatingActionButton mFAB;
public FragmentCar() {
// Required empty public constructor
}
public static android.support.v4.app.Fragment newInstance(String param1, String param2) {
FragmentCar fragment = new FragmentCar();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_car, container, false);
//setupFAB();
textFila = (TextView) layout.findViewById(R.id.textFila);
btn = (Button) layout.findViewById(R.id.buttonSavePosition);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFila();
}
});
return layout;
}
private void setupFAB() {
//define the icon for the main floating action button
ImageView iconFAB = new ImageView(getActivity());
iconFAB.setImageResource(R.drawable.ic_action_new);
//set the appropriate background for the main floating action button along with its icon
mFAB = new FloatingActionButton.Builder(getActivity())
.setContentView(iconFAB)
.setBackgroundDrawable(R.drawable.selector_button_red)
.build();
mFAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFila();
}
});
}
public void getFila(){
gps = new GPSTracker(getActivity());
if(gps.canGetLocation()) {
double latitude = 0;
double longitude = 0;
latitude = new Double(gps.getLatitude());
longitude = new Double(gps.getLongitude());
DecimalFormat df = new DecimalFormat("0.000000");
double lat = Double.parseDouble(df.format(latitude));
double lon = Double.parseDouble(df.format(longitude));
double laRadianti = (lat * PIGRECO) / 180;
double loRadianti = (lon * PIGRECO) / 180;
double f1_latitudineRadianti = (f1_latitudine * PIGRECO) / 180;
double f1_longitudineRadianti = (f1_longitudine * PIGRECO) / 180;
double f2_latitudineRadianti = (f2_latitudine * PIGRECO) / 180;
double f2_longitudineRadianti = (f2_longitudine * PIGRECO) / 180;
double f3_latitudineRadianti = (f3_latitudine * PIGRECO) / 180;
double f3_longitudineRadianti = (f3_longitudine * PIGRECO) / 180;
double f4_latitudineRadianti = (f4_latitudine * PIGRECO) / 180;
double f4_longitudineRadianti = (f4_longitudine * PIGRECO) / 180;
double f5_latitudineRadianti = (f5_latitudine * PIGRECO) / 180;
double f5_longitudineRadianti = (f5_longitudine * PIGRECO) / 180;
double p_latitudineRadianti = (p_latitudine * PIGRECO) / 180;
double p_longitudineRadianti = (p_longitudine * PIGRECO) / 180;
double distanzaUno = ((RAGGIO * Math.acos(Math.sin(laRadianti) * Math.sin(f1_latitudineRadianti) +
Math.cos(laRadianti) * Math.cos(f1_latitudineRadianti) * Math.cos((loRadianti - f1_longitudineRadianti))))) * 1000;
double distanzaDue = ((RAGGIO * Math.acos(Math.sin(laRadianti) * Math.sin(f2_latitudineRadianti) +
Math.cos(laRadianti) * Math.cos(f2_latitudineRadianti) * Math.cos((loRadianti - f2_longitudineRadianti))))) * 1000;
double distanzaTre = ((RAGGIO * Math.acos(Math.sin(laRadianti) * Math.sin(f3_latitudineRadianti) +
Math.cos(laRadianti) * Math.cos(f3_latitudineRadianti) * Math.cos((loRadianti - f3_longitudineRadianti))))) * 1000;
double distanzaQuattro = ((RAGGIO * Math.acos(Math.sin(laRadianti) * Math.sin(f4_latitudineRadianti) +
Math.cos(laRadianti) * Math.cos(f4_latitudineRadianti) * Math.cos((loRadianti - f4_longitudineRadianti))))) * 1000;
double distanzaCinque = ((RAGGIO * Math.acos(Math.sin(laRadianti) * Math.sin(f5_latitudineRadianti) +
Math.cos(laRadianti) * Math.cos(f5_latitudineRadianti) * Math.cos((loRadianti - f5_longitudineRadianti))))) * 1000;
double distanzaPunto = ((RAGGIO * Math.acos(Math.sin(laRadianti) * Math.sin(p_latitudineRadianti) +
Math.cos(laRadianti) * Math.cos(p_latitudineRadianti) * Math.cos((loRadianti - p_longitudineRadianti))))) * 1000;
DecimalFormat df1 = new DecimalFormat("0.00");
double distanzaFilaUno = Double.parseDouble(df1.format(distanzaUno));
double distanzaFilaDue = Double.parseDouble(df1.format(distanzaDue));
double distanzaFilaTre = Double.parseDouble(df1.format(distanzaTre));
double distanzaFilaQuattro = Double.parseDouble(df1.format(distanzaQuattro));
double distanzaFilaCinque = Double.parseDouble(df1.format(distanzaCinque));
double distanzaFilaPunto = Double.parseDouble(df1.format(distanzaPunto));
if(distanzaFilaUno < distanzaFilaDue && distanzaFilaUno < distanzaFilaTre && distanzaFilaUno < distanzaFilaQuattro && distanzaFilaUno < distanzaFilaCinque){
if(distanzaFilaUno > 110 && distanzaFilaUno < 300){
textFila.setText("fila uno");
} else if (distanzaFilaCinque > 300){
textFila.setText("Ops!");
} else {
textFila.setText("1");
}
} else if (distanzaFilaDue < distanzaFilaUno && distanzaFilaDue < distanzaFilaTre && distanzaFilaDue < distanzaFilaQuattro && distanzaFilaDue < distanzaFilaCinque){
if(distanzaFilaDue > 110 && distanzaFilaDue < 300){
textFila.setText("fila due");
} else if (distanzaFilaCinque > 300){
textFila.setText("Ops!");
} else {
textFila.setText("2");
}
} else if (distanzaFilaTre < distanzaFilaUno && distanzaFilaTre < distanzaFilaDue && distanzaFilaTre < distanzaFilaQuattro && distanzaFilaTre < distanzaFilaCinque){
if(distanzaFilaTre > 110 && distanzaFilaTre < 300){
textFila.setText("fila tre");
} else if (distanzaFilaCinque > 300){
textFila.setText("Ops!");
} else {
textFila.setText("3");
}
} else if (distanzaFilaQuattro < distanzaFilaUno && distanzaFilaQuattro < distanzaFilaDue && distanzaFilaQuattro < distanzaFilaTre && distanzaFilaQuattro < distanzaFilaCinque){
if(distanzaFilaQuattro > 110 && distanzaFilaQuattro < 300){
textFila.setText("fila quattro");
} else if (distanzaFilaCinque > 300){
textFila.setText("Ops!");
} else {
textFila.setText("4");
}
} else if (distanzaFilaCinque < distanzaFilaUno && distanzaFilaCinque < distanzaFilaDue && distanzaFilaCinque < distanzaFilaTre && distanzaFilaCinque < distanzaFilaQuattro){
if(distanzaFilaCinque > 110 && distanzaFilaCinque < 300){
textFila.setText("fila cinque");
} else if (distanzaFilaCinque > 300){
textFila.setText("Ops!");
} else {
textFila.setText("5");
}
}
} else {
gps.showSettingsAlert();
}
}
}
the problem is in your line no 177.you are getting comma there,SO you need to replace it by(.)dot to parse it as a double.
Change the line
double distanzaFilaQuattro = Double.parseDouble(df1.format(distanzaQuattro));
to
double distanzaFilaQuattro = Double.parseDouble((df1.format(distanzaQuattro)).replace(",","."));