GeoPoint and current Location - android

how I can get current GeoPoint from my location.
I am on :
Longitude: 21.760029
Latitude: 54.035795
But when I use getLatitude(), I have 54.0
but I want 54.035795.

Here's a method for converting a latitude, longitude pair to a GeoPoint object:
public static GeoPoint convert(double latitude, double longitude)
{
int lat = (int)(latitude * 1E6);
int lng = (int)(longitude * 1E6);
return new GeoPoint(lat, lng);
}

Related

Show closest result of a Geocoder on map

I've been stuck on the problem. i'm searching for Tesco stores in this geocoder. Is there anyway way of getting only the closest result of the geo.getFromLocationName?
private void setUpMap() throws IOException {
Geocoder geo = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addressList= geo.getFromLocationName("Tesco",1);
Address add = addressList.get(0);
String locality = add.getLocality();
double lat = addressList.get(0).getLatitude();
double lng = addressList.get(0).getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat,lng)).title("Waitrose"));
}
Modify your method like this:
private void setUpMap() throws IOException {
Geocoder geo = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addressList= geo.getFromLocationName("Tesco",1);
Address yourAddress = // get your location or the address to compare
Address closest = findClosest(addressList, yourAddress);
// do what you need
}
To create the findClosest you have to create a function that iterates over results and use haversine formula to calculate the distance to your location (or the desired one).
public double rad(double x)
{
return x*Math.PI/180.;
}
public Address findClosest( List<Address> addressList, Address yourAddress )
{
double lat = yourAddress.getLatitude(); // your (or desired) latitude
double lng = yourAddress.getLongitude(); // your (or desired) longitude
double R = 6371.; // radius of earth in km
double[] distances = new double[addressList.lenght];
var closest = -1;
for( i=0;i<addressList.lenght; i++ ) {
double mlat = addressList.get(i).getLatitude();
double mlng = addressList.get(i).getLongitude();
double dLat = rad(mlat - lat);
double dLong = rad(mlng - lng);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong/2) * Math.sin(dLong/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double d = R * c;
distances[i] = d;
if ( closest == -1 || d < distances[closest] ) {
closest = i;
}
}
return addressList.get(closest);
}

Tracking in Geofence radious

I have Created application for geo fence.
I implement location listener which sends me current Lat and Long.
I have array of Lat Long and i created Geofence from this array.
I want to check that Current lat long are within my Geofence Region or not?
Code For Geofence:-
private void createGeofence(double latitude, double longitude, int radius,
String geofenceType, String title) {
Marker stopMarker = googleMap.addMarker(new MarkerOptions()
.draggable(true)
.position(new LatLng(latitude, longitude))
.title(title)
);
googleMap.addCircle(new CircleOptions()
.center(new LatLng(latitude, longitude)).radius(radius)
.fillColor(Color.parseColor("#B2A9F6")));
}
Lat Long from Listener:-
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Lat=location.getLatitude();
Lng=location.getLongitude();
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(Lat, Lng, 1);
address = addresses.get(0).getAddressLine(0);
city = addresses.get(0).getAddressLine(1);
country = addresses.get(0).getAddressLine(2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Lat Long is "+ Lat + " " + Lng);
}
Please help for this.
You could use the harvesine formula:
public static final double R = 6372.8; // In kilometers
public static double haversine(double lat1, double lon1, double lat2, double lon2) {
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
lat1 = Math.toRadians(lat1);
lat2 = Math.toRadians(lat2);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.asin(Math.sqrt(a));
return R * c;
}
That will give you the distance between the two locations. After that you could compare that distance with the geofence region radius to know if is inside the region.
Note: This distance will be in kilometers if your radius is on meters then just multiply the haversine method result with 1000 so that it's converted to meters.
Reference

Display title of closest marker from my current position Google Maps v2

I get the data from my database which contains, TITLE, SNIPPET and LOCATION and tried to test to check the distances between my currentlocation. I'm confused how to display the title of the closest marker to my position.
List<MyMarkerObj> m = data.getMyMarkers();
for (int i = 0; i < m.size(); i++) {
String[] slatlng = m.get(i).getPosition().split(" ");
LatLng lat = new LatLng(Double.valueOf(slatlng[0]), Double.valueOf(slatlng[1]));
map.addMarker(new MarkerOptions()
.title(m.get(i).getTitle())
.snippet(m.get(i).getSnippet())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.position(lat)
);
float[] distance = new float[1];
Location.distanceBetween(currentlat, currentlong,Double.valueOf(slatlng[0]), Double.valueOf(slatlng[1]), distance);
Toast.makeText(getActivity(), "Marker Distance: "+ m.get(i).getTitle() +" "+distance[0], Toast.LENGTH_LONG).show();
}
I made few changes here. Try it..
List<MyMarkerObj> m = data.getMyMarkers();
float mindist;
int pos=0;
for (int i = 0; i < m.size(); i++) {
String[] slatlng = m.get(i).getPosition().split(" ");
LatLng lat = new LatLng(Double.valueOf(slatlng[0]), Double.valueOf(slatlng[1]));
map.addMarker(new MarkerOptions()
.title(m.get(i).getTitle())
.snippet(m.get(i).getSnippet())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.position(lat)
);
float[] distance = new float[1];
Location.distanceBetween(currentlat, currentlong,Double.valueOf(slatlng[0]), Double.valueOf(slatlng[1]), distance);
if(i==0) mindist=distance[0];
else if(mindist>distance[0]) {
mindist=distance[0];
pos=i;
}
}
Toast.makeText(getActivity(), "Closest Marker Distance: "+ m.get(pos).getTitle() +" "+mindist, Toast.LENGTH_LONG).show();
You can use this simple function to calculate distance between two points in latitude and longitude format it works like a charm, and you can then check for which distance is closest from your location. just pass the latitude and longitude of both location in it
public double distanceFrom(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 new Double(dist * meterConversion).floatValue(); // this will return distance
}

method distanceTo(double) is undefined

I have a Problem to get the right way to get the distanceTo from my 2 Geo Points. How to get it work?
from the gps class:
double latitude; // latitude
String mlat;
latitude = location.getLatitude();
mlat = String.valueOf(latitude);
from the ListView:
// Get distance
String mReportA;
double mLocB;
int distance;
mReportA = e.getString("lat");
mReportA = e.getString("lon");
mLocB = gps.latitude;
mLocB = gps.longitude;
distance = mReportA.distanceTo(mLocB);
Error in Eclipse: The method distanceTo(double) is undefined for the type String
I get e.getString("lat"); from json
To calculate distance between two geopoint you can follow the below example.
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
double endLatitude = lat;
double endLongitude = lng;
float[] results = new float[3];
Location.distanceBetween(currentLatitude, currentLongitude,endLatitude, endLongitude, results);
BigDecimal bd = new BigDecimal(results[0]);// results in meters
BigDecimal rounded = bd.setScale(2, RoundingMode.HALF_UP);
double values = rounded.doubleValue();
EDIT
if (values > 1000) {
values = (Double) (values * 0.001f);// convert meters to Kilometers
bd = new BigDecimal(values);
rounded = bd.setScale(2, RoundingMode.HALF_UP);
values = rounded.doubleValue();
}
// Here is the code to find out the distance between two locations
float distance;
Location locationA = new Location("A");
locationA.setLatitude(latA);
locationA.setLongitude(lngA);
Location locationB = new Location("B");
locationB.setLatitude(latB);
LocationB.setLongitude(lngB);
distance = locationA.distanceTo(locationB);

Map Draw Path and Calculate Distance

How to Draw path and Calculate Distance on Move. The code below dont calculate distance at onLocationChanged method??
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
String text = String.format("Lat:\t %f\nLong:\t %f\nAlt:\t %f\nBearing:\t %f\nDistance:\t %f",
location.getLatitude() *1E6, location.getLongitude() *1E6,
location.getAltitude() *1E6, location.getBearing() *1E6, location.distanceTo(location));
textOut.setText(text);
lat = (int) (location.getLatitude() *1E6);
longi = (int) (location.getLongitude() *1E6);
GeoPoint myLocation = new GeoPoint(lat, longi);
OverlayItem overlayItem = new OverlayItem(myLocation, "WHATZ UP", "2nd String");
StagePoint custom = new StagePoint(d, Start.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}
private class MyLocationOverlay1 extends MyLocationOverlay {
#Override
public void drawMyLocation(Canvas canvas, MapView mapView, Location lastFix, GeoPoint myLocation, long when)
super.drawMyLocation(canvas,mapView,lastFix,myLocation,when);
Location bLocation = new Location("reverseGeocoded");
bLocation.setLatitude(FindList.gpslat);
bLocation.setLongitude(FindList.gpslong);
Location aLocation = new Location("reverseGeocoded");
aLocation.setLatitude(myLocation.getLatitudeE6() / 1e6);
aLocation.setLongitude(myLocation.getLongitudeE6() / 1e6);
int distance = (int)aLocation.distanceTo(bLocation);
String str = " (" + String.valueOf(distance) + " meters)";
}
}

Categories

Resources