有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从坐标中获取城市名称

我的应用程序获取用户坐标。现在我想知道坐标所属城市的名称。我搜索了其他线程,但没有找到有用的或新的内容。我的文本视图应该显示地址名,但它仍然是空的,或者这是获取地址的错误方式吗

我的代码:

public class MainActivity extends AppCompatActivity {

    double lat;
    double lon;
    Button btnLoc;
    TextView textView7;

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

        TextView textView7 = (TextView) findViewById(R.id.textView7);

        btnLoc = (Button) findViewById(R.id.btnGetLoc);
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);

        btnLoc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                GPSTracker gt = new GPSTracker(getApplicationContext());
                Location location = gt.getLocation();

                if (location == null) {
                    Toast.makeText(getApplicationContext(), "GPS unable to get Value", Toast.LENGTH_SHORT).show();
                } else {

                    double lat = location.getLatitude();
                    double lon = location.getLongitude();

                    TextView textView5 = (TextView) findViewById(R.id.textView5);
                    textView5.setText(String.valueOf(lat));

                    TextView textView6 = (TextView) findViewById(R.id.textView6);
                    textView6.setText(String.valueOf(lon));

                }
            }
        });

        try {

            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
            if (addresses.size() > 0)

                textView7.setText(addresses.get(0).getLocality());
        } catch (IOException e) {

        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    我注意到了一些事情

    1. 您没有初始化在活动范围中定义的lat和long

      双lat; 双离子

    当您将它们传递到函数中时,它们将保持为null

    List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
    

    因此,您可能希望尝试从click函数中的lat/long变量中删除类型

                - double lat = location.getLatitude();
                - double lon = location.getLongitude();
    
    
                + lat = location.getLatitude();
                + lon = location.getLongitude();
    
    1. 单击后尝试获取结果。在初始化click侦听器之后不会。由于在获取位置后没有适当的回调设置(我假设这是一个异步调用),因此可以通过设置另一个按钮/单击侦听器来暂时克服这一问题,在获取坐标后可以单击该按钮/单击侦听器

    如果这不起作用,请看一下这个简短的有用指南 https://www.kerstner.at/2013/08/convert-gps-coordinates-to-address-using-google-geocoding-api-in-java/

    干杯