仅地理编码 returns 个空对象

Geocoder only returns null objects

我正在制作一个 android 应用程序,该应用程序的一个功能是它可以根据经纬度对输入的街道地址进行地理编码,然后在地图上标记该点。

我已经尝试了来自各地的各种解决方案,但我无法让它工作!

  public LatLng getLocationFromAddress(String strAddress) {

    Geocoder coder = new Geocoder(getApplicationContext(), Locale.getDefault());
    List<Address> address;

    try {
        address = coder.getFromLocationName(strAddress, 1);
        while(address.size()==0){
            address = coder.getFromLocationName(strAddress,1);
        }
        Address location = address.get(0);
        double lat = location.getLatitude();
        double lng = location.getLongitude();
        return new LatLng(lat,lng);
    } catch (Exception e) {
        return null;
    }
}

当我如下所示测试此方法时:

       pickupPointsPlots.add(getLocationFromAddress("london"));
        for (int i = 0; i < pickupPointsPlots.size(); i++) {
        LatLng position = pickupPointsPlots.get(i);
        MarkerOptions options = new MarkerOptions().position(position);

        googleMap.addMarker(options);

    }

} 

我收到这个错误

 java.lang.IllegalArgumentException: latlng cannot be null - a position is required.

试试这个。

(注意:你制作了 getLocationFromAddress() 一个 public 方法,所以我不能确定这是否在另一个 class 从它被调用的地方所以我传递确定上下文。如果 getLocationFromAddress() 在您的 activity class 中,则只需使用 "TheNameOfActivity.this" 而不是 getApplicationContext()。)

public LatLng getLocationFromAddress(Context context, String strAddress) {
    LatLng latLng = null;
    try {
        Geocoder coder = new Geocoder(context, Locale.getDefault());
        List<Address> address = coder.getFromLocationName(strAddress, 1);
        // will only iterate through address list when the geocoder was successful
        for(Address a : address){
            latLng = new LatLng(a.getLatitude, a.getLongitude);
            Log.e(TAG, "Country Name = " + a.getCountryName());
        }
    } catch (Exception e) {
        //Log that error!
        Log.e(TAG, e.getMessage());
    }
    //will return null if an address was not found
    return latLng;
}

您的 getLocationFromAddress() 方法只返回一个位置,因此不需要列表。因此,使用您的代码片段:

    ....
    LatLng latLng = getLocationFromAddress(TheNameOfActivity.this, "london");
    if(latLng != null){
        MarkerOptions options = new MarkerOptions().position(latLng);
        if(googleMap != null){
            googleMap.addMarker(options);
        {
    }
} 

请务必将 "TheNameOfActivity" 替换为您 activity

的真实姓名