Android获取当前城市名称

时间:2022-03-19 20:33:03

参考:残缺的孤独
txxs

不需要导入百度地图的SDK,利用手机自带的定位,获取当前的经纬度,然后调用百度地图的地址,返回的为json数据

{
status: "OK",
result: {
location: {
lng: 118.776047,
lat: 31.965235
},
formatted_address: "江苏省南京市雨花台区龙西路",
business: "铁心桥",
addressComponent: {
city: "南京市",
direction: "",
distance: "",
district: "雨花台区",
province: "江苏省",
street: "龙西路",
street_number: ""
},
cityCode: 315
}
}
//wd 纬度 
//jd 经度
public void updateVersion(String wd, String jd) {
String path = "http://api.map.baidu.com/geocoder?output=json&location=" + wd + "," + jd + "&key="这里为你的百度地图的key";
OkHttpUtils
.get()
.url(path)
.build()
.execute(new StringCallback() {
@Override
public void onError(Call arg0, Exception arg1, int arg2) {
}

@Override
public void onResponse(String arg0, int arg1) {
Gson gson = new Gson();
City response = gson.fromJson(arg0, City.class);
CMLog.d(TAG, arg0);
if (response.getStatus().equals("OK")) {
CMLog.d("地址为", response.getResult().getAddressComponent().getCity());
}
}

});
}


public void getLocation() {
String locationProvider;
//获取地理位置管理器
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//获取所有可用的位置提供器
List<String> providers = locationManager.getProviders(true);
if (providers.contains(LocationManager.GPS_PROVIDER)) {
//如果是GPS
locationProvider = LocationManager.GPS_PROVIDER;
} else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
//如果是Network
locationProvider = LocationManager.NETWORK_PROVIDER;
} else {
Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();
return;
}
//获取Location
Location location = locationManager.getLastKnownLocation(locationProvider);
if (location != null) {
//不为空,显示地理位置经纬度
showLocation(location);
}
//监视地理位置变化
locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);
}

/**
* 显示地理位置经度和纬度信息
*
* @param location
*/
private void showLocation(Location location) {
String locationStr = "纬度:" + location.getLatitude() + "\n"
+ "经度:" + location.getLongitude();
updateVersion(location.getLatitude() + "", location.getLongitude() + "");
}

/**
* LocationListern监听器
* 参数:地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器
*/

LocationListener locationListener = new LocationListener() {

@Override
public void onStatusChanged(String provider, int status, Bundle arg2) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

@Override
public void onLocationChanged(Location location) {
//如果位置发生变化,重新显示
showLocation(location);
}
};

注意:别忘了加上权限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>  
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>