Android getting the distance using a Location object - android

I’d like to take a series of samples of coordinates returned by GPS and calculate the (straight line) distance between them so I can graph the distances via Excel. I see the method distanceBetween and distanceTo of the Location class, but I’m concerned these don’t return the straight line distance.
Does anyone know what distance is returned by these methods or if there are any ways to calculate straight line distance based on latitude/longitude values returned by the Location class?

A Google search will offer solutions should you somehow desire to do this calculation yourself. For example the Haversine approach:
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
is reported here. Note that this is straight line and does not account for irregularities in elevation, etc.

How can I measure distance and create a bounding box based on two latitude+longitude points in Java?
provides a Java implementation of the Haversine approach.

Here my code
float[] result=new float[1];
if(cordenatalar.size()>1)
{
LatLong add_kor=(LatLong)cordenatalar.get(cordenatalar.size()-1);
Location.distanceBetween(add_kor.getLat(), add_kor.getLongg(), location.getLatitude(), location.getLongitude(), result);
kilometr+=result[0];
//KMTextView.setText(String.valueOf(kilometr));
}
KMTextView.setText("sss: "+String.valueOf(cordenatalar.size()+" res: "+kilometr+" metr"));
cordenatalar.add(new LatLong(location.getLatitude(), location.getLongitude()));

source = starting location;
destination = current location;
/* this method will fetch you the distance between two geo points. */
source.distanceTo(destination);

Related

What should I store in Firestore so that I can fetch data on the basis of details get from autocomplete place api? [duplicate]

Does the new firestore database from firebase natively support location based geo queries? i.e. Find posts within 10 miles, or find the 50 nearest posts?
I see that there are some existing projects for the real-time firebase database, projects such as geofire- could those be adapted to firestore as well?
UPDATE: Firestore does not support actual GeoPoint queries at present so while the below query executes successfully, it only filters by latitude, not by longitude and thus will return many results that are not nearby. The best solution would be to use geohashes. To learn how to do something similar yourself, have a look at this video.
This can be done by creating a bounding box less than greater than query. As for the efficiency, I can't speak to it.
Note, the accuracy of the lat/long offset for ~1 mile should be reviewed, but here is a quick way to do this:
SWIFT 3.0 Version
func getDocumentNearBy(latitude: Double, longitude: Double, distance: Double) {
// ~1 mile of lat and lon in degrees
let lat = 0.0144927536231884
let lon = 0.0181818181818182
let lowerLat = latitude - (lat * distance)
let lowerLon = longitude - (lon * distance)
let greaterLat = latitude + (lat * distance)
let greaterLon = longitude + (lon * distance)
let lesserGeopoint = GeoPoint(latitude: lowerLat, longitude: lowerLon)
let greaterGeopoint = GeoPoint(latitude: greaterLat, longitude: greaterLon)
let docRef = Firestore.firestore().collection("locations")
let query = docRef.whereField("location", isGreaterThan: lesserGeopoint).whereField("location", isLessThan: greaterGeopoint)
query.getDocuments { snapshot, error in
if let error = error {
print("Error getting documents: \(error)")
} else {
for document in snapshot!.documents {
print("\(document.documentID) => \(document.data())")
}
}
}
}
func run() {
// Get all locations within 10 miles of Google Headquarters
getDocumentNearBy(latitude: 37.422000, longitude: -122.084057, distance: 10)
}
UPDATE: Firestore does not support actual GeoPoint queries at present so while the below query executes successfully, it only filters by latitude, not by longitude and thus will return many results that are not nearby. The best solution would be to use geohashes. To learn how to do something similar yourself, have a look at this video.
(First let me apologize for all the code in this post, I just wanted anyone reading this answer to have an easy time reproducing the functionality.)
To address the same concern the OP had, at first I adapted the GeoFire library to work with Firestore (you can learn a lot about geo-stuff by looking at that library). Then I realized I didn't really mind if locations were returned in an exact circle. I just wanted some way to get 'nearby' locations.
I can't believe how long it took me to realize this, but you can just perform a double inequality query on a GeoPoint field using a SW corner and NE corner to get locations within a bounding box around a center point.
So I made a JavaScript function like the one below (this is basically a JS version of Ryan Lee's answer).
/**
* Get locations within a bounding box defined by a center point and distance from from the center point to the side of the box;
*
* #param {Object} area an object that represents the bounding box
* around a point in which locations should be retrieved
* #param {Object} area.center an object containing the latitude and
* longitude of the center point of the bounding box
* #param {number} area.center.latitude the latitude of the center point
* #param {number} area.center.longitude the longitude of the center point
* #param {number} area.radius (in kilometers) the radius of a circle
* that is inscribed in the bounding box;
* This could also be described as half of the bounding box's side length.
* #return {Promise} a Promise that fulfills with an array of all the
* retrieved locations
*/
function getLocations(area) {
// calculate the SW and NE corners of the bounding box to query for
const box = utils.boundingBoxCoordinates(area.center, area.radius);
// construct the GeoPoints
const lesserGeopoint = new GeoPoint(box.swCorner.latitude, box.swCorner.longitude);
const greaterGeopoint = new GeoPoint(box.neCorner.latitude, box.neCorner.longitude);
// construct the Firestore query
let query = firebase.firestore().collection('myCollection').where('location', '>', lesserGeopoint).where('location', '<', greaterGeopoint);
// return a Promise that fulfills with the locations
return query.get()
.then((snapshot) => {
const allLocs = []; // used to hold all the loc data
snapshot.forEach((loc) => {
// get the data
const data = loc.data();
// calculate a distance from the center
data.distanceFromCenter = utils.distance(area.center, data.location);
// add to the array
allLocs.push(data);
});
return allLocs;
})
.catch((err) => {
return new Error('Error while retrieving events');
});
}
The function above also adds a .distanceFromCenter property to each piece of location data that's returned so that you could get the circle-like behavior by just checking if that distance is within the range you want.
I use two util functions in the function above so here's the code for those as well. (All of the util functions below are actually adapted from the GeoFire library.)
distance():
/**
* Calculates the distance, in kilometers, between two locations, via the
* Haversine formula. Note that this is approximate due to the fact that
* the Earth's radius varies between 6356.752 km and 6378.137 km.
*
* #param {Object} location1 The first location given as .latitude and .longitude
* #param {Object} location2 The second location given as .latitude and .longitude
* #return {number} The distance, in kilometers, between the inputted locations.
*/
distance(location1, location2) {
const radius = 6371; // Earth's radius in kilometers
const latDelta = degreesToRadians(location2.latitude - location1.latitude);
const lonDelta = degreesToRadians(location2.longitude - location1.longitude);
const a = (Math.sin(latDelta / 2) * Math.sin(latDelta / 2)) +
(Math.cos(degreesToRadians(location1.latitude)) * Math.cos(degreesToRadians(location2.latitude)) *
Math.sin(lonDelta / 2) * Math.sin(lonDelta / 2));
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return radius * c;
}
boundingBoxCoordinates(): (There are more utils used in here as well that I've pasted below.)
/**
* Calculates the SW and NE corners of a bounding box around a center point for a given radius;
*
* #param {Object} center The center given as .latitude and .longitude
* #param {number} radius The radius of the box (in kilometers)
* #return {Object} The SW and NE corners given as .swCorner and .neCorner
*/
boundingBoxCoordinates(center, radius) {
const KM_PER_DEGREE_LATITUDE = 110.574;
const latDegrees = radius / KM_PER_DEGREE_LATITUDE;
const latitudeNorth = Math.min(90, center.latitude + latDegrees);
const latitudeSouth = Math.max(-90, center.latitude - latDegrees);
// calculate longitude based on current latitude
const longDegsNorth = metersToLongitudeDegrees(radius, latitudeNorth);
const longDegsSouth = metersToLongitudeDegrees(radius, latitudeSouth);
const longDegs = Math.max(longDegsNorth, longDegsSouth);
return {
swCorner: { // bottom-left (SW corner)
latitude: latitudeSouth,
longitude: wrapLongitude(center.longitude - longDegs),
},
neCorner: { // top-right (NE corner)
latitude: latitudeNorth,
longitude: wrapLongitude(center.longitude + longDegs),
},
};
}
metersToLongitudeDegrees():
/**
* Calculates the number of degrees a given distance is at a given latitude.
*
* #param {number} distance The distance to convert.
* #param {number} latitude The latitude at which to calculate.
* #return {number} The number of degrees the distance corresponds to.
*/
function metersToLongitudeDegrees(distance, latitude) {
const EARTH_EQ_RADIUS = 6378137.0;
// this is a super, fancy magic number that the GeoFire lib can explain (maybe)
const E2 = 0.00669447819799;
const EPSILON = 1e-12;
const radians = degreesToRadians(latitude);
const num = Math.cos(radians) * EARTH_EQ_RADIUS * Math.PI / 180;
const denom = 1 / Math.sqrt(1 - E2 * Math.sin(radians) * Math.sin(radians));
const deltaDeg = num * denom;
if (deltaDeg < EPSILON) {
return distance > 0 ? 360 : 0;
}
// else
return Math.min(360, distance / deltaDeg);
}
wrapLongitude():
/**
* Wraps the longitude to [-180,180].
*
* #param {number} longitude The longitude to wrap.
* #return {number} longitude The resulting longitude.
*/
function wrapLongitude(longitude) {
if (longitude <= 180 && longitude >= -180) {
return longitude;
}
const adjusted = longitude + 180;
if (adjusted > 0) {
return (adjusted % 360) - 180;
}
// else
return 180 - (-adjusted % 360);
}
A new project has been introduced since #monkeybonkey first ask this question. The project is called GEOFirestore.
With this library you can perform queries like query documents within a circle:
const geoQuery = geoFirestore.query({
center: new firebase.firestore.GeoPoint(10.38, 2.41),
radius: 10.5
});
You can install GeoFirestore via npm. You will have to install Firebase separately (because it is a peer dependency to GeoFirestore):
$ npm install geofirestore firebase --save
As of today, there is no way to do such a query. There are other questions in SO related to it:
Is there a way to use GeoFire with Firestore?
How to query closest GeoPoints in a collection in Firebase Cloud Firestore?
Is there a way to use GeoFire with Firestore?
In my current Android project I may use https://github.com/drfonfon/android-geohash to add a geohash field while Firebase team is developing native support.
Using Firebase Realtime Database like suggested in other questions means that you can't filter your results set by location and other fields simultaneously, the main reason I want to switch to Firestore in the first place.
As of late 2020 there is now also documentation of how to do geoqueries with Firestore.
These solutions for iOS, Android, and Web, build on top of a slimmed down version of the Firebase-created GeoFire libraries, and then show how to:
Generate geohash values and store them in Firestore
Determine geohash ranges of the bounding box for a certain point and radius
Perform queries across these geohash ranges
This a bit more low-level than most of the other libraries presented here, so it may be a better fit for some use-cases and a worse fit for others.
Hijacking this thread to hopefully help anyone still looking. Firestore still does not support geo-based queries, and using the GeoFirestore library isnt ideal either as it will only let you search by location, nothing else.
I've put this together:
https://github.com/mbramwell1/GeoFire-Android
It basically lets you do nearby searches using a location and distance:
QueryLocation queryLocation = QueryLocation.fromDegrees(latitude, longitude);
Distance searchDistance = new Distance(1.0, DistanceUnit.KILOMETERS);
geoFire.query()
.whereNearTo(queryLocation, distance)
.build()
.get();
There are more docs on the repo. Its working for me so give it a try, hopefully it will do what you need.
For Dart
///
/// Checks if these coordinates are valid geo coordinates.
/// [latitude] The latitude must be in the range [-90, 90]
/// [longitude] The longitude must be in the range [-180, 180]
/// returns [true] if these are valid geo coordinates
///
bool coordinatesValid(double latitude, double longitude) {
return (latitude >= -90 && latitude <= 90 && longitude >= -180 && longitude <= 180);
}
///
/// Checks if the coordinates of a GeopPoint are valid geo coordinates.
/// [latitude] The latitude must be in the range [-90, 90]
/// [longitude] The longitude must be in the range [-180, 180]
/// returns [true] if these are valid geo coordinates
///
bool geoPointValid(GeoPoint point) {
return (point.latitude >= -90 &&
point.latitude <= 90 &&
point.longitude >= -180 &&
point.longitude <= 180);
}
///
/// Wraps the longitude to [-180,180].
///
/// [longitude] The longitude to wrap.
/// returns The resulting longitude.
///
double wrapLongitude(double longitude) {
if (longitude <= 180 && longitude >= -180) {
return longitude;
}
final adjusted = longitude + 180;
if (adjusted > 0) {
return (adjusted % 360) - 180;
}
// else
return 180 - (-adjusted % 360);
}
double degreesToRadians(double degrees) {
return (degrees * math.pi) / 180;
}
///
///Calculates the number of degrees a given distance is at a given latitude.
/// [distance] The distance to convert.
/// [latitude] The latitude at which to calculate.
/// returns the number of degrees the distance corresponds to.
double kilometersToLongitudeDegrees(double distance, double latitude) {
const EARTH_EQ_RADIUS = 6378137.0;
// this is a super, fancy magic number that the GeoFire lib can explain (maybe)
const E2 = 0.00669447819799;
const EPSILON = 1e-12;
final radians = degreesToRadians(latitude);
final numerator = math.cos(radians) * EARTH_EQ_RADIUS * math.pi / 180;
final denom = 1 / math.sqrt(1 - E2 * math.sin(radians) * math.sin(radians));
final deltaDeg = numerator * denom;
if (deltaDeg < EPSILON) {
return distance > 0 ? 360.0 : 0.0;
}
// else
return math.min(360.0, distance / deltaDeg);
}
///
/// Defines the boundingbox for the query based
/// on its south-west and north-east corners
class GeoBoundingBox {
final GeoPoint swCorner;
final GeoPoint neCorner;
GeoBoundingBox({this.swCorner, this.neCorner});
}
///
/// Defines the search area by a circle [center] / [radiusInKilometers]
/// Based on the limitations of FireStore we can only search in rectangles
/// which means that from this definition a final search square is calculated
/// that contains the circle
class Area {
final GeoPoint center;
final double radiusInKilometers;
Area(this.center, this.radiusInKilometers):
assert(geoPointValid(center)), assert(radiusInKilometers >= 0);
factory Area.inMeters(GeoPoint gp, int radiusInMeters) {
return new Area(gp, radiusInMeters / 1000.0);
}
factory Area.inMiles(GeoPoint gp, int radiusMiles) {
return new Area(gp, radiusMiles * 1.60934);
}
/// returns the distance in km of [point] to center
double distanceToCenter(GeoPoint point) {
return distanceInKilometers(center, point);
}
}
///
///Calculates the SW and NE corners of a bounding box around a center point for a given radius;
/// [area] with the center given as .latitude and .longitude
/// and the radius of the box (in kilometers)
GeoBoundingBox boundingBoxCoordinates(Area area) {
const KM_PER_DEGREE_LATITUDE = 110.574;
final latDegrees = area.radiusInKilometers / KM_PER_DEGREE_LATITUDE;
final latitudeNorth = math.min(90.0, area.center.latitude + latDegrees);
final latitudeSouth = math.max(-90.0, area.center.latitude - latDegrees);
// calculate longitude based on current latitude
final longDegsNorth = kilometersToLongitudeDegrees(area.radiusInKilometers, latitudeNorth);
final longDegsSouth = kilometersToLongitudeDegrees(area.radiusInKilometers, latitudeSouth);
final longDegs = math.max(longDegsNorth, longDegsSouth);
return new GeoBoundingBox(
swCorner: new GeoPoint(latitudeSouth, wrapLongitude(area.center.longitude - longDegs)),
neCorner: new GeoPoint(latitudeNorth, wrapLongitude(area.center.longitude + longDegs)));
}
///
/// Calculates the distance, in kilometers, between two locations, via the
/// Haversine formula. Note that this is approximate due to the fact that
/// the Earth's radius varies between 6356.752 km and 6378.137 km.
/// [location1] The first location given
/// [location2] The second location given
/// sreturn the distance, in kilometers, between the two locations.
///
double distanceInKilometers(GeoPoint location1, GeoPoint location2) {
const radius = 6371; // Earth's radius in kilometers
final latDelta = degreesToRadians(location2.latitude - location1.latitude);
final lonDelta = degreesToRadians(location2.longitude - location1.longitude);
final a = (math.sin(latDelta / 2) * math.sin(latDelta / 2)) +
(math.cos(degreesToRadians(location1.latitude)) *
math.cos(degreesToRadians(location2.latitude)) *
math.sin(lonDelta / 2) *
math.sin(lonDelta / 2));
final c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a));
return radius * c;
}
I just published a Flutter package based on the JS code above
https://pub.dartlang.org/packages/firestore_helpers
Yes, this is an old topic, but I want to help only on Java code. How I solved a problem with longitude? I used a code from Ryan Lee and Michael Teper.
A code:
#Override
public void getUsersForTwentyMiles() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
double latitude = 33.0076665;
double longitude = 35.1011336;
int distance = 20; //20 milles
GeoPoint lg = new GeoPoint(latitude, longitude);
// ~1 mile of lat and lon in degrees
double lat = 0.0144927536231884;
double lon = 0.0181818181818182;
final double lowerLat = latitude - (lat * distance);
final double lowerLon = longitude - (lon * distance);
double greaterLat = latitude + (lat * distance);
final double greaterLon = longitude + (lon * distance);
final GeoPoint lesserGeopoint = new GeoPoint(lowerLat, lowerLon);
final GeoPoint greaterGeopoint = new GeoPoint(greaterLat, greaterLon);
Log.d(LOG_TAG, "local general lovation " + lg);
Log.d(LOG_TAG, "local lesserGeopoint " + lesserGeopoint);
Log.d(LOG_TAG, "local greaterGeopoint " + greaterGeopoint);
//get users for twenty miles by only a latitude
db.collection("users")
.whereGreaterThan("location", lesserGeopoint)
.whereLessThan("location", greaterGeopoint)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
UserData user = document.toObject(UserData.class);
//here a longitude condition (myLocation - 20 <= myLocation <= myLocation +20)
if (lowerLon <= user.getUserGeoPoint().getLongitude() && user.getUserGeoPoint().getLongitude() <= greaterLon) {
Log.d(LOG_TAG, "location: " + document.getId());
}
}
} else {
Log.d(LOG_TAG, "Error getting documents: ", task.getException());
}
}
});
}
Just inside after issuing the result set the filter to longitude:
if (lowerLon <= user.getUserGeoPoint().getLongitude() && user.getUserGeoPoint().getLongitude() <= greaterLon) {
Log.d(LOG_TAG, "location: " + document.getId());
}
I hope this will help someone.
Have a nice day!
You should use GeoFire (works with Firestore). With this you can filter documents on server and read less documents from your Firestore db. This will reduce your read count as well.
Check this lib for GroFire: https://github.com/patpatchpatrick/GeoFirestore-iOS
"patpatchpatrick" made this to Swift 5 compatible.
Just do a pod install as follows:
pod 'Geofirestore', :git => 'https://github.com/patpatchpatrick/GeoFirestore-iOS'
I am using this library in one of my projects and it works fine.
To set a location:
let location: CLLocation = CLLocation(latitude: lat, longitude: lng)
yourCollection.setLocation(location: location, forDocumentWithID: "YourDocId") { (error) in }
To remove location:
collection.removeLocation(forDocumentWithID: "YourDocId")
To get docs:
let center = CLLocation(latitude: lat, longitude: lng)
let collection = "Your collection path"
let circleQuery = collection.query(withCenter: center, radius: Double(yourRadiusVal))
let _ = circleQuery.observe(.documentEntered, with: { (key, location) in
//Use info as per your need
})
I have used .documentEntered, you can use other available geo queries like (Document Exited, Document Moved) as per your need.
You can query using GeoPoint as well.
This is not fully tested yet it should be a bit of an improvement on Ryan Lee's answer
My calculation is more accurate and then I filter the answers to remove hits which fall within the bounding box but outside the radius
Swift 4
func getDocumentNearBy(latitude: Double, longitude: Double, meters: Double) {
let myGeopoint = GeoPoint(latitude:latitude, longitude:longitude )
let r_earth : Double = 6378137 // Radius of earth in Meters
// 1 degree lat in m
let kLat = (2 * Double.pi / 360) * r_earth
let kLon = (2 * Double.pi / 360) * r_earth * __cospi(latitude/180.0)
let deltaLat = meters / kLat
let deltaLon = meters / kLon
let swGeopoint = GeoPoint(latitude: latitude - deltaLat, longitude: longitude - deltaLon)
let neGeopoint = GeoPoint(latitude: latitude + deltaLat, longitude: longitude + deltaLon)
let docRef : CollectionReference = appDelegate.db.collection("restos")
let query = docRef.whereField("location", isGreaterThan: swGeopoint).whereField("location", isLessThan: neGeopoint)
query.getDocuments { snapshot, error in
guard let snapshot = snapshot else {
print("Error fetching snapshot results: \(error!)")
return
}
self.documents = snapshot.documents.filter { (document) in
if let location = document.get("location") as? GeoPoint {
let myDistance = self.distanceBetween(geoPoint1:myGeopoint,geoPoint2:location)
print("myDistance:\(myDistance) distance:\(meters)")
return myDistance <= meters
}
return false
}
}
}
Functions which accurately measure the distance in Meters between 2 Geopoints for filtering
func distanceBetween(geoPoint1:GeoPoint, geoPoint2:GeoPoint) -> Double{
return distanceBetween(lat1: geoPoint1.latitude,
lon1: geoPoint1.longitude,
lat2: geoPoint2.latitude,
lon2: geoPoint2.longitude)
}
func distanceBetween(lat1:Double, lon1:Double, lat2:Double, lon2:Double) -> Double{ // generally used geo measurement function
let R : Double = 6378.137; // Radius of earth in KM
let dLat = lat2 * Double.pi / 180 - lat1 * Double.pi / 180;
let dLon = lon2 * Double.pi / 180 - lon1 * Double.pi / 180;
let a = sin(dLat/2) * sin(dLat/2) +
cos(lat1 * Double.pi / 180) * cos(lat2 * Double.pi / 180) *
sin(dLon/2) * sin(dLon/2);
let c = 2 * atan2(sqrt(a), sqrt(1-a));
let d = R * c;
return d * 1000; // meters
}
The easiest way is to calculate a "geo hash" when storing the location in the database.
A geo hash is a string which represents a location down to a certain accuracy. The longer the geo hash, the closer the locations with said geo hash must be. Two location which are e.g. 100m apart may have the same 6-char geo hash but when calculating a 7-char geo hash the last char might be different.
There are plenty libraries allowing you to calculate geo hashes for any language. Just store it alongside the location and use a == query to find locations with the same geo hash.
In javascript you can simply
const db = firebase.firestore();
//Geofire
import { GeoCollectionReference, GeoFirestore, GeoQuery, GeoQuerySnapshot } from 'geofirestore';
// Create a GeoFirestore reference
const geofirestore: GeoFirestore = new GeoFirestore(db);
// Create a GeoCollection reference
const geocollection: GeoCollectionReference = geofirestore.collection('<Your_collection_name>');
const query: GeoQuery = geocollectionDrivers.near({
center: new firebase.firestore.GeoPoint(location.latitude, location.longitude),
radius: 10000
});
query.onSnapshot(gquerySnapshot => {
gquerySnapshot.forEach(res => {
console.log(res.data());
})
});
A workaround for Flutter till we have native query in Firestore to pull ordered documents based on lat/long:
https://pub.dev/packages/geoflutterfire
A plugin to store geo hashes in the Firestore and query the same.
Limitations: limit not supported
There's a GeoFire library for Firestore called Geofirestore: https://github.com/imperiumlabs/GeoFirestore (Disclaimer: I helped develop it). It's super easy to use and offers the same features for Firestore that Geofire does for Firebase Realtime DB)

Geo Coordinates (Long,Lat) to Meters (x,y)

I am working coordinates system as shown below:
x and y are in meters. I am interested in only positive x,y. I want to convert (x,y) to (lat,lon) and vise versa.
I thought it is simple and I dont see a problem with my solutions below. But I am not getting very correct results.
My Solution:
As we see in the image below, I considered the Latitude and Longitude as angles of 2 circles:
1. (x,y) to (lat,lon)
I applied the Arc Length formula (here), shown below, on both; x and y
Hence, my functions are:
private static double calculateLat(float x) {
int earthRadius = 6371000;
return REF_LOC.getLatitude() + x*360/(2*PI*earthRadius);
}
private static double calculateLong(float y) {
int earthRadius = 6371000;
return REF_LOC.getLongitude() + y*360/(2*PI*earthRadius);
}
REF_LOC is the reference Geo Location for which (x,y) are (0,0). It can be any point on earth.
2. (lat,lon) to (x,y)
For this I am simply using this:
int calculateX(double longitude){
Location.distanceBetween(REF_LOC.getLatitude(), REF_LOC.getLongitude(),
REF_LOC.getLatitude(), lonDeg, results);
return results[0];
}
int calculateY(double latitude){
Location.distanceBetween(REF_LOC.getLatitude(), REF_LOC.getLongitude(),
latDeg, REF_LOC.getLongitude(), results);
return results[0];
}
But I am getting inconsistent results. First I use solution 1 and convert some value (x,y) to (lat,long). But when I use the same (lat,long) back to (x,y) using solution 2, I get about 2 meters difference in x and 10 meters in y. Can anyone help me identify the problem please?
Alluding to my comment on spherical vs elliptical calculations, another way to look at difference in distance calculations for spherical vs elliptical distance is to use the 2 available utilities:
// For REF_LOC = (70, 20)
// Compute a lat/lng due east of a REF_LOC and compute distance using both
// available methods.
LatLng P = SphericalUtil.computeOffsetOrigin(REF_LOC, 20000, 90.0);
// And then compute a distance
d = SphericalUtil.computeDistanceBetween(REF_LOC, P);
Location.distanceBetween(REF_LOC.latitude, REF_LOC.longitude, P.latitude, P.longitude, results);
// d = 20000.000000000036
// results[0] = 20081.818
// and for a REF_LOC = (0, 20)
// d = 20000.000000000127
// results[0] = 20022.377
What's also interesting is the SphericalUtil.computeOffsetOrigin() produces error
in latitude increasing from equator to pole making it non-symmetrical. Yet the resulting distances are essentially exact.
I'd recommend using SphericalUtil.computeOffsetOrigin to compute the X/Y breaking
it into the latitude and longitude offsets as you are doing.
Finally demonstrating the SphericalUtil solution:
// Start with some arbitrary x/y relative to REF_LOC
double Rx = 125.0;
double Ry = 73.0;
// Compute a lat/lon from REF_LOC to the point
LatLng Rll = new LatLng(SphericalUtil.computeOffsetOrigin(REF_LOC, Ry, 180).latitude,
SphericalUtil.computeOffsetOrigin(REF_LOC, Rx, 270).longitude);
// And recompute the x/y components of the lat/lon
double Rxx = SphericalUtil.computeDistanceBetween(REF_LOC, new LatLng(REF_LOC.latitude, Rll.longitude));
double Ryy = SphericalUtil.computeDistanceBetween(REF_LOC, new LatLng(Rll.latitude, REF_LOC.longitude));
Resulting in:
Rx/Ry = (125.0, 73.0)
Rxx/Ryy = (125.00000004545973, 73.00000000137051)
Acceptable error I assume.
So the parting question is - what does the x/y really represent?
Reference the source for both utilities for more information:
Location
SphericalUtil

How can i check if location is in my radius?

i trying to get if location is in my radius.
i.e I have my current location "LatLng" object and i have one more "LatLng" object and i want to check if the two object are in rang of 1km?
How can i implement that?
In Location.distanceBetween() function provide you distance in meters and float value ..
distanceBetween(double startLatitude, double startLongitude, double
endLatitude, double endLongitude, float[] results) Computes the
approximate distance in meters between two locations, and optionally
the initial and final bearings of the shortest path between them.
use this it working i've already checked it .....
float[] dist = new float[1];
Location.distanceBetween(firstLoaction.latitude,firstLoaction.longitude,anotherLocation.latitude,anotherLocation.longitude,dist);
if(dist[0]/1000 > 1){
//here your code or alert box for outside 1Km radius area
}
NOTE:- For getting the location distance always use Location.distanceBetween() which is provide by ANDROID .
double distanceInKiloMeters = (currentLocation.distanceTo(someLocation)) / 1000; // as distance is in meter
if(distanceInKiloMeters <= 1) {
// It is in range of 1 km
}
else {
// not in range of 1 km
}
you can try converting LatLng to Location object for both first and then using distanceTo method to find the distance between those two and check if it is 1km or not
distanceto methode to get distance from locCenter and point and just substitute this distance from the radius if <0 so the point out of range , else the point in border or inside the range.. good luck

Google Places API LatLngBounds from LatLng and Radius

I am using the new Android place Api to get autocomplete predictions while the user type.
From what I saw so far the API takes a LatLngBounds object which is created using two locations.
Is there a way to generate a LatLngBounds object using one LatLng as a center point and a radius?
Thank you.
As promised Distwo, here is how I am creating a viewport based on a single latitude and longitude. The reason for me wanting to do this is that my store locator script searches from the viewport returned by the Places API, and so if a viewport isn't returned (rare but it happens) I go ahead and create one from the lat and lng returned by places. Please note that I am not using the android app, this is for regular web viewing.
console.log("no viewport found so lets spherically compute the bounds");
var sw = google.maps.geometry.spherical.computeOffset(place.geometry.location, 1609, 225);
var ne = google.maps.geometry.spherical.computeOffset(place.geometry.location, 1609, 45);
swlat = sw.lat().toFixed(6);
swlng = sw.lng().toFixed(6);
nelat = ne.lat().toFixed(6);
nelng = ne.lng().toFixed(6);
Not sure this is of use to you. In my case the radius is fixed, but in your situation it sounds though it's a variable and hence you'll have to refer to it as a variable.
OK so a little edit: I've changed 1423 to 1000, which represents a lilometer radius. If you're using kilometers then 1000 is the number to use, but if you're using miles then use "1609.3440006" instead.
Thanks to #luke_mclachlan, I found the method I was looking for on the google map github.
https://github.com/googlemaps/android-maps-utils/blob/master/library/src/com/google/maps/android/SphericalUtil.java
Here is the method I was looking for:
public static LatLng computeOffset(LatLng from, double distance, double heading) {
distance /= EARTH_RADIUS;
heading = toRadians(heading);
// http://williams.best.vwh.net/avform.htm#LL
double fromLat = toRadians(from.latitude);
double fromLng = toRadians(from.longitude);
double cosDistance = cos(distance);
double sinDistance = sin(distance);
double sinFromLat = sin(fromLat);
double cosFromLat = cos(fromLat);
double sinLat = cosDistance * sinFromLat + sinDistance * cosFromLat * cos(heading);
double dLng = atan2(
sinDistance * cosFromLat * sin(heading),
cosDistance - sinFromLat * sinLat);
return new LatLng(toDegrees(asin(sinLat)), toDegrees(fromLng + dLng));
}
Note that Heart radius here is expected in meters.
Using this method, I find the southwest (heading = 225) and northeast (heading = 45) coordinates and then create my LatLongBounds object.

Moving GPS coordinate

I am fairly new to Android programming, but I am getting pretty good at it (I think: ))
What I am doing is building a situated stories app. It is an app that places audio files at certain GPS markers and enables the user to listen to them at specific locations.
The next step is moving audio files. What I want to do is set a marker at a specific position in a city. (done). Next I want to check the location of a second marker that moves in a circle around it.
What I have so far is this:
public void checkCircularPosition(){
/*
* could be a solution?
*
radius = 250; //offset in meters
gpsLatCenter = 5.1164; //?how can i make this accurate in meters?
gpsLonCenter = 52.0963; //??how can i make this accurate in meters?
degree = 0; //should be variable over time (full circle in 1Hr, 3600sec --> 360/3600 = 0,1 deg/s)
radian;
radian = (degree/180)*Math.PI;
gpsCircleLat = gpsLatCenter+Math.cos(radian)*radius;
gpsCircleLon = gpsLonCenter-Math.sin(radian)*radius;
*/
}
Now, I have checked this code in adobe flash, which made a movie clip move around in a circle. So I know the calculations are somewhat right. But, I have no way of calculating the latitude and longitude of the resulting coordinates.
EDIT!!
i found the solution with the help posted below. still a lot of work to figure out how to use the results. anyway, i posted the resulting function below.
to make this work, you need _radius wich is 6371 (earth's radius), a bearing, a distance, and a start location.
thanks a lot guys!
public static void destinationPoint(double brng, double dist) {
dist = dist/_radius; // convert dist to angular distance in radians
brng = Math.toRadians(brng); //
double lat1 = Math.toRadians(_lat);
double lon1 = Math.toRadians(_lon);
double lat2 = Math.asin( Math.sin(lat1)*Math.cos(dist) + Math.cos(lat1)*Math.sin(dist)*Math.cos(brng) );
double lon2 = lon1 + Math.atan2(Math.sin(brng)*Math.sin(dist)*Math.cos(lat1), Math.cos(dist)-Math.sin(lat1)*Math.sin(lat2));
lon2 = (lon2+3*Math.PI) % (2*Math.PI) - Math.PI; // normalise to -180..+180º
Log.i(APPTAG, ""+Math.toDegrees(lat2));
Log.i(APPTAG, ""+Math.toDegrees(lon2));
Location movLoc = new Location("");
movLoc.setLatitude(Math.toDegrees(lat2));
movLoc.setLongitude(Math.toDegrees(lon2));
Log.i(APPTAG, ""+movLoc);
}
You should check the section Destination point given distance and bearing from start point at this website: http://www.movable-type.co.uk/scripts/latlong.html
That website has the proper formula for using your start point (gpsLatCenter/gpsLonCenter) and bearing (degree in you code) to compute the final lat/lon (gpsCircleLat/gpsCircleLon).

Categories

Resources