在地图上显示地理编码器的最接近结果

Show closest result of a Geocoder on map

我一直卡在这个问题上。我正在使用此地理编码器搜索 Tesco 商店。有没有办法只得到最接近 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"));
}

像这样修改你的方法:

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
}

要创建 findClosest,您必须创建一个迭代结果的函数,并使用 haversine formula 计算到您所在位置(或所需位置)的距离。

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