java - 从坐标中获取城市名称
问题描述
我的应用程序获取用户坐标。现在我尝试获取坐标所属城市的名称。我搜索了其他线程,但没有找到有用或新的东西。我应该显示地址名称的 textView 只是保持空白,还是获取地址的错误方法?
我的代码:
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) {
}
}
}
解决方案
我注意到了一些事情。
您没有初始化您在活动范围中定义的经纬度。
双纬度;双龙;
当您将它们传递给您的函数时,它们将保持为空
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();
- 单击后尝试获取结果。不是在初始化单击侦听器之后。由于您在获取您的位置后没有适当的回调设置来触发(我假设它是一个异步调用),您可以通过设置另一个按钮/单击侦听器来暂时克服这个问题,您可以在获取后单击该侦听器你的坐标。
如果这不起作用,请查看这个简短的有用指南 https://www.kerstner.at/2013/08/convert-gps-coordinates-to-address-using-google-geocoding-api-in-java/
干杯
推荐阅读
- swiftui - 在滚动视图中初始化无数据,稍后添加无显示
- typescript - 如何清除 ion-datetime ionic4 的值
- java - Spring Data Mongo 没有访问器来设置已初始化的最终属性
- sql - 具有对应值总和的 SQL 不同列
- tensorflow - 如何在不弃用的情况下修复错误 tensorflow has not attribute 'ConfigProto'?
- python - Pandas - 如何交换列内容,保持标签序列不变?
- python - 如何在 django rest 框架中附加序列化程序
- tkinter - Tkinter 防止手动输入到 Combobox
- python - 在 python 烧瓶中不使用 celery 执行多个任务
- typescript - 如何更改打字稿中的所有接口值