简体   繁体   中英

android- Find nearest location to my current place

I've some gps coordinate on my database.

I get my current location but I don't know how can I find the nearest location to me and the distance between me and those point .

Could you help me to find the nearest locations and the distance between me and those points ?

You can use the built in method distanceBetween() of the class android.location.Location to calculate the distance between two lat longs.

Documentation

On the whole what you will need to do is, find the distance between your current location and all other points individually and then find out the smallest one.

Use this method to find distance between two points http://www.geodatasource.com/developers/java

private double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
      double theta = lon1 - lon2;
      double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
      dist = Math.acos(dist);
      dist = rad2deg(dist);
      dist = dist * 60 * 1.1515;
      if (unit == "K") {
        dist = dist * 1.609344;
      } else if (unit == "N") {
        dist = dist * 0.8684;
        }
      return (dist);
    }

    private double deg2rad(double deg) {
      return (deg * Math.PI / 180.0);
    }

    system.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "M") + " Miles\n");
    system.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "K") + " Kilometers\n");
    system.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "N") + " Nautical Miles\n");

you can calculate the distance between two latLongs usng this.

Location loc1 = new Location("");
loc1.setLatitude(lat1);
loc1.setLongitude(lon1);

Location loc2 = new Location("");
loc2.setLatitude(lat2);
loc2.setLongitude(lon2);

float distanceInMeters = loc1.distanceTo(loc2);

For finding nearest location, I am not sure what you are referring to. Please elaborate.

Can you please tell us what is mean by nearest location? Do you have lat-long of that location (Nearest location)?

If yes then you can use distanceBetween() method of Location class. http://developer.android.com/reference/android/location/Location.html#distanceBetween%28double,%20double,%20double,%20double,%20float[]%29

If No, then Google has some API which gives you nearby places which is registered on Google like Malls, Airports and then you can find distances between you and other locations.

Please see below link for more details.

http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM