Java Code Examples for android.location.Location#distanceBetween()

The following examples show how to use android.location.Location#distanceBetween() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LocationUtils.java    From PlayTogether with Apache License 2.0 7 votes vote down vote up
public static String getDistance(AVGeoPoint p1, AVGeoPoint p2)
{
	float[] results = new float[1];
	Location.distanceBetween(p1.getLatitude(), p1.getLongitude(), p2.getLatitude(), p2
					.getLongitude(), results);
	int m = (int) results[0];
	String strM = m + "";
	if (strM.length() > 6)//换算成kkm
	{
		float kkm = m * 1.0f / (1000 * 1000);
		kkm = Math.round(kkm * 100) * 1.0f / 10;
		return kkm + "kkm";
	} else if (strM.length() > 3)//换算成 km
	{
		float km = m * 1.0f / 1000;
		km = Math.round(km * 100) * 1.0f / 10;
		return km + "km";
	}
	return m + "m";
}
 
Example 2
Source File: Line.java    From geopaparazzi with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Calculates the length of a line.
 *
 * @return the length of the line in meters.
 */
public double getLength() {
    final float[] dist = new float[3];
    double length = 0;
    for (int i = 0; i < latList.size() - 1; i++) {
        double lat1 = latList.get(i);
        double lon1 = lonList.get(i);
        double altim1 = altimList.get(i);
        double lat2 = latList.get(i + 1);
        double lon2 = lonList.get(i + 1);
        double altim2 = altimList.get(i + 1);
        Location.distanceBetween(lat1, lon1, lat2, lon2, dist);

        double deltaAltim = abs(altim2 - altim1);
        double deltaLength = sqrt(pow(deltaAltim, 2.0) + pow(dist[0], 2.0));
        length = length + deltaLength;

    }
    return length;
}
 
Example 3
Source File: LocationGeofenceEditorActivity.java    From PhoneProfilesPlus with Apache License 2.0 6 votes vote down vote up
private float getCircleZoomValue(double latitude, double longitude, double radius,
                               float minZoom, float maxZoom) {
    LatLng position = new LatLng(latitude, longitude);
    float currZoom = (minZoom + maxZoom) / 2;
    CameraUpdate camera = CameraUpdateFactory.newLatLngZoom(position, currZoom);
    mMap.moveCamera(camera);
    float[] results = new float[1];
    LatLng topLeft = mMap.getProjection().getVisibleRegion().farLeft;
    LatLng topRight = mMap.getProjection().getVisibleRegion().farRight;
    Location.distanceBetween(topLeft.latitude, topLeft.longitude, topRight.latitude,
                                topRight.longitude, results);
    // Difference between visible width in meters and 2.5 * radius.
    double delta = results[0] - 2.5 * radius;
    double accuracy = 10; // 10 meters.
    if (delta < -accuracy)
        return getCircleZoomValue(latitude, longitude, radius, minZoom, currZoom);
    else
    if (delta > accuracy)
        return getCircleZoomValue(latitude, longitude, radius, currZoom, maxZoom);
    else
        return currZoom;
}
 
Example 4
Source File: CodePresenter.java    From open-location-code with Apache License 2.0 5 votes vote down vote up
private void navigate() {
    OpenLocationCode code = mView.getLastFullCode();
    CodeArea codeArea = code.decode();
    Location currentLocation = MainActivity.getMainPresenter().getCurrentLocation();
    float[] results = new float[3];
    Location.distanceBetween(
            currentLocation.getLatitude(),
            currentLocation.getLongitude(),
            codeArea.getCenterLatitude(),
            codeArea.getCenterLongitude(),
            results);
    float distance = results[0];
    char navigationMode;
    if (distance <= MAX_WALKING_MODE_DISTANCE) {
        navigationMode = 'w';
    } else {
        navigationMode = 'd';
    }

    Uri gmmIntentUri = Uri.parse(
            String.format(
                    Locale.US,
                    "google.navigation:q=%f,%f&mode=%s",
                    codeArea.getCenterLatitude(),
                    codeArea.getCenterLongitude(),
                    navigationMode));
    Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
    mView.getContext().startActivity(mapIntent);
}
 
Example 5
Source File: CbScience.java    From PressureNet-SDK with MIT License 5 votes vote down vote up
/**
 * Determine if a list of locations are all close by
 * @param recents
 * @return
 */
private static boolean locationsAreClose(List<CbObservation> recents) {
	double minLat = 90;
	double maxLat = -90;
	double minLon = 180;
	double maxLon = -180;
	for (CbObservation obs : recents ) {
		Location location = obs.getLocation();
		double latitude = location.getLatitude();
		double longitude = location.getLongitude();
		if(latitude > maxLat) {
			maxLat = latitude;
		} 
		if(latitude < minLat) {
			minLat = latitude;
		}
		if(longitude > maxLon) {
			maxLon = longitude;
		}
		if(longitude < minLon) {
			minLon = longitude;
		}
	}
	
	float[] results = new float[2];
	Location.distanceBetween(minLat, minLon, maxLat, maxLon, results);
	float distanceMeters = results[0];
	
	//System.out.println(distanceMeters + "; Locations' proximity for change notification: " + minLat + " to " + maxLat + ", " + minLon + " to " + minLon);

	if(distanceMeters < 2000) {
		return true;
	} else {
		return false;
	}
}
 
Example 6
Source File: DirectionUtil.java    From open-location-code with Apache License 2.0 5 votes vote down vote up
/**
 * This computes a direction between {@code fromLocation} and a
 * {@code destinationCode}. The computation is done using
 * {@link Location#distanceBetween(double, double, double, double, float[])}.
 *
 * @param fromLocation    The user position.
 * @param destinationCode The code to compute the direction to.
 * @return the {@link Direction}
 */
public static Direction getDirection(Location fromLocation, OpenLocationCode destinationCode) {
    CodeArea destinationArea = destinationCode.decode();
    double toLatitude = destinationArea.getCenterLatitude();
    double toLongitude = destinationArea.getCenterLongitude();
    float[] results = new float[3];
    Location.distanceBetween(
            fromLocation.getLatitude(),
            fromLocation.getLongitude(),
            toLatitude,
            toLongitude,
            results);

    // The device bearing in the location object is 0-360, the value returned from
    // distanceBetween is -180 to 180. Adjust the device bearing to be in the same range.
    float deviceBearing = fromLocation.getBearing();
    if (deviceBearing > 180) {
        deviceBearing = deviceBearing - 360;
    }

    // Compensate the initial bearing for the device bearing.
    results[1] = results[1] - deviceBearing;
    if (results[1] > 180) {
        results[1] = -360 + results[1];
    } else if (results[1] < -180) {
        results[1] = 360 + results[1];
    }
    return new Direction(
            OpenLocationCodeUtil.createOpenLocationCode(
                    fromLocation.getLatitude(), fromLocation.getLongitude()),
            destinationCode,
            results[0],
            results[1]);
}
 
Example 7
Source File: MapFragment.java    From NoiseCapture with GNU General Public License v3.0 5 votes vote down vote up
public void addMeasurement(LatLng location, String htmlColor) {
    if(lastPt != null) {
        float[] result = new float[3];
        Location.distanceBetween(lastPt.lat, lastPt.lng, location.lat, location.lng, result);
        if(result[0] < ignoreNewPointDistanceDelta) {
            return;
        }
    }
    lastPt = location;
    String command = "addMeasurementPoint(["+location.getLat()+","+location.getLng()+"], '"+htmlColor+"')";
    if(!runJs(command)) {
        cachedCommands.add(command);
    }
}
 
Example 8
Source File: Utils.java    From ploggy with GNU General Public License v3.0 5 votes vote down vote up
public static int calculateLocationDistanceInMeters(
        double latitudeA,
        double longitudeA,
        double latitudeB,
        double longitudeB) {
    float[] results = new float[1];
    Location.distanceBetween(latitudeA, longitudeA, latitudeB, longitudeB, results);
    return Math.round(results[0]);
}
 
Example 9
Source File: Utils.java    From barterli_android with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the distance between two Locations(in metres)
 *
 * @param start The start location
 * @param end   The end location
 * @return The distance between two locations(in metres)
 */
public static float distanceBetween(final Location start, final Location end) {

    final float[] results = new float[1];
    Location.distanceBetween(start.getLatitude(), start.getLongitude(), end
            .getLatitude(), end.getLongitude(), results);
    return results[0];
}
 
Example 10
Source File: ChartFragmentTest.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the logic to get the value of metric Distance in {@link ChartFragment#fillDataPoint(Location,
 * double[])}.
 */
public void testFillDataPoint_distanceMetric() {
  // By distance.
  chartFragment.setChartByDistance(true);
  // Resets last location and writes first location.
  MyTracksLocation myTracksLocation1 = TrackStubUtils.createMyTracksLocation();
  double[] point = fillDataPointTestHelper(myTracksLocation1);
  assertEquals(0.0, point[0]);

  // The second is a same location, just different time.
  MyTracksLocation myTracksLocation2 = TrackStubUtils.createMyTracksLocation();
  point = fillDataPointTestHelper(myTracksLocation2);
  assertEquals(0.0, point[0]);

  // The third location is a new location, and use metric.
  MyTracksLocation myTracksLocation3 = TrackStubUtils.createMyTracksLocation();
  myTracksLocation3.setLatitude(23);
  point = fillDataPointTestHelper(myTracksLocation3);

  // Computes the distance between Latitude 22 and 23.
  float[] results = new float[4];
  Location.distanceBetween(myTracksLocation2.getLatitude(), myTracksLocation2.getLongitude(),
      myTracksLocation3.getLatitude(), myTracksLocation3.getLongitude(), results);
  double distance1 = results[0] * UnitConversions.M_TO_KM;
  assertEquals(distance1, point[0]);

  // The fourth location is a new location, and use metric.
  MyTracksLocation myTracksLocation4 = TrackStubUtils.createMyTracksLocation();
  myTracksLocation4.setLatitude(24);
  point = fillDataPointTestHelper(myTracksLocation4);

  // Computes the distance between Latitude 23 and 24.
  Location.distanceBetween(myTracksLocation3.getLatitude(), myTracksLocation3.getLongitude(),
      myTracksLocation4.getLatitude(), myTracksLocation4.getLongitude(), results);
  double distance2 = results[0] * UnitConversions.M_TO_KM;
  assertEquals((distance1 + distance2), point[0]);
}
 
Example 11
Source File: OmniArea.java    From LibreTasks with Apache License 2.0 5 votes vote down vote up
/**
 * Determine distance (in miles) between 2 OmniAreas.
 * 
 * @param pointA
 *          first point
 * @param pointB
 *          second point
 * @return distance (in miles) between pointA and pointB.
 */
public static double getDistance(OmniArea pointA, OmniArea pointB) {
  final int DISTANCE = 0;
  final int DISTANCE_ONLY = 1;

  float[] results = new float[DISTANCE_ONLY];

  Location.distanceBetween(pointA.getLatitude(), pointA.getLongitude(), pointB.getLatitude(),
      pointB.getLongitude(), results);

  // convert distance from meters to miles
  return results[DISTANCE] * MILES_IN_A_METER;
}
 
Example 12
Source File: HttpResponseParser.java    From barterli_android with Apache License 2.0 5 votes vote down vote up
/**
 * Method for calculating the distance between two location points
 *
 * @param startLatitude
 * @param startLongitude
 * @param endLatitude
 * @param endLongitude
 * @return distance in kms
 */
private float getDistanceBetweenInKms(double startLatitude,
                                      double startLongitude, double endLatitude,
                                      double endLongitude) {
    float[] distanceBetween = new float[1];
    if ((startLatitude != 0.0) && (startLongitude != 0.0)) {
        Location.distanceBetween(startLatitude, startLongitude, mEndLatitude, mEndLongitude, distanceBetween);
        // to convert it into kms
        distanceBetween[0] = distanceBetween[0] / 1000;
    } else {
        distanceBetween[0] = 0;
    }
    return distanceBetween[0];

}
 
Example 13
Source File: LocationUtils.java    From PrivacyStreams with Apache License 2.0 5 votes vote down vote up
public static Double getDistanceBetween(LatLon latLon1, LatLon latLon2) {
    if (latLon1 == null || latLon2 == null)
        return null;
    float[] result = new float[1];
    Location.distanceBetween(latLon1.getLatitude(), latLon1.getLongitude(),
            latLon2.getLatitude(), latLon2.getLongitude(), result);
    return (double) result[0];
}
 
Example 14
Source File: ChartFragmentTest.java    From mytracks with Apache License 2.0 4 votes vote down vote up
/**
 * Tests the logic to get the value of imperial Distance in {@link ChartFragment#fillDataPoint(Location,
 * double[])}.
 */
public void testFillDataPoint_distanceImperial() {
  // By distance.
  chartFragment.setChartByDistance(true);
  // Setups to use imperial.
  chartFragment.setMetricUnits(false);

  // The first is a same location, just different time.
  MyTracksLocation myTracksLocation1 = TrackStubUtils.createMyTracksLocation();
  double[] point = fillDataPointTestHelper(myTracksLocation1);
  assertEquals(0.0, point[0]);

  // The second location is a new location, and use imperial.
  MyTracksLocation myTracksLocation2 = TrackStubUtils.createMyTracksLocation();
  myTracksLocation2.setLatitude(23);
  point = fillDataPointTestHelper(myTracksLocation2);

  /*
   * Computes the distance between Latitude 22 and 23. And for we set using
   * imperial, the distance should be multiplied by UnitConversions.KM_TO_MI.
   */
  float[] results = new float[4];
  Location.distanceBetween(myTracksLocation1.getLatitude(), myTracksLocation1.getLongitude(),
      myTracksLocation2.getLatitude(), myTracksLocation2.getLongitude(), results);
  double distance1 = results[0] * UnitConversions.M_TO_KM * UnitConversions.KM_TO_MI;
  assertEquals(distance1, point[0]);

  // The third location is a new location, and use imperial.
  MyTracksLocation myTracksLocation3 = TrackStubUtils.createMyTracksLocation();
  myTracksLocation3.setLatitude(24);
  point = fillDataPointTestHelper(myTracksLocation3);

  /*
   * Computes the distance between Latitude 23 and 24. And for we set using
   * imperial, the distance should be multiplied by UnitConversions.KM_TO_MI.
   */
  Location.distanceBetween(myTracksLocation2.getLatitude(), myTracksLocation2.getLongitude(),
      myTracksLocation3.getLatitude(), myTracksLocation3.getLongitude(), results);
  double distance2 = results[0] * UnitConversions.M_TO_KM * UnitConversions.KM_TO_MI;
  assertEquals(distance1 + distance2, point[0]);
}
 
Example 15
Source File: MarkerAreasUtils.java    From MarkerBuilder with Apache License 2.0 4 votes vote down vote up
public static double toRadiusMeters(LatLng center, LatLng radius) {
    float[] result = new float[1];
    Location.distanceBetween(center.latitude, center.longitude, radius.latitude, radius.longitude, result);
    return result[0];
}
 
Example 16
Source File: CircleDemoActivity.java    From android-samples with Apache License 2.0 4 votes vote down vote up
private static double toRadiusMeters(LatLng center, LatLng radius) {
    float[] result = new float[1];
    Location.distanceBetween(center.latitude, center.longitude,
            radius.latitude, radius.longitude, result);
    return result[0];
}
 
Example 17
Source File: ARObject.java    From geoar-app with Apache License 2.0 4 votes vote down vote up
public void onLocationUpdate(Location location) {
	if (entity == null || location == null)
		return;

	final double longitude = entity.getLongitude();
	final double latitude = entity.getLatitude();
	int altitude = (int) entity.getAltitude();

	/** calc the distance XXX */
	final float[] x = new float[1];
	Location.distanceBetween(location.getLatitude(),
			location.getLongitude(), latitude, longitude, x);
	distanceTo = x[0];
	x[0] = 0;

	/** set scaling */
	this.featureDetailsScale = getScaleByDistance(distanceTo);

	/** just the distance -> length 1 */
	Location.distanceBetween(location.getLatitude(),
			location.getLongitude(), location.getLatitude(), longitude, x);

	/** just the distance -> length 1 */
	final float[] z = new float[1];
	Location.distanceBetween(location.getLatitude(),
			location.getLongitude(), latitude, location.getLongitude(), z);

	// correct the direction according to the poi location, because we just
	// get the distance in x and z direction
	if (location.getLongitude() < longitude)
		x[0] *= -1;
	if (location.getLatitude() < latitude)
		z[0] *= -1;
	if (altitude == 0)
		altitude = (int) location.getAltitude();
	// testen

	newPosition[0] = x[0];
	newPosition[1] = (float) (altitude - location.getAltitude());
	// FIXME XXX TODO and here the third position has to be negative i think
	newPosition[2] = z[0];

	for (RenderFeature2 renderFeature : renderFeatures)
		renderFeature.setRelativePosition(newPosition);

	this.newPosition[0] = newPosition[0]; // - GLESCamera.cameraPosition[0];
	this.newPosition[1] = newPosition[1] - GLESCamera.cameraPosition[1];
	this.newPosition[2] = newPosition[2]; // - GLESCamera.cameraPosition[2];
}
 
Example 18
Source File: LocationUtils.java    From YelpQL with MIT License 3 votes vote down vote up
public static String getDistanceFromLocation(double startLatitude, double startLongitude, double endLatitude, double endLongitude) {

        float[] distance = new float[2];

        Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, distance);

        return String.format("%.2f %S", distance[0] * 0.0006, "mi");
    }
 
Example 19
Source File: PlaceRecord.java    From android_coursera_1 with MIT License 3 votes vote down vote up
public boolean intersects(Location location) {

		double tolerance = 1000;
		float[] results = new float[3];

		Location.distanceBetween(location.getLatitude(),
				location.getLongitude(), lat, lon, results);

		return (results[0] <= tolerance);

	}
 
Example 20
Source File: SimpleLocation.java    From Android-SimpleLocation with Apache License 2.0 2 votes vote down vote up
/**
 * Calculates the difference from the start position to the end position (in meters)
 *
 * @param startLatitude the latitude of the start position
 * @param startLongitude the longitude of the start position
 * @param endLatitude the latitude of the end position
 * @param endLongitude the longitude of the end position
 * @return the distance in meters
 */
public static double calculateDistance(double startLatitude, double startLongitude, double endLatitude, double endLongitude) {
	float[] results = new float[3];
	Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results);
	return results[0];
}