Android Find Latitude Longitude Of X point From Defined Location - android

i m working on Android MapView and developing a map based Application. i Need to find an X distance from the Specific Co-ordinates. Direction is not my priority Distance is my priority let say i need to find 100 meters from a particular location any idea on how can i do that
Thanks in advance for reading and answering.

in order to calculate to find a point on a line a given distance away from an origin, you need to have a bearing (or direction) as well as the distance. Here is a function that will take a starting location, a bearing and a distance (depth) and return a destination location (for Android): You may want to conver it from KM to Meters or whatever.
public static Location GetDestinationPoint(Location startLoc, float bearing, float depth)
{
Location newLocation = new Location("newLocation");
double radius = 6371.0; // earth's mean radius in km
double lat1 = Math.toRadians(startLoc.getLatitude());
double lng1 = Math.toRadians(startLoc.getLongitude());
double brng = Math.toRadians(bearing);
double lat2 = Math.asin( Math.sin(lat1)*Math.cos(depth/radius) + Math.cos(lat1)*Math.sin(depth/radius)*Math.cos(brng) );
double lng2 = lng1 + Math.atan2(Math.sin(brng)*Math.sin(depth/radius)*Math.cos(lat1), Math.cos(depth/radius)-Math.sin(lat1)*Math.sin(lat2));
lng2 = (lng2+Math.PI)%(2*Math.PI) - Math.PI;
// normalize to -180...+180
if (lat2 == 0 || lng2 == 0)
{
newLocation.setLatitude(0.0);
newLocation.setLongitude(0.0);
}
else
{
newLocation.setLatitude(Math.toDegrees(lat2));
newLocation.setLongitude(Math.toDegrees(lng2));
}
return newLocation;
};

Just to make the answer from javram into meters and radians instead of degrees.
/**
* Create a new location specified in meters and bearing from a previous location.
* #param startLoc from where
* #param bearing which direction, in radians from north
* #param distance meters from startLoc
* #return a new location
*/
public static Location createLocation(Location startLoc, double bearing, double distance) {
Location newLocation = new Location("newLocation");
double radius = 6371000.0; // earth's mean radius in m
double lat1 = Math.toRadians(startLoc.getLatitude());
double lng1 = Math.toRadians(startLoc.getLongitude());
double lat2 = Math.asin(Math.sin(lat1) * Math.cos(distance / radius) + Math.cos(lat1) * Math.sin(distance / radius) * Math.cos(bearing));
double lng2 = lng1 + Math.atan2(Math.sin(bearing) * Math.sin(distance / radius) * Math.cos(lat1), Math.cos(distance / radius) - Math.sin(lat1) * Math.sin(lat2));
lng2 = (lng2 + Math.PI) % (2 * Math.PI) - Math.PI;
// normalize to -180...+180
if (lat2 == 0 || lng2 == 0) {
newLocation.setLatitude(0.0);
newLocation.setLongitude(0.0);
} else {
newLocation.setLatitude(Math.toDegrees(lat2));
newLocation.setLongitude(Math.toDegrees(lng2));
}
return newLocation;
}

Related

Get Latitude Longitude after x kilometer on Google Map without destination?

I am creating an Android app which requires finding a coordinate on the same route after X kilometers.
I have two coordinates x1,y1 & x2,y2 on a road. Now, my requirement is to find coordinate x3,y3 after some 3 kilometers (i.e., coordinate after x2,y2 not between x1,y1 & x2,y2) on the same road.
How can this be achieved ?
If you know the bearing, you can calculate the destination coordinate.
Sample Code:
private LatLng getDestinationPoint(LatLng source, double brng, double dist) {
dist = dist / 6371;
brng = Math.toRadians(brng);
double lat1 = Math.toRadians(source.latitude), lon1 = Math.toRadians(source.longitude);
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));
if (Double.isNaN(lat2) || Double.isNaN(lon2)) {
return null;
}
return new LatLng(Math.toDegrees(lat2), Math.toDegrees(lon2));
}
Sample usage:
double radiusInKM = 10.0;
double bearing = 90;
LatLng destinationPoint = getDestinationPoint(new LatLng((25.48, -71.26), bearing, radiusInKM);
Or you can use heading between your pointA and pointB instead of bearing:
LatLng destinationPoint = getDestinationPoint(new LatLng(37.4038194,-122.081267), SphericalUtil.computeHeading(new LatLng(37.7577,-122.4376), new LatLng(37.4038194,-122.081267)), radiusInKM);
The SphericalUtil.computeHeading(p1, p2); method is from the Android Google Maps Utility library.
This is based on the Javascript method from this Stackoverflow answer.
If you want the point on same road, you might checkout this PHP answer.

Find nearby places android java

I have a list of latitude and longitude stored in database. Now I'm trying to develop a function on finding nearby place from my current location. Means that, i have to search all the latitude and longitude from my database and see which of the places are within my area will be shown.
Location.distanceBetween(lat1,lon1, lat2,lon2, result);
To find the distance from one two-dimensional point to another you can use the Haversine formula, (without calling any API functions.)
// All measurements are in meters
var rad = function(x) {
return x * Math.PI / 180;
};
var getDistance = function(coord1, coord2) {
// This is the Earth's radius
var earthRad = 6378137;
var dLat = rad(coord2.lat() - coord1.lat());
var dLong = rad(coord2.lng() - coord1.lng());
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(rad(coord1.lat())) * Math.cos(rad(coord2.lat())) *
Math.sin(dLong / 2) * Math.sin(dLong / 2);
var b = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var distance = earthRad * b;
// Returns distance from coord1 to coord2 in meters
return distance;
};
Your question is a bit broad so this might not be the best solution. If you were constantly updating your current location you'd have to implement a Tree Sorting algorithm or some other way of optimizing performance rather than checking through your database for distances on every update.
You can use the Location object. The distanceBetween or distanceTo method will give you the 'as the crow flies' distance between two points. From there you can filter your results and display only the places you want to.
here is what i use
public void nearBy() {
if (map.getMyLocation() != null) {//check if my location was found
db = new MyDatabase(MainActivity.context);
Cursor medecin = db.lireMedecin();//read values from database
map.clear();//clearing the map
while (medecin.getPosition() < medecin.getCount()) { //cheking if this doctor is nearby...
String Lat1 = medecin.getString(5);//doctor's latitude
String Lon1 = medecin.getString(6);//doctor's longitude
LatLng me = new LatLng(map.getMyLocation().getLatitude(), map.getMyLocation().getLongitude());//my location
LatLng med = new LatLng(Double.parseDouble(Lat1), Double.parseDouble(Lon1));//doctor location
if (CalDist(me, med) < 6) {//if distance is < 6km add marker to the map
map.addMarker(new MarkerOptions().position(med).title(medecin.getString(1) + " " + medecin.getString(2))
.snippet(medecin.getString(4)).icon(BitmapDescriptorFactory
.fromResource(Icone(medecin.getString(7).charAt(0))))); //showing the doctor on the map
}
medecin.moveToNext();//next doctor
}
} else
Toast.makeText(context, "Gps signal not valid", Toast.LENGTH_SHORT).show();//can't find my position
}
calculate distance :
public static double CalDist(LatLng StartP, LatLng EndP) {
int Radius = 6371;//­radius of earth in Km 
double lat1 = StartP.latitude ;
double lat2 = EndP.latitude ;
double lon1 = StartP.longitude ;
double lon2 = EndP.longitude ;
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
return Radius * c;
}

Android Google Map : Heading is drawn wrongly, when I draw a line with specific length and heading on Google Map

I have a GoogleMap in my project. It's set in zoom level 21. I want to draw a line that is 5 meter in length with a specific heading. I used this code:
private LatLng drawHeadingOnMap(LatLng centre, double radius, double heading)
{
double EARTH_RADIUS = 6378100.0;
// Convert to radians.
double lat = Math.toRadians(centre.latitude );
double lon = Math.toRadians(centre.longitude);
// y
double latPoint = lat + (radius / EARTH_RADIUS) * Math.sin(Math.toRadians(heading));
// x
double lonPoint = lon + (radius / EARTH_RADIUS) * Math.cos( Math.sin(Math.toRadians(heading)) / Math.cos(lat));
LatLng point =new LatLng(latPoint * 180.0 / Math.PI, lonPoint * 180.0 / Math.PI);
return point;
}
I run it by:
LatLng ll = drawHeadingOnMap(origin, 5, 90);
LatLng lll = drawHeadingOnMap(origin, 5, 0);
googleMap.addPolyline(new PolylineOptions().add(Mabda).add(ll).color(Color.BLUE).width(3));
googleMap.addPolyline(new PolylineOptions().add(Mabda).add(lll).color(Color.BLUE).width(3));
It draw 0 degree very well!! but others are wrong. for example this pic is shown the above code :
When I want to draw 90 degree, It draw sth like this pic! and after 90 , it get back to 0 degree (When I write drawHeadingOnMap(origin, 5, 180), It draw 0 degree!). How can I fix it? I'm so confused !!!...
Updated:
I tried it for origin= (12,12)...
I got this result:
ll.Latitude = 12.000898320495335
ll.Longitude = 12.00046835742835
lll.latitude = 12.0
lll.longitude = 12.000898320495335
ll is result for moving of (12,12) for 1 meter in direction of 90 degree.
lll is result for moving of (12,12) for 1 meter in direction of 0 degree.
the method is just OK for 0 degree ...
If you have a center point (10, 20), and you want to find the other point (x, y) to its 20 degree with radius 5, you can do the following math:
x = 10 + 5 * Math.sin(Math.toRadians(20));
y = 20 + 5 * Math.cos(Math.toRadians(20));
Not sure why you did Math.cos( Math.sin(Math.toRadians(heading)) / Math.cos(lat)) for your lonPoint.
To understand exact math I suggest reading this link.
If a working implementation is all you need use this function (adopted from Maps SphericalUtil):
/**
* #param loc location to transale (creates a copy)
* #param distance in meters
* #param heading in degrees, where 0 is NORTH, clockwise
* #return new location
*/
public static LatLng translate(LatLng loc, double distance, double heading){
double EARTH_RADIUS = 6378100.0;
heading = Math.toRadians(heading);
distance = distance/EARTH_RADIUS;
// http://williams.best.vwh.net/avform.htm#LL
double fromLat = Math.toRadians(loc.latitude);
double fromLng = Math.toRadians(loc.longitude);
double cosDistance = Math.cos(distance);
double sinDistance = Math.sin(distance);
double sinFromLat = Math.sin(fromLat);
double cosFromLat = Math.cos(fromLat);
double sinLat = cosDistance * sinFromLat + sinDistance * cosFromLat * Math.cos(heading);
double dLng = Math.atan2(
sinDistance * cosFromLat * Math.sin(heading),
cosDistance - sinFromLat * sinLat);
return new LatLng(Math.toDegrees(Math.asin(sinLat)), Math.toDegrees(fromLng + dLng));
}

Find geopoints in a radius near me

I have a DB with Geopoints.
I need to do a query to get all geopoints in the radius of X meters of me.
How can i do this?
I think the best way is get the minimal lat/long possible point, and the max lat/long point and get all of them for which: geopoint > minPoint AND geopoint < MaxPoint
Other ideas?
You can use this class to get de distance between to points:
How to use:
double distInKm = GeoMath.getDistance(12.345, -8.788, 12.33, -8.77);
Or, if point1 and point2 are GeoPoint:
double distInKm = GeoMath.getDistance(point1, point2);
You can also calculate a Geopoint that is a distance of you and along a bearing.
This computes a point that is 5 km northward from point1:
GeoPoint northPointAt5 = GeoMath.getGeoPointAlongBearing(point1, 0, 5);
You can calculate the other points at 90 degrees, 180 degrees and 270 degrees to calculate minPoint AND MaxPoint.
GeoMath class:
public class GeoMath {
public static final int EARTH_MEAN_RADIUS = 6371; // earth's mean radius in Km
public static double getDistance(double startLatitude, double startLongitude,
double endLatitude, double endLongitude){
return distHaversine(startLatitude,startLongitude,endLatitude,endLongitude);
}
public static double getDistance(GeoPoint point1, GeoPoint point2){
return distHaversine(point1.getLatitudeE6()/1E6, point1.getLongitudeE6()/1E6,
point2.getLatitudeE6()/1E6, point2.getLongitudeE6()/1E6);
}
private static double getSpanInRadians(double max, double min){
return Math.toRadians(max - min);
}
//Distance in Km between point1 (lat1,lon1) and point2 (lat2,lon2) Haversine formula
private static double distHaversine(double lat1, double lon1, double lat2, double lon2) {
double dLat = getSpanInRadians(lat2,lat1);
double dLon = getSpanInRadians(lon2,lon1);
lat1 = Math.toRadians(lat1);
lat2 = Math.toRadians(lat2);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = EARTH_MEAN_RADIUS * c;
return Math.round(dist * 1000)/1000; //3 decimal places
}
// Get GeoPoint at distance along a bearing
// bearing in degrees
// distance in Km
public static GeoPoint getGeoPointAlongBearing(GeoPoint location, double bearing, double distance){
double PI = Math.PI;
double NM = 1.852; //1 nm = 1.852 Km -> nm = Km/NM
GeoPoint geoPointAlongBearing;
double locationLatRad = Math.toRadians(location.getLatitudeE6()/1E6);
double locationLongRad = Math.toRadians(location.getLongitudeE6()/1E6)*(-1.0d);
double distanceRad = distance/NM * PI/(180*60);
double bearingRad = Math.toRadians(bearing);
double latAlongBearingRad = Math.asin(Math.sin(locationLatRad) *
Math.cos(distanceRad) +
Math.cos(locationLatRad) *
Math.sin(distanceRad) *
Math.cos(bearingRad));
double lonAlongBearingRad = mod(locationLongRad -
Math.asin(Math.sin(bearingRad) *
Math.sin(distanceRad) /
Math.cos(latAlongBearingRad)) + PI, 2 * PI) - PI;
double latAlongBearing = rad2lat(latAlongBearingRad);
double lonAlongBearing = rad2lng(lonAlongBearingRad) * (-1);
geoPointAlongBearing = new GeoPoint((int)(latAlongBearing*1E6),(int)(lonAlongBearing*1E6));
return geoPointAlongBearing;
}
private static double mod(double y, double x) {
return y - x * Math.floor(y/x);
}
}
With your query I think that you will find all points inside a square centered at your location and with a side length X.
After that, yuo can get all the points that are inside a circle centered at your location with radius X.
What about this pseudo code:
//create your location
Location yourLocation=new Location("myLoc");
double latitude = geoPointYourLocation.getLatitudeE6() / 1E6;
double longitude = geoPointYourLocation.getLongitudeE6() / 1E6;
yourLocation.setLatitude(latitude);
yourLocation.setLongitude(longitude);
//Browse geopoints from DB, convert to GeoPoint and check if it is at a distance less than X
for (geoPointTemp in in query geopoint of your DDBB inside square) {
//create the location of the geopoint
Location locTemp=new Location("locTemp");
double latitude = geoPointTemp.getLatitudeE6() / 1E6;
double longitude = geoPointTemp.getLongitudeE6() / 1E6;
locTemp.setLatitude(latitude);
locTemp.setLongitude(longitude);
//calculate the distance between you and de temporary location
double distance=yourLocation.distanceTo(locTemp);
if(distance<X){
//do something
}
With Mysql, you can use built-in spacial functions such as GLength, linestring ....

How can I calculate a current distance to polyline points on google maps v2 in android?

I have used tutorial from the link below to display Google map route in Android app. My question is how can I calculate distance to polyline points on map? Like when I use Google maps app and it tells when a street turn is getting close. I want to implement similar feature in my app. I am able to display the route polyline on the map and it updates itself while I drive along it but I want it to warn me 500 feet in advance of a coming turn. How can I do that?
Here is the link:
http://jigarlikes.wordpress.com/2013/04/26/driving-distance-and-travel-time-duration-between-two-locations-in-google-map-android-api-v2/
I use this method for Markers. Assuming you have Latitude and Longitude of the points that make up the Polyline this should do:
public class MapUtils {
public static float distBetween(LatLng pos1, LatLng pos2) {
return distBetween(pos1.latitude, pos1.longitude, pos2.latitude,
pos2.longitude);
}
/** distance in meters **/
public static float distBetween(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 3958.75;
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));
double dist = earthRadius * c;
int meterConversion = 1609;
return (float) (dist * meterConversion);
}
}
To determine wether the road is turning, I would look into euclidean angle between vectors (x being current location and y being a polyline point)
Simply take your current location and a LatLng from some distance ahead for this.
Calculation is based on: http://en.wikipedia.org/wiki/Euclidean_space#Angle
Location currentLocation; // obtained somewhere in your code
LatLng polylinePoint; // a point further ahead
double cLat = currentLocation.getLatitude();
double cLon = currentLocation.getLongitude();
double pLat = polylinePoint.latitude;
double pLon = polylinePoint.longitude;
double angle = Math.acos(
(cLat*pLat+cLon+pLon) / norm(cLat,cLon)*norm(pLat,cLon));
private double norm(double x, double y) {
return Math.sqrt(Math.pow(x, 2)*Math.pow(y, 2));
}
This is untested so might contain error.

Categories

Resources