android getFromLocationName()有时会返回null

时间:2017-03-11 17:28:00

标签: android locationmanager google-geocoder android-gps

我的代码仅适用于80%的地址,我不明白为什么有时候我得不到结果。如果地址工作正常,我只需将街道号码从1更改为2即可运行。

我提供的我的字符串地址如下所示: "街道号码,邮政编码,城市" 或者对于US,CA,EN: "没有街道,邮政编码,城市"

public Map<Location, String> getLocationFromAddress(String strAddress) {
    Geocoder coder = new Geocoder(ctx, Locale.getDefault());
    List<Address> address;
    Location res = new Location(LocationManager.GPS_PROVIDER);
    Map<Location, String> resMap = new HashMap<Location, String>();
    try {
        address = coder.getFromLocationName(strAddress, 5);
        if (address == null) {
            return null;
        }
        Address location = address.get(0);
        String addressText = "";
        if(location.getAddressLine(0) != null && 
              location.getAddressLine(1) != null)
            addressText = location.getAddressLine(0) + 
               " - " +location.getAddressLine(1);
        res.setLatitude(location.getLatitude());
        res.setLongitude(location.getLongitude());
        resMap.put(res, addressText);
        Log.d("LocationUtil: ", addressText);
        } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
    return resMap;
}

0 个答案:

没有答案