now i am getting latitude and longitude n time, if i move with my phone the marker also moving according latitude and longitude, but i need to draw a route line if phone change the position. example i have T1, T2, T4, T5 time latitude longitude points i need to draw route line from T1 to T2 and T2 to T3 and T3 to T4 So on in real time, i am unable draw the lines.
MainActivity
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 5445;
private GoogleMap googleMap;
private FusedLocationProviderClient fusedLocationProviderClient;
private Marker currentLocationMarker;
private Location currentLocation;
private boolean firstTimeFlag = true;
private final View.OnClickListener clickListener = view -> {
if (view.getId() == R.id.currentLocationImageButton && googleMap != null && currentLocation != null)
animateCamera(currentLocation);
};
private final LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult.getLastLocation() == null)
return;
currentLocation = locationResult.getLastLocation();
if (firstTimeFlag && googleMap != null) {
animateCamera(currentLocation);
firstTimeFlag = false;
}
showMarker(currentLocation);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment);
supportMapFragment.getMapAsync(this);
findViewById(R.id.currentLocationImageButton).setOnClickListener(clickListener);
mydb = new DatabaseHelper(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
}
private void startCurrentLocationUpdates() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(3000);
//locationRequest.setFastestInterval(1000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
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) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
return;
}
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, mLocationCallback,
Looper.myLooper());
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status)
return true;
else {
if (googleApiAvailability.isUserResolvableError(status))
Toast.makeText(this, "Please Install google play services to use this application", Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED)
Toast.makeText(this, "Permission denied by uses", Toast.LENGTH_SHORT).show();
else if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
startCurrentLocationUpdates();
}
}
private void animateCamera(#NonNull Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(getCameraPositionWithBearing(latLng)));
addLines(latLng);
AddData(location);
}
#NonNull
private CameraPosition getCameraPositionWithBearing(LatLng latLng) {
addLines(latLng);
return new CameraPosition.Builder().target(latLng).zoom(16).build();
}
private void showMarker(#NonNull Location currentLocation) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
BitmapDescriptor icon =
BitmapDescriptorFactory.fromResource(R.drawable.ic_person_pin_circle_black_24dp);
addLines(latLng);
viewAll();
if (currentLocationMarker == null)
currentLocationMarker = googleMap.addMarker(new
MarkerOptions().icon(BitmapDescriptorFactory.defaultMarker()).flat(true).position(latLng));
else
MarkerAnimation.animateMarkerToGB(currentLocationMarker, latLng, new LatLngInterpolator.Spherical());
}
#Override
protected void onStop() {
super.onStop();
if (fusedLocationProviderClient != null)
fusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
#Override
protected void onResume() {
super.onResume();
if (isGooglePlayServicesAvailable()) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
startCurrentLocationUpdates();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
fusedLocationProviderClient = null;
googleMap = null;
}
private void addLines(LatLng latLng) {
LatLng TIMES_SQUARE = new LatLng(latLng.latitude, latLng.longitude);
LatLng BROOKLYN_BRIDGE = new LatLng(latLng.latitude, latLng.longitude);
LatLng LOWER_MANHATTAN = new LatLng(latLng.latitude, latLng.longitude);
Log.i("===Lat", String.valueOf(latLng.latitude));
Log.i("===Longt", String.valueOf(latLng.longitude));
String polyLine = "q`epCakwfP_#EMvBEv#iSmBq#GeGg#}C]mBS{#KTiDRyCiBS";
List<LatLng> polyLineList = Collections.singletonList(TIMES_SQUARE);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng1 : polyLineList) {
builder.include(latLng1);
googleMap.addPolyline((new PolylineOptions())
//.add(TIMES_SQUARE, LOWER_MANHATTAN,TIMES_SQUARE).width(5).color(Color.RED)
//.add( new LatLng(14.2354843, 76.2484165), new LatLng(14.2251, 76.3980)).width(5).color(Color.RED)
.add(new LatLng(latLng.latitude, latLng.longitude), new LatLng(latLng.latitude, latLng.longitude)).addAll(polyLineList).width(5).color(Color.BLUE)
.geodesic(true));
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.color(Color.BLACK);
polylineOptions.width(5);
polylineOptions.startCap(new SquareCap());
polylineOptions.endCap(new SquareCap());
polylineOptions.jointType(ROUND);
polylineOptions.addAll(polyLineList);
Polyline greyPolyLine = googleMap.addPolyline(polylineOptions);
}
;
// move camera to zoom on map
// googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LOWER_MANHATTAN,13));
}
}
MarkerAnimation
public class MarkerAnimation {
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);
handler.postDelayed(this, 16);
}
}
});
}
}
LatLngInterpolator Interface
public interface LatLngInterpolator {
LatLng interpolate(float fraction, LatLng a, LatLng b);
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)));
}
}
}
Consider replacing your addLines method with this which maintains and redraws polyline on every update:
private List<LatLng> polyLineList = new ArrayList<>();
private Polyline greyPolyLine;
private void addToLine(LatLng pt)
{
polyLineList.add(pt);
if (greyPolyLine != null)
{
greyPolyLine.remove();
}
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.color(Color.BLACK);
polylineOptions.width(5);
polylineOptions.startCap(new SquareCap());
polylineOptions.endCap(new SquareCap());
polylineOptions.jointType(ROUND);
polylineOptions.addAll(polyLineList);
greyPolyLine = googleMap.addPolyline(polylineOptions);
}
You addLine was simply drawing a single point on every invocation - a single point is unlikely to be visible.
Probably only need to call it in the showMarker method - not sure why you're calling addLines in the camera methods.
how to push longitude and latitude to server for every certain distances covered
the requirement here to solve to push data to server accoring to 1000m every time
public class LocationUpdateIntentService extends IntentService implements LocationListener {
private static final Location TODO = null;
private Activity activity;
//Location Manager
LocationManager locationManager;
public static Boolean isRunning = false;
Location location;
Map<String, String> inputMap;
float minimumDistanceBetweenUpdates = 10;
double initialLat;
double initialLong;
double finalLat;
double finalLong;
LocationRequest locationRequest;
public LocationUpdateIntentService() {
super("locationUpdateService");
}
public LocationUpdateIntentService(Activity activity) {
super("locationUpdateService");
this.activity = activity;
}
public LocationUpdateIntentService(Activity baseActivity, Map<String, String> inputMap) {
super("locationUpdateService");
this.activity = baseActivity;
this.inputMap = inputMap;
}
#Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (Permissions.getLocationPermissionStatus(activity)){
location = getLastKnownLocation();
}
} else {
location = getLastKnownLocation();
}*/
location = getLastKnownLocation();
LocationRequest request = new LocationRequest();
request.setSmallestDisplacement(minimumDistanceBetweenUpdates);
}
Handler mHandler = new Handler();
Runnable mHandlerTask = new Runnable() {
#Override
public void run() {
if (!isRunning) {
startListening();
}
mHandler.postDelayed(mHandlerTask, C.TIME_LOCATION_UPDATE);
}
};
#Override
protected void onHandleIntent(Intent intent) {
mHandlerTask.run();
}
public void startListening() {
if (location != null) {
location = getLastKnownLocation();
initialLong = location.getLongitude();
initialLat = location.getLatitude();
/* String latitudeintial = String.valueOf(location.getLatitude());
String longitudeintial = String.valueOf(location.getLongitude());
// server Call : Location Update Server Call
LocationUpdateServerCall locationUpdateServerCall = new LocationUpdateServerCall(getApplicationContext());
locationUpdateServerCall.pushLocationUpdateServerCall(latitudeintial, longitudeintial);*/
}
}
public Location getLastKnownLocation() {
Location location = null;
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
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 l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (location == null
|| l.getAccuracy() < location.getAccuracy()) {
location = l;
}
}
if (location == null) {
return null;
}
return location;
}
#Override
public void onLocationChanged(Location location) {
this.location = location;
if (location != null) {
/* String latitude = String.valueOf(location.getLatitude());
String longitude = String.valueOf(location.getLongitude());
// server Call : Location Update Server Call
LocationUpdateServerCall locationUpdateServerCall = new LocationUpdateServerCall(getApplicationContext());
locationUpdateServerCall.pushLocationUpdateServerCall(latitude, longitude);*/
finalLat = location.getLatitude();
finalLong = location.getLongitude();
double distance = CalculationByDistance(initialLat, initialLong, finalLat, finalLong);
if(distance == 500){
LocationUpdateServerCall locationUpdateServerCall = new LocationUpdateServerCall(getApplicationContext());
locationUpdateServerCall.pushLocationUpdateServerCall(String.valueOf(finalLat), String.valueOf(finalLat));
}
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
public double CalculationByDistance(double initialLat, double initialLong, double finalLat, double finalLong) {
/*PRE: All the input values are in radians!*/
double latDiff = finalLat - initialLat;
double longDiff = finalLong - initialLong;
double earthRadius = 6371; //In Km if you want the distance in km
double distance = 2 * earthRadius * Math.asin(Math.sqrt(Math.pow(Math.sin(latDiff / 2.0), 2) + Math.cos(initialLat) * Math.cos(finalLat) * Math.pow(Math.sin(longDiff / 2), 2)));
return distance;
}
}
there are distanceTo method to find distance between loction.below is example of getting distnce between to location over km; after getting specified distance put a req to send position to server;
**location.distanceTo(location) / km)**
You can use method requestLocationUpdates with LocationManager. It will reduce your work. Here is the code.
//it will call every 1000 milisec and on more than 10m distance
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 10, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
//Your API calls here
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
});
I have code which correctly calculates the speed using Service but i am unable to transfer the speed data to my Activity.The speed correctly displays inside onLocationChanged but when i try to get this speed data using gps.getspeed it returns 0.I am not able to understand why i am unable to transfer this data using the getter function.
public class GPSTracker extends Service implements LocationListener {
Context mContext;
private Location mLastLocation;
String format_speed="0";
public GPSTracker(){
}
public static final int LOCATION_PERMISSION_IDENTIFIER = 1;
// 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 static boolean checkPermission(final Context context) {
return ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
checkPermission(mContext);
// 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, 0, 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,
0,
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) {
checkPermission(mContext);
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;
}
public String getspeed(){
return format_speed;
}
/**
* 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) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
double speed = 0;
if (this.mLastLocation != null){
speed=1000*18/5*distance(mLastLocation.getLatitude(),lat,mLastLocation.getLongitude(),lng,0.0,0.0)/(location.getTime() - this.mLastLocation.getTime());
if (UnitLocale.getDefault() == UnitLocale.Imperial) {
speed = speed * 0.621371;
}
else{
speed = speed ;
}
if(speed>200){
speed=0;
}
}
this.mLastLocation = location;
// format_speed=df2.format(speed);
int a = (int) Math.round(Math.abs(speed));
format_speed=String.valueOf(a);
Log.v("speedgps2",format_speed);
}
#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 double distance(double lat1, double lat2, double lon1,
double lon2, double el1, double el2) {
final int R = 6371; // Radius of the earth
Double latDistance = Math.toRadians(lat2 - lat1);
Double lonDistance = Math.toRadians(lon2 - lon1);
Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = R * c * 1000; // convert to meters
double height = el1 - el2;
distance = Math.pow(distance, 2) + Math.pow(height, 2);
return Math.sqrt(distance);
}
}
In my Activity OnCreate i have
GPSService gps;
and then a function to get location data
public void getlocationdata(){
gps = new GPSTracker(TripActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
latinit = String.valueOf(latitude);
loninit = String.valueOf(longitude);
speed=gps.getspeed();
// \n is for new line
// Toast.makeText(getApplicationContext(), "Your Location is - \nLat: "+ latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
Log.v("location",latinit+" "+loninit);
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
I am trying to find the speed of Device. I am getting every good using speed formula. BUT I HAVE ONE PROBLEM. i am getting different lat,long if i put the Mobile at same place, then after few second its location change and also speed,and distance etc.
I want that if device is not in running then it only show one current lat, long(speed=0) not different, because location is not changing.
I am using this class:
public class GPSTracker extends Service implements LocationListener
{
boolean first_time=true;
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 prev_lat=0.0;
double prev_long=0.0;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;// meters (make the time and distance to 0,0 so that we could get the updates very quickly
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 0;//1000 * 60 * 1; // minute
// Declaring a Location Manager
protected LocationManager locationManager;
int hour1=0;
int minute1=0;
int second1=0;
int hour2=0;
int minute2=0;
int second2=0;
int time_dif=0;
private static float distance=0;
static double speed=0;
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)
{
Toast.makeText(getApplicationContext(), "Either Network or GPS is not available in your Mob " , Toast.LENGTH_LONG).show();
// no network provider is enabled
}
else
{
this.canGetLocation = true;
// if GPS Enabled get lat/long using GPS Services
/*if (isNetworkEnabled)
{
//Update the location of a user after t time and d distance... where we have declared time and distance as 0,0 which means to get frequent updates.
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();
//Toast.makeText(getApplicationContext(), "Location "+location.getLatitude() , Toast.LENGTH_LONG).show();
}
}
}
//*/
//else if (isGPSEnabled)
if (isGPSEnabled)
{ //Toast.makeText(getApplicationContext(), "inside 'isGpdenabled' " , Toast.LENGTH_LONG).show();
if (location == null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
//*/
}
} catch (Exception e)
{
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS()
{
if(locationManager != null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation()
{
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enable. 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();
}
//((((( Find distance between two geolocation )))
public float FindDistance(float lat1, float lng1, float lat2, float lng2)
{
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
public double Set_Speed_inKM()
{
speed=speed*3.6; // Formula to Convert M/Sec --> KM/Sec
return speed;
}
#Override
public void onLocationChanged(Location location)
{
if(!first_time )
{
if( prev_lat!=location.getLatitude() & prev_long!=location.getLongitude())
{
//showtoast("Location Changed");
Calendar c = Calendar.getInstance();
second1=c.get(Calendar.SECOND);
if(second2>second1)
second1=60+second1;
time_dif=second1-second2;
time_dif=Math.abs(time_dif);
second2=second1;
distance=FindDistance((float)prev_lat,(float)prev_long,(float)location.getLatitude(),(float)location.getLongitude());
if(time_dif!=0)
speed=distance/time_dif;
Set_Speed_inKM();
Log.e("LOCATION CHANGED", "data"+location.getLatitude()+"\n");
//Calling Function and Passing Value
sendMessageToActivity(location ,time_dif,"NewLocation", this.mContext);
//prev_lat=location.getLatitude();
// prev_long=location.getLongitude();
}
}
prev_lat=location.getLatitude();
prev_long=location.getLongitude();
first_time=false;
}
//((( This Function SEND data 2 ACTIVITY )))))))
private static void sendMessageToActivity(Location l,float time_diff, String msg, Context c)
{
Intent intent = new Intent("GPSLocationUpdates");
// You can also include some extra data.
intent.putExtra("Status", msg);
Bundle b = new Bundle();
b.putParcelable("Location", l);
intent.putExtra("Location", b);
intent.putExtra("speed", ""+speed);
intent.putExtra("time_diff", ""+distance);
LocalBroadcastManager.getInstance(c).sendBroadcast(intent);
}
#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;
}
//Show-Toast Message
public void showtoast(String str)
{
// Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
}
}
The accuracy of the GPS is not absolute, so even a static device will show different locations in successive readings. You can add a method that detects if the mobile is static or not, by reading the accelerometer - if the delta between two readings if bigger than some threshold - the device is moving. If it's too small - it's not moving. To determine the delta - put the device on a table and see what values you get.
I have an app in which I am continuously tracking user's location using Google Plays new service API for Maps. I am updating the location every single second and I am also checking user activity like STILL, TILTING, IN VEHICLE, etc to get the better location tracking. I am able to draw a path using my code but it's not accurate and differs very much from the road where the user actually drives/walk. It always draws the line someway far from the actual user's path.
My Service:-
public class MyService extends Service implements LocationListener {
private final Context mContext;
private static MyService mInstance = null;
private final static String TAG = "RidingTimerService";
boolean isGPSEnabled = false;
private long mStartTime = 0L;
private long timeInMilliseconds = 0L;
private long timeSwapBuff = 0L;
private long updatedTime = 0L;
private Handler mHandler = null;
private int mHours = 0;
// Declaring a Location Manager
private LocationManager mLocationManager = null;
private Location mCurrentLocation = null; // location
private double[][] positions;
private long[] times;
private final Integer data_points = 2; // how many data points to calculate
private double mTravelledDistance = 0.0f;
private SharedPreferences mPreferences = null;
private ArrayList<LatLng> mDirectionsPoints = new ArrayList<LatLng>();
public boolean mIsPhoneMoving = false;
public int mActivityType = -1;
int counter = 0;
private IntentFilter mBroadcastFilter;
private DetectionRequester mDetectionRequester;
private DetectionRemover mDetectionRemover;
public MyService() {
mContext = this;
}
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
// two arrays for position and time.
positions = new double[data_points][2];
times = new long[data_points];
mStartTime = SystemClock.uptimeMillis();
mHandler = new Handler();
mHandler.postDelayed(countDownTimerThread, 0);
mPreferences = getSharedPreferences(MyPreferences.PREFERENCES,
Context.MODE_PRIVATE);
// Create a new Intent filter for the broadcast receiver
mBroadcastFilter = new IntentFilter(
MyConstants.ACTION_REFRESH_STATUS_LIST);
mBroadcastFilter.addCategory(MyConstants.CATEGORY_LOCATION_SERVICES);
// Get detection requester and remover objects
mDetectionRequester = new DetectionRequester(this);
mDetectionRemover = new DetectionRemover(this);
mDirectionsPoints.clear();
}
/**
* Pause the timer
*/
public void pauseRide() {
timeSwapBuff += timeInMilliseconds;
mHandler.removeCallbacks(countDownTimerThread);
mLocationManager.removeUpdates(this);
}
/**
* Restart the timer
*/
public void reStartRide() {
mStartTime = SystemClock.uptimeMillis();
mHandler.postDelayed(countDownTimerThread, 0);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, this);
}
#Override
public void onDestroy() {
mHandler.removeCallbacks(countDownTimerThread);
mLocationManager.removeUpdates(this);
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
getLocation();
return super.onStartCommand(intent, flags, startId);
}
/**
* Timer thread
*/
private final Runnable countDownTimerThread = new Runnable() {
public void run() {
mHours = 0;
timeInMilliseconds = SystemClock.uptimeMillis() - mStartTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
final int mins = secs / 60;
mHours = mins / 60;
secs = secs % 60;
final Message msg = new Message();
final Bundle bundle = new Bundle();
bundle.putInt(MyPreferences.BROADCAST_CODES, 300);
bundle.putString(
"time",
String.format("%02d", mHours) + ":"
+ String.format("%02d", mins) + ":"
+ String.format("%02d", secs));
msg.setData(bundle);
final Intent intent = new Intent(MyConstants.BROADCAST_INTENT);
intent.putExtras(bundle);
sendBroadcast(intent);
mHandler.postDelayed(this, 1000);
}
};
#Override
public IBinder onBind(final Intent intent) {
return null;
}
#Override
public void onLocationChanged(final Location location) {
if (location != null) {
LocationUtils.sLatitude = location.getLatitude();
LocationUtils.sLongitude = location.getLongitude();
mDirectionsPoints.add(new LatLng(LocationUtils.sLatitude,
LocationUtils.sLongitude));
riderLocation(location);
} else {
Log.i(TAG, "Location is not available.");
}
}
/**
* Calculate speed, distance and average speed. Send Broadcast which
* received by activities
*
* #param location
*/
private void riderLocation(final Location location) {
DecimalFormat formatter = new DecimalFormat("#0.00");
double distance = 0.0;
Double speed = 0.0;
long t1 = 0l;
final float[] results = new float[3];
positions[counter][0] = location.getLatitude();
positions[counter][1] = location.getLongitude();
times[counter] = location.getTime();
final Bundle bundle = new Bundle();
bundle.putInt(MyPreferences.BROADCAST_CODES, 200);
distance = calculateDistance(positions[counter][0],
positions[counter][1], positions[(counter + (data_points - 1))
% data_points][0],
positions[(counter + (data_points - 1)) % data_points][1]);
Location.distanceBetween(positions[counter][0], positions[counter][1],
positions[(counter + (data_points - 1)) % data_points][0],
positions[(counter + (data_points - 1)) % data_points][1],
results);
mTravelledDistance += results[0] / 1000;
LocationUtils.sDistance = formatter
.format((mTravelledDistance * 100.0) / 100.0);
final double averageSpeed = mTravelledDistance / mHours;
LocationUtils.sAverageSpeed = formatter
.format((averageSpeed * 100.0) / 100.0);
if (location.hasSpeed()) {
speed = location.getSpeed() * 3.6;
LocationUtils.sSpeed = speed.intValue();
} else {
try {
t1 = times[counter]
- times[(counter + (data_points - 1)) % data_points];
} catch (final NullPointerException e) {
// all good, just not enough data yet.
}
speed = (distance / t1) * 3.6;
LocationUtils.sSpeed = speed.intValue();
counter = (counter + 1) % data_points;
}
LocationUtils.sLatitude = location.getLatitude();
LocationUtils.sLongitude = location.getLongitude();
final Intent intent = new Intent(MyConstants.BROADCAST_INTENT);
intent.putExtras(bundle);
sendBroadcast(intent);
}
public void onProviderDisabled(final String arg0) {
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(final String arg0) {
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
/**
* #return location
*/
public Location getLocation() {
try {
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = mLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) {
// no network provider is enabled
showSettingsAlert();
} else {
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, this);
Log.d(TAG, "GPS Enabled");
if (mCurrentLocation == null) {
if (mLocationManager != null) {
mCurrentLocation = mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mCurrentLocation != null) {
LocationUtils.sLatitude = mCurrentLocation
.getLatitude();
LocationUtils.sLongitude = mCurrentLocation
.getLongitude();
}
}
} else {
LocationUtils.sLatitude = mCurrentLocation
.getLatitude();
LocationUtils.sLongitude = mCurrentLocation
.getLongitude();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return mCurrentLocation;
}
/**
* #fn public static RidingTimerService getInstance()
* #brief returns instance of the service.
* #return RidingTimerService instance
*/
public static MyService getInstance() {
return mInstance;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
/**
* Reset all the values stored in Preferences
*/
public void resetAllText() {
mPreferences.edit().putString(MyPreferences.LATITUDE, "0.0").commit();
mPreferences.edit().putString(MyPreferences.LONGITUDE, "0.0")
.commit();
mPreferences.edit().putString(MyPreferences.SPEED, "0.0").commit();
mPreferences.edit().putString(MyPreferences.AVERAGE_SPEED, "0.0")
.commit();
mPreferences.edit().putString(MyPreferences.DISTANCE, "0.0").commit();
}
/**
* Respond to "Start" button by requesting activity recognition updates.
*
* #param view
* The view that triggered this method.
*/
public void onStartUpdates() {
// Pass the update request to the requester object
mDetectionRequester.requestUpdates();
}
/**
* Respond to "Stop" button by canceling updates.
*
* #param view
* The view that triggered this method.
*/
public void onStopUpdates() {
// Pass the remove request to the remover object
mDetectionRemover.removeUpdates(mDetectionRequester
.getRequestPendingIntent());
/*
* Cancel the PendingIntent. Even if the removal request fails,
* canceling the PendingIntent will stop the updates.
*/
mDetectionRequester.getRequestPendingIntent().cancel();
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS");
alertDialog.setMessage("GPS is not enabled. Do you want to enable it?");
// 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();
}
/**
* #return List of Direction points
*/
public ArrayList<LatLng> getDirectionsPoints() {
if (mDirectionsPoints != null) {
return mDirectionsPoints;
} else {
mDirectionsPoints = new ArrayList<LatLng>();
return mDirectionsPoints;
}
}
/**
* Calculate distance
*
* #param lat1
* #param lon1
* #param lat2
* #param lon2
* #return
*/
private double calculateDistance(final double lat1, final double lon1,
final double lat2, final double lon2) {
// haversine great circle distance approximation, returns meters
final double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2))
+ Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2))
* Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60; // 60 nautical miles per degree of seperation
dist = dist * 1852; // 1852 meters per nautical mile
return dist;
}
private double deg2rad(final double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(final double rad) {
return (rad * 180.0 / Math.PI);
}
}
I kept location updates every 1 seconds and activity recognition updates every 3 seconds. I am able to get the location but path is not drawn properly in Google maps.
Code to draw path :-
public class MapsActivity extends FragmentActivity {
private static GoogleMap mGoogleMap = null;
private static final String TAG = "MapsActivity";
private Button mBtnStartRide, mBtnPauseRide, mBtnStopRide = null;
private static TextView mTxtLatLong, mTxtTimer, mTxtTotalSize,
mTxtSpeed = null;
private static PolylineOptions mPolyLineOptions = null;
// Storing the directions returned by the direcction api
private SharedPreferences mPreferences = null;
private MapsBroadcastReceiver receiver = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
receiver = new MapsBroadcastReceiver();
mPreferences = getSharedPreferences(TestPreferences.PREFERENCES,
Context.MODE_PRIVATE);
mTxtLatLong = (TextView) findViewById(R.id.txtLatLong);
mTxtTimer = (TextView) findViewById(R.id.txtTimer);
mTxtTotalSize = (TextView) findViewById(R.id.txtDirectionsSize);
mTxtSpeed = (TextView) findViewById(R.id.txtSpeed);
mBtnStartRide = (Button) findViewById(R.id.btn_start_ride);
mBtnPauseRide = (Button) findViewById(R.id.btn_pause_ride);
mBtnStopRide = (Button) findViewById(R.id.btn_stop_ride);
final Button mBtnCenter = (Button) findViewById(R.id.btn_center);
mBtnCenter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
animateCameraTo();
}
});
mBtnStartRide.setOnClickListener(btnStartRideClickListener);
mBtnPauseRide.setOnClickListener(btnPauseRideClickListener);
mBtnStopRide.setOnClickListener(btnStopRideClickListener);
initilizeMap();
}
/**
* Start Ride Button Click Listener
*/
private OnClickListener btnStartRideClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (mPreferences.getBoolean(TestPreferences.IS_RIDE_PAUSE, false)) {
if (MyService.getInstance() != null) {
MyService.getInstance().reStartRide();
}
} else {
startService(new Intent(MapsActivity.this,
MyService.class));
}
mPreferences.edit().putBoolean(TestPreferences.IS_RIDE_START, true)
.commit();
mPreferences.edit().remove(TestPreferences.IS_RIDE_PAUSE).commit();
mPreferences.edit().remove(TestPreferences.IS_RIDE_STOPPED)
.commit();
mBtnStartRide.setVisibility(View.GONE);
mBtnPauseRide.setVisibility(View.VISIBLE);
mBtnStopRide.setVisibility(View.VISIBLE);
}
};
/**
* Start Ride Button Click Listener
*/
private OnClickListener btnPauseRideClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
MyService.getInstance().pauseRide();
mPreferences.edit().putBoolean(TestPreferences.IS_RIDE_PAUSE, true)
.commit();
mPreferences.edit()
.putBoolean(TestPreferences.IS_RIDE_START, false).commit();
mBtnStartRide.setVisibility(View.VISIBLE);
mBtnPauseRide.setVisibility(View.GONE);
mBtnStopRide.setVisibility(View.VISIBLE);
}
};
/**
* Stop Ride Button Click Listener
*/
private OnClickListener btnStopRideClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(MapsActivity.this, MyService.class));
mPreferences.edit().remove(TestPreferences.IS_RIDE_PAUSE).commit();
mPreferences.edit()
.putBoolean(TestPreferences.IS_RIDE_START, false).commit();
mPreferences.edit()
.putBoolean(TestPreferences.IS_RIDE_STOPPED, true).commit();
mBtnStartRide.setVisibility(View.VISIBLE);
mBtnPauseRide.setVisibility(View.GONE);
mBtnStopRide.setVisibility(View.GONE);
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter(
MyConstants.BROADCAST_INTENT));
initilizeMap();
if (mPreferences.getBoolean(TestPreferences.IS_RIDE_START, false)) {
mBtnStartRide.setVisibility(View.GONE);
mBtnPauseRide.setVisibility(View.VISIBLE);
mBtnStopRide.setVisibility(View.VISIBLE);
} else if (mPreferences
.getBoolean(TestPreferences.IS_RIDE_PAUSE, false)) {
mBtnStartRide.setVisibility(View.VISIBLE);
mBtnPauseRide.setVisibility(View.GONE);
mBtnStopRide.setVisibility(View.VISIBLE);
} else if (mPreferences.getBoolean(TestPreferences.IS_RIDE_STOPPED,
false)) {
// Show start button and gone Pause & Stop both
mBtnStartRide.setVisibility(View.VISIBLE);
mBtnPauseRide.setVisibility(View.GONE);
mBtnStopRide.setVisibility(View.GONE);
} else {
// Show start button and gone Pause & Stop both
mBtnStartRide.setVisibility(View.VISIBLE);
mBtnPauseRide.setVisibility(View.GONE);
mBtnStopRide.setVisibility(View.GONE);
}
setAllText();
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
protected void onDestroy() {
super.onDestroy();
mGoogleMap = null;
}
/**
* Function to load map. If map is not created it will create it for you
* */
private void initilizeMap() {
if (mGoogleMap == null) {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (mGoogleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
} else {
mPolyLineOptions = new PolylineOptions().width(6).color(
Color.BLUE);
mGoogleMap.setTrafficEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
if (MyService.getInstance() != null
&& MyService.getInstance().getDirectionsPoints() != null
&& !MyService.getInstance().getDirectionsPoints()
.isEmpty()
&& MyService.getInstance().getDirectionsPoints()
.size() >= 1) {
mGoogleMap.addMarker(new MarkerOptions()
.position(
MyService.getInstance()
.getDirectionsPoints().get(0))
.anchor(0.8f, 1.0f).title("Your Location"));
animateCameraTo(MyService.getInstance()
.getDirectionsPoints().get(0).latitude,
MyService.getInstance().getDirectionsPoints()
.get(0).longitude);
}
}
} else {
mPolyLineOptions = new PolylineOptions().width(6).color(Color.BLUE);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
if (MyService.getInstance() != null
&& MyService.getInstance().getDirectionsPoints() != null
&& !MyService.getInstance().getDirectionsPoints()
.isEmpty()
&& MyService.getInstance().getDirectionsPoints().size() >= 1) {
Log.i(TAG, "Lat long in resume2222222222 = "
+ MyService.getInstance().getDirectionsPoints()
.get(0).latitude
+ ", "
+ MyService.getInstance().getDirectionsPoints()
.get(0).longitude);
mGoogleMap.addMarker(new MarkerOptions()
.position(
MyService.getInstance().getDirectionsPoints()
.get(0)).anchor(0.8f, 1.0f)
.title("Your Location"));
animateCameraTo(MyService.getInstance().getDirectionsPoints()
.get(0).latitude, MyService.getInstance()
.getDirectionsPoints().get(0).longitude);
}
}
}
/**
* #author Scorpion
*
*/
private class MapsBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getExtras().getInt(TestPreferences.BROADCAST_CODES)) {
case 100:
showErrorDialog(intent.getExtras().getInt(
TestPreferences.BROADCAST_CODES));
break;
case 200:
setAllText();
break;
case 300:
if (intent.getExtras().getString("time") != null) {
mTxtTimer.setText("Timer - "
+ intent.getExtras().getString("time"));
} else {
mTxtTimer.setText("Timer - 00:00:00");
}
break;
default:
break;
}
if (MyService.getInstance() != null
&& !MyService.getInstance().getDirectionsPoints()
.isEmpty()
&& MyService.getInstance().getDirectionsPoints().size() == 1) {
mGoogleMap.addMarker(new MarkerOptions()
.position(
MyService.getInstance().getDirectionsPoints()
.get(0)).anchor(0.8f, 1.0f)
.title("Your Location"));
}
}
}
/**
*
*/
public void setAllText() {
mTxtLatLong.setText("Lat - " + LocationUtils.sLatitude + ", Lng - "
+ LocationUtils.sLongitude);
mTxtSpeed.setText("Speed - " + LocationUtils.sSpeed);
mTxtTotalSize.setText("Distance - " + LocationUtils.sDistance);
}
/**
* Animate to position on Google Maps
*
* #param lat
* #param lng
*/
private void animateCameraTo() {
// Saving the points in a polyline
if (MyService.getInstance() != null
&& MyService.getInstance().getDirectionsPoints() != null
&& !MyService.getInstance().getDirectionsPoints().isEmpty()) {
mPolyLineOptions.geodesic(true);
mPolyLineOptions.addAll(MyService.getInstance()
.getDirectionsPoints());
// Drawing the path on the map Polyline route =
mGoogleMap.addPolyline(mPolyLineOptions);
int index = MyService.getInstance().getDirectionsPoints().size() - 1;
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(MyService.getInstance().getDirectionsPoints()
.get(index)).zoom(20).build();
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
}
/**
* Animate to position on Google Maps
*
* #param lat
* #param lng
*/
private void animateCameraTo(final double lat, final double lng) {
// Saving the points in a polyline
if (MyService.getInstance() != null
&& MyService.getInstance().getDirectionsPoints() != null
&& !MyService.getInstance().getDirectionsPoints().isEmpty()) {
mPolyLineOptions.geodesic(true);
mPolyLineOptions.addAll(MyService.getInstance()
.getDirectionsPoints());
// Drawing the path on the map
mGoogleMap.addPolyline(mPolyLineOptions);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lng)).zoom(20).build();
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
}
/**
* Show a dialog returned by Google Play services for the connection error
* code
*
* #param errorCode
* An error code returned from onConnectionFailed
*/
private void showErrorDialog(int errorCode) {
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(errorCode,
MapsActivity.this,
LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment in which to show the error dialog
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
// Set the dialog in the DialogFragment
errorFragment.setDialog(errorDialog);
// Show the error dialog in the DialogFragment
errorFragment.show(getSupportFragmentManager(),
LocationUtils.APPTAG);
}
}
}
Coordinate results got from Location provider :-
23.030392522689674, 72.5570888165469, 23.030408166940184, 72.55708600340783, 23.030451207802273, 72.55708215400317, 23.030448342522195, 72.5570607428365, 23.03045605637773, 72.55702903413072, 23.03046687434995, 72.55702007867455, 23.030481227996425, 72.55702017125606, 23.03049188235562, 72.55701618151457, 23.030501580461667, 72.55701051075931, 23.030506644074638, 72.55700568837983, 23.030510243171772, 72.55699463185964, 23.03051656621021, 72.55698811382064, 23.030523584332027, 72.55698589863236, 23.030527893257556, 72.5569835596, 23.03052731568596, 72.55698681171178, 23.030533706759005, 72.55699683791043, 23.03053795413862, 72.5570022232021, 23.03054422659466, 72.55700788646914, 23.030550353227323, 72.5570133047868, 23.03056167617575, 72.5570171806126, 23.030572274532982, 72.55702744953462, 23.03057623596164, 72.55703687229187, 23.03058756510295, 72.55703589208271, 23.030591797598742, 72.5570396833694, 23.030597556470788, 72.55703954449652, 23.030602030769657, 72.55704359454182, 23.030606735158617, 72.55704993131606, 23.030611670633565, 72.55705060538087,23.030618875802222, 72.55705181604097, 23.030629137631596, 72.55705043471286, 23.030651405170016, 72.55705440295588, 23.03066642161307, 72.55705285209174, 23.030690454277963, 72.55703884780276, 23.030708214416187, 72.55703489882957, 23.03072341369183, 72.5570340196122, 23.030737371000015, 72.55703289416898, 23.03075088423441, 72.55703750535102, 23.030767572625837, 72.55704489874579, 23.030794398930176, 72.55703870239826, 23.03081655932613, 72.55702474270966, 23.030827505666753, 72.5570121351611, 23.03083720431765, 72.55700390084714, 23.03084624667527, 72.55700122660554, 23.030859495795887, 72.55699948514881, 23.030870357210333, 72.55699625144317, 23.030881843633054
This code will work
GoogleMap map;
// ... get a map.
// Add a thin red line from London to New York.
Polyline line = map.addPolyline(new PolylineOptions()
.add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
.width(5)
.color(Color.RED));
You should split your problem into the aspects of data collection and data display.
Therefore take two coordinates you precisely know and draw a straight polyline on google maps.
If it's really displayed at the wrong location, GoogleMap has indeed a bug, which BTW I don't believe.
Then print out your coordinates e.g. to LogCat before drawing them and check the coordinates. If they are wrong, it is not a problem of GoogleMaps but of the LocationProvider or of how you use it.
If the coordinates are collected correctly, you may pick them somehow up from LogCat and use them directly in your code to draw a polyline. If then the polyline is displaced, you may again have found a bug in GoogleMap. Then you should paste the coordinates here, so someone can reproduce it. It may be device dependent. I never had a polyline which did not match the map.
Your code for drawing the path looks strange.
Inside the for-loop you should only add the points to an instance of PolylineOptions (which you create before entering the for loop).
Then, after the for-loop you can add the width, color etc. to the polylineOptions object and finally use that in mGoogleMap.addPolyline().
In your coding, you are somehow adding a new polyline for each point (I am wondering that this draws lines at all, as each "line" consists of one point only.).