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

标签 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);
        }

最佳答案

来自android documentation :

The Geocoder class requires a backend service that is not included in the core android framework.

问题是地理编码器后端服务在您的设备/模拟器中不可用。您的设备/模拟器需要 Google API 才能与 Grocoder 正常工作。

关于android - Geocoder.getFromLocation() 不返回任何地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39578181/

相关文章:

java.lang.NullPointerException : Can't pass null for argument 'pathString' in child() - Error Occurs in MessagesDbRef

java - 我的应用程序卡住,如何在其中实现线程?

android - 在 android 中解析 XML 时的字符编码问题

javascript - 将现有的 WebView JavascriptInterface 与 React-Native 结合使用

JavaScript 将数组插入数组

google-maps-api-3 - 使用 Googlemaps 地理编码器并存储数据

java - 在 Azure AD B2C 注册页面上添加自定义电话号码字段

javascript - 将 json 响应获取到变量中

java - Geocoder.isPresent() 导致 NullPointerException?

Java Geocoding - 将纬度和经度转换为地址