0

我正在尝试查找没有城市的街道地址的位置(纬度/经度) - 例如“123 Main St.” - 最接近当前位置。此功能内置于 Google Maps 应用程序和 iOS 地图 api 中,因此令人惊讶的是 Android 缺少该功能 - 例如调用 Geocoder.getFromLocation() 并让平台插入参考点。我尝试了几种解决方案,以下是最好的,但仍然感觉逊色。

我用左下角和右上角的坐标调用 Geocoder.getFromLocationName()。从当前位置周围 10kmx10km 的区域开始调用,然后重复(30x30、100x100,然后不带边界框参数)直到返回一些地址。当返回多个地址时,计算并使用最接近的地址:

更新:这种方法对于容易找到的越界地址似乎效率低下。例如,从西海岸搜索“New york, NY”或“Boston” - 需要对 Geocoder.getFromLocation() 进行 3 次有界和 1 次无界调用。然而,出乎意料的是,在第一次调用时,为纽约市和波士顿返回了正确的纬度/经度,在加州这里有最严格的界限。谷歌很聪明,无视我们的界限。这可能会给某些人带来问题,但这种方法非常有用。

package com.puurbuy.android;

import java.io.IOException;
import java.util.List;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.util.Log;

public class GeocoderRunner extends AsyncTask<String, Void, Address> {
    final static double LON_DEG_PER_KM = 0.012682308180089;
    final static double LAT_DEG_PER_KM =0.009009009009009;
    final static double[] SEARCH_RANGES = {10, 50,800,-1}; //city, region, state, everywhere

private Context mContext;
private GeocoderListener mListener;
private Location mLocation;

public GeocoderRunner(Context context, Location location,
        GeocoderListener addressLookupListener) {
    mContext = context;
    mLocation = location;
    mListener = addressLookupListener;
}
@Override
protected Address doInBackground(String... params) {
    Geocoder geocoder = new Geocoder(mContext);
    List<Address> addresses = null;

    //reference location TODO handle null 
    double lat = mLocation.getLatitude();
    double lon = mLocation.getLongitude();
    int i = 0;
    try {
        //loop through SEARCH_RANGES until addresses are returned
        do{
            //if range is -1, call  getFromLocationName() without bounding box
            if(SEARCH_RANGES[i] != -1){

                //calculate bounding box
                double lowerLeftLatitude =  translateLat(lat,-SEARCH_RANGES[i]);
                double lowerLeftLongitude = translateLon(lon,SEARCH_RANGES[i]);
                double upperRightLatitude = translateLat(lat,SEARCH_RANGES[i]);
                double upperRightLongitude = translateLon(lon,-SEARCH_RANGES[i]);

                addresses = geocoder.getFromLocationName(params[0], 5, lowerLeftLatitude, lowerLeftLongitude, upperRightLatitude, upperRightLongitude);

            } else {
                //last resort, try unbounded call with 20 result
                addresses = geocoder.getFromLocationName(params[0], 20);    
            }
            i++;

        }while((addresses == null || addresses.size() == 0) && i < SEARCH_RANGES.length );

    } catch (IOException e) {
        Log.i(this.getClass().getSimpleName(),"Gecoder lookup failed! " +e.getMessage());
    }



    if(addresses == null ||addresses.size() == 0)
        return null;

    //If multiple addresses were returned, find the closest
    if(addresses.size() > 1){
        Address closest = null;
        for(Address address: addresses){
            if(closest == null)
                closest = address;
            else
                closest = getClosest(mLocation, closest,address);//returns the address that is closest to mLocation
        }
        return closest;
    }else
        return addresses.get(0);

}

@Override
protected void onPostExecute(Address address) {
    if(address == null)
        mListener.lookupFailed();
    else
        mListener.addressReceived(address);

}

//Listener callback
public interface GeocoderListener{
    public void addressReceived(Address address);
    public void lookupFailed();
}

//HELPER Methods

private static double translateLat(double lat, double dx){
    if(lat > 0 )
        return (lat + dx*LAT_DEG_PER_KM);
    else
        return (lat - dx*LAT_DEG_PER_KM);
}

private static double translateLon(double lon, double dy){
    if(lon > 0 )
        return (lon + dy*LON_DEG_PER_KM);
    else
        return (lon - dy*LON_DEG_PER_KM);

}

private static Address getClosest(Location ref, Address address1, Address address2){
    double xO = ref.getLatitude();
    double yO = ref.getLongitude();
    double x1 = address1.getLatitude();
    double y1 = address1.getLongitude();
    double x2 = address2.getLatitude();
    double y2 = address2.getLongitude();
    double d1 = distance(xO,yO,x1,y1);
    double d2 = distance(xO,yO,x2,y2);
    if(d1 < d2)
        return address1;
    else
        return address2;

}

private static double distance(double x1, double y1, double x2, double y2){
    return Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) );
}

}

也许这是最好的解决方案,但我想知道是否有办法在一次通话中做到这一点。

4

3 回答 3

2

你的代码看起来太复杂了,这里有更简单的方法:

    String searchPattern = "123 Main St." 
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    //I use last known location, but here we can get real location
    Location lastKnownLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    List<Address> addresses = null;
    try {
        //trying to get all possible addresses by search pattern
        addresses = (new Geocoder(this)).getFromLocationName(searchPattern, Integer.MAX_VALUE);
    } catch (IOException e) {
    }
    if (addresses == null || lastKnownLocation == null) {
        // location service unavailable or incorrect address
        // so returns null
        return null;
    }

    Address closest = null;
    float closestDistance = Float.MAX_VALUE;
    // look for address, closest to our location
    for (Address adr : addresses) {
        if (closest == null) {
            closest = adr;
        } else {
            float[] result = new float[1];
            Location.distanceBetween(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude(), adr.getLatitude(), adr.getLongitude(), result);
            float distance = result[0];
            if (distance < closestDistance) {
                closest = adr;
                closestDistance = distance;
            }
        }
    }
    return closest; //here can be null if we did not find any addresses by search pattern.
于 2012-09-25T06:43:17.483 回答
0

我尝试了 Jin35 的建议,并增加了 Geocoder.getFromLocationName() 的 max_results,但结果并不理想。首先,最大的 max_result 无界调用比我的模拟器上的 5 结果 geocoord 有界调用花费了更长的时间(2.5x - 7x = 1 - 6 秒)。也许现实世界会更快,这个因素变得不那么重要了。

杀手锏是不管 max_results 是 50 还是 100,每次只返回 20 个结果。似乎谷歌正在限制服务器端的结果。对我来说,最接近的“123 Main St”不在这 20 个结果中——从加利福尼亚州的 Mt View 测试并返回加利福尼亚州的奥克利。

除非有除 Geocoder.getFromLocationName() 之外的其他方法来进行地址查找,或者使用边界坐标的更好方法,否则我会接受我自己的原始答案。

于 2012-09-25T19:14:32.987 回答
0
    getFromLocationName(String locationName, int maxResults, double lowerLeftLatitude, double lowerLeftLongitude, double upperRightLatitude, double upperRightLongitude)
于 2013-07-19T18:41:06.443 回答