Show closest result of a Geocoder on map

穿精又带淫゛_ 提交于 2019-12-24 14:08:01

问题


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"));
}

回答1:


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);
}


来源:https://stackoverflow.com/questions/29120950/show-closest-result-of-a-geocoder-on-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!