I am in constant location but i am getting gps updates continuosly and plot the line in constant location also.How to stop gps updates in constant location?
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
getActivity().runOnUiThread(new Runnable() {
public void run() {
gps = new GPSTracker(getActivity());
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
if(latitude>0.0&&longitude>0.0){
Toast.makeText(
getActivity(),
"Your Location is - \nLat: " + latitude
+ "\nLong: " + longitude,
Toast.LENGTH_SHORT).show();
}
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
RouteManager.sourceMarker(getActivity(), latLng,
googleMap, markpos, 0);
markpos++;
points.add(latLng);// addding Latlng to points array
Log.d("pointssize", "pointskal--->" + points.size());
Double distance = 0.0;
//if more than one point we can find duplicate points getting or not,if getting duplicate we remove duplicate point
if (points.size() > 1) {
// 2.comparing prev and nextlatitudes and longitudes
boolean duplicate = routemanage.isDuplicate(points,
googleMap);
if (duplicate) {
points.remove(points.size() - 1);
Log.d("pointssize", "pointskalremnoveafter--->"
+ points.size());
duplicate = false;
} else {
int size = points.size();
//if not duplicate we can find out the distance
distance = routemanage.findDistanceOnRoute(
points.get(size - 2).latitude,
points.get(size - 2).longitude,
points.get(size - 1).latitude,
points.get(size - 1).longitude);
Log.d("sorrry", "distance initaial" + distance);
if (distance < 1) {
//if distance is less than 1 meter we simply remove the point
points.remove(points.size() - 1);
Log.d("pointssize",
"distance lessthan 1--->"
+ points.size());
} else {
// we have to check distance >1 m we can draw the route
sum = sum + distance;
RouteManager.drawRoute(getActivity(),
points, googleMap, sum);
Log.d("sorrry", "sorry dad sum" + sum);
settingmaprunDetails(points.get(size - 1),
sum);
}
duplicate = true;
}// else
}// if
//if points size is <=1 we can't draw the route
else if (points.size() == 1) {
settingmaprunDetails(points.get(0), 0.0);
}
}
I am attaching screen shot please see once and give me solution to avoid this clumsy ness of plotting the route on google map.
you can set Smallest Displacement somewhere in your GPSTracker (where the locationManager) is created. For example:
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Set the Smallest Displacement sets the minimum displacement between location updates in meters. By default this is 0. You can reduce the signal jitter using this with a reasonable value.
Related
I'm hoping someone can help with this.
I've seen many posts and answers but none of them seem to address my specific problem, but if I've missed one, I apologise in advance.
I'm building a small app that stores a phones current longitude and latitude as doubles. This is done via android's LocationManager
#TargetApi(23)
private void initLocationService(Context context) {
if (Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
this.longitude = 0.0;
this.latitude = 0.0;
this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// Get GPS and network status
this.isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
this.isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (forceNetwork) isGPSEnabled = false;
if (!isNetworkEnabled && !isGPSEnabled) {
// cannot get location
this.locationServiceAvailable = false;
}
else
{
this.locationServiceAvailable = 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);
updateCoordinates();
}
}//end if
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateCoordinates();
}
}
}
} catch (Exception ex) {
}
}
public void updateCoordinates()
{
longitude = location.getLongitude();
latitude = location.getLatitude();
}
I've got a set of longitude and latitude coordinates hardcoded into the app, but need a way to work out if my user is within a specific metre radius of a hardcoded point.
I'm using just the Android API's for the project and can't deviate from that.
I've already found out how to convert the longitude and latitude from degrees to metres:
public double longOffset(int offsetX, double lon){
double longoff = offsetX / earthRadius;
return lon + longoff * 180 / Math.PI;
}
public double latOffset(int offsetY, double lat){
double latoff = offsetY / (earthRadius * cos(Math.PI*lat/180));
return lat + latoff * 180 / Math.PI;
}
But I admit to being stumped on the rest.
I'm wondering if creating a small bounding box around the longitude and latitude and then using a method similar to the one shown here:
http://www.sanfoundry.com/java-program-check-whether-given-point-lies-given-polygon/
I'm getting to the point now where i'm going crosseyed so any help would be appreciated.
Like #EugenPechanec says, you can use SphericalUtil.computeDistanceBetween() from Google Maps Android API utility library . Something like this:
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
LatLng positionLatLng = new LatLng(latitude, longitude);
// sample hardcoded point.
LatLng specificPointLatLang = new LatLng(1.333434, 1.3333);
// Returns the distance between two LatLngs, in meters.
double distance = SphericalUtil.computeDistanceBetween(positionLatLng, specificPointLatLang);
i want to create an activity which will restrict the users to access the activity inside some location parameters. if they are outside then they cannot access the activity. The location parameter is big or large area, so access outside even upto 50Km is not an issue. but how to make it restrict inside the particular confinement?
Edit:
i am asking how to define the location restriction?, i am asking if the location is 100N and 100E, so how will i restrict, or can i restrict it using places name?
can anyone explain with some example or a bit of code!?
if you integrated the location api, you can use this to calculate the distance between your particular location and the current location
Location currentLoc;
float radius = 50.0;
float distance = loc.distanceTo(PARTICULAR_LOCATION);
if (distance < radius) {
//start activity
}
here the PARTICULAR_LOCATION is the location of the some area you mentiond
You can calculate the Distance between the Location of the Person and the Location with parameters as
Location personLocation =...; // Person's Location
Location restrictedLocation =...; // Location with constraints
// Calculate distance in meters to person's location from restricted location
float distance = restrictedLocation.distanceTo(personLocation);
float distanceInKms = distance / 1000;
if (distanceInKms > 50) {
// Place code for person outside restricted location's 50 KM radius
} else {
// Place code for person inside restricted location's 50 KM radius
}
In your onLocationChanged you can check if a user is inside a given location or not
#Override
public void onLocationChanged(Location location) {
float[] distance = new float[2];
Location.distanceBetween( location.getLatitude(), location.getLongitude(),
locationtomonitor.latitude, locationtomonitor.longitude, distance);
/// distance in meters
if( distance[0] > 1 ){
Toast.makeText(getBaseContext(), " Outside, Distance in meters: " + locationtomonitor.getRadius(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside, distance in meters : " + distance[0] , Toast.LENGTH_LONG).show();
}
}
if you want to check a specific country or city, you can use IP to location:
just send a simple get Request to http://ip-api.com/json url and you will get a json data containing info about country, city, zip code etc.
I am just trying to figure out what can I do to ensure I get precise GPS Coordinates from the mobile device. When I add the distances together, I get a crazy reading that I have gone 8m when the phone has not moved from my table. I do not know if it is because of the way I have set up my LocationRequest. I was reading on google something about GPS coordinates being 68% accurate, and some readings may fall out of the 68%... perhaps I should do something to remove the inaccurate readings??
Here is the location request I have created, so I can receive the location updates:
private void createLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(2000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//Some other code below which checks location settings
}
This is my onLocationChanged... this is where I get updates of the new location, and then calculate the distance between the two points:
#Override
public void onLocationChanged(Location location) {
//For the first location update, we will assume this is the starting point
if (currentLocation == null) {
currentLocation = location;
}
float distance = 0L;
double height = 0;
double speed = 0;
height = location.getAltitude();
if (runStarted && !runPaused) {
locationsList.add(location); //This adds the current location to the list
runnerLocations.add(location); //This adds the current route the runner is running (without pauses)
} else {
locationsList.add(location);
}
//Calculate the distance from the last recorded gps point
if (currentLocation != null && runStarted && !runPaused){
distance = currentLocation.distanceTo(location);
}
currentLocation = location;
//move the map view to the user's current location, regardless of their running state (paused or run)
mapObject.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 18));
if (runStarted && !runPaused) {
if (location.getSpeed() > 0) {
speed = location.getSpeed() * 3.6;// convert m/sec to km/h
}
DecimalFormat format = new DecimalFormat("###.##");
speed = Double.valueOf(format.format(speed));
recordedSpeeds.add(speed);
totalDistance = totalDistance + distance;
updateUI(speed, location, distance);
if (height > 0) {
height = Double.valueOf(format.format(height));
}
calculateCurrentCaloriesBurnt(height, speed);
}
}
I was thinking of calculating the distances manually, with some formula. What else can I try, to get accurate distance calculations?
I'm trying to calculate distance between LatLng points. It's easy to calculate for two coordinates. I have to calculate distance between more than two LatLngs and calculate the cumulative distance from a set of LatLngs. I calculated distance between two points as per the following code.
tvDistance=(TextView)findViewById(R.id.textView4);
Location loc1=new Location("");
loc1.setLatitude(11.2805);
loc1.setLongitude(77.5989);
Location loc2=new Location("");
loc2.setLatitude(11.2801);
loc2.setLongitude(77.5976);
DecimalFormat format=new DecimalFormat("#.##");
double distanceInMeters = loc1.distanceTo(loc2)/1000;
tvDistance.setText(format.format(distanceInMeters) + " Km's");
Now I have for example sixteen LatLng points. First is starting place and last is stopping place. I have the LatLngs in a ArrayList. tried the following code. But it caused ArrayIndexOutOfBoundException.
Do anybody know a method please share with me. Thanks.
private void calculateDistance() {
for (int i=0;i<coordList.size();i++){
LatLng l1=coordList.get(i);
double lat1=l1.latitude;
double lng1=l1.longitude;
Location location1=new Location("");
location1.setLatitude(lat1);
location1.setLongitude(lng1);
LatLng l2=coordList.get(i+1);
double lat2=l2.latitude;
double lng2=l2.longitude;
Location location2=new Location("");
location2.setLatitude(lat2);
location2.setLongitude(lng2);
DecimalFormat format=new DecimalFormat("#.##");
double distance=location1.distanceTo(location2)/1000;
Toast.makeText(MainPage.this,format.format(distance) + " Km's",Toast.LENGTH_SHORT).show();
}
}
You can use SphericalUtil.computeLength method:
http://googlemaps.github.io/android-maps-utils/javadoc/com/google/maps/android/SphericalUtil.html#computeLength-java.util.List-
Sources: https://github.com/googlemaps/android-maps-utils/blob/master/library/src/com/google/maps/android/SphericalUtil.java
The line
LatLng l2=coordList.get(i+1);
causes the exception.
jon
->Its easy to calculate the distance if you have sets of latitudes and longitudes
ArrayList<RideRoutes> ride_route_list = new ArrayList<>();
//suppose "ride_route_list" contains collections of Latitudes and longitudes
String distance_covered_str;
double total_meters = 0.0;
for(int i = 0; i < (ride_route_list.size() - 1); i++){
double previous_latitude = Double.parseDouble(ride_route_list.get(i).getRout_latitude());
double previous_longitude = Double.parseDouble(ride_route_list.get(i).getRout_longitude());
double updated_latitude = Double.parseDouble(ride_route_list.get(i+1).getRout_latitude());
double updated_longitude = Double.parseDouble(ride_route_list.get(i+1).getRout_longitude());
Location start_latlng = new Location("location_previous");
start_latlng.setLatitude(previous_latitude);
start_latlng.setLongitude(previous_longitude);
Location end_latlng = new Location("location_updated");
end_latlng.setLatitude(updated_latitude);
end_latlng.setLongitude(updated_longitude);
total_meters += start_latlng.distanceTo(end_latlng);
}
double distance_covered_km = total_meters / 1000;
distance_covered_str = String.format(Locale.getDefault(), "%.2f", distance_covered_km);
Note:
->here ride_route_list is an ArrayList which contains the list of Latitude and longitude
RideRoutes Class Structure:
public class RideRoutes {
private String rout_latitude;
private String rout_longitude;
public RideRoutes(String rout_latitude, String rout_longitude) {
this.rout_latitude = rout_latitude;
this.rout_longitude = rout_longitude;
}
public String getRout_latitude() {
return rout_latitude;
}
public void setRout_latitude(String rout_latitude) {
this.rout_latitude = rout_latitude;
}
public String getRout_longitude() {
return rout_longitude;
}
public void setRout_longitude(String rout_longitude) {
this.rout_longitude = rout_longitude;
}
}
I'm trying to calculate the route between two locations with a code that you already know.
In my case the first location is MY location and the second location is the nearest LatLng
of a path.
This code below calculates the nearest LatLng:
private LatLng nearestLatLng(Location mCurrentLocation) {
LatLng latLngCurrentLocation = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
double nearestLatitude = 0;
double nearestLongitude = 0;
float minDistance = 1000; //I don't know how to initialize
float currentDistance;
for(int i=0; i<mLatLngGpxList.size(); i++) {
LatLng currentTrackLatLng = mLatLngGpxList.get(i);
currentDistance = getDistance(latLngCurrentLocation, currentTrackLatLng);
if(currentDistance <= minDistance) {
minDistance = currentDistance;
nearestLatitude = currentTrackLatLng.latitude;
nearestLongitude = currentTrackLatLng.longitude;
}
}
//mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(nearestLatitude, nearestLongitude)));
return new LatLng(nearestLatitude,nearestLongitude);
}
//Calcola la distanza tra due LatLng
private float getDistance(LatLng first, LatLng second) {
float [] dist = new float[1];
Location.distanceBetween(first.latitude, first.longitude, second.latitude, second.longitude, dist);
return dist[0];
}
If i draw a path in my country, i can also draw the path for reach it, but if i draw a path
away from my country, i get this:
org.json.JSONException: Index 0 out of range [0..0)
at org.json.JSONArray.get(JSONArray.java:263)
at org.json.JSONArray.getJSONObject(JSONArray.java:480)
etc.
and consequently no path to my path is drawn. Why? :(
Ps: i DON'T get "error_message" : "You have exceeded your daily request quota for this API."
Update: the error is in the code above. Advice? :/
Second Update: float minDistance = 1000; --> became float minDistance = 100000000
and now works. It remains a logical problem but i'll see.. :/