Geocoder仅返回null对象

时间:2018-05-22 00:46:09

标签: java android geocoding

我正在制作一个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.

1 个答案:

答案 0 :(得分:0)

试一试。

(注意:你使getLocationFromAddress()成为一个公共方法,所以我无法确定它是否在另一个类中,因为我正在传递上下文以确定。如果{{1在您的活动类中,然后只使用“TheNameOfActivity.this”而不是getLocationFromAddress()。)

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()

确保将“TheNameOfActivity”替换为您活动的实际名称

相关问题