Geocoder.getFromLocation()不返回任何地址

时间:2016-09-19 16:48:03

标签: android google-geocoder

我试图通过经度和纬度来获取位置信息(国家名称,城市名称等)。但是,以下代码不返回任何地址,addresses.size()始终为零!!我需要帮助。谢谢。

public class FirstUsage extends Activity{

private LocationListener myLocListener;
private LocationManager myLocManager;
private TextView tv;
private Button okButt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.first_use_page);

    tv = (TextView)findViewById(R.id.TextView_firstPageCoordination);
    okButt = (Button)findViewById(R.id.firstPageOKButt);

    myLocManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    setLocationChangeListener();
}

private void setLocationChangeListener() {
    myLocListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {

            /*----------to get City-Name from coordinates ------------- */
            String countryName = null;
            Geocoder gcd = new Geocoder(FirstUsage.this, Locale.getDefault());
            List<Address> addresses;
            try {
                addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                if (addresses.size() > 0) {

                    Address returnedAddress = addresses.get(0);
                    countryName = returnedAddress.getCountryName();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            tv.setText("Your current country is: " + countryName + "\n Your current coordination is:\n" + "Longitude: " + location.getLongitude() + "   Latitude: " + location.getLatitude());


            /////
            if (ActivityCompat.checkSelfPermission(FirstUsage.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(FirstUsage.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            myLocManager.removeUpdates(myLocListener);
        }

2 个答案:

答案 0 :(得分:1)

有时在连接不可用或后端未实现时附加。验证这两件事的最佳方法是使用以下方法检查地理编码器是否存在:

gcd.isPresent ()
  

如果Geocoder方法为getFromLocation,则返回true   getFromLocationName已实现。可能缺乏网络连接   仍会导致这些方法返回null或空列表。

答案 1 :(得分:1)

来自android documentation

  

Geocoder类需要一个未包含的后端服务   核心android框架。

问题是您的设备/模拟器中没有Geocoder后端服务。您的设备/模拟器需要Google API才能正常使用Grocoder。