Android獲取當前城市名稱
阿新 • • 發佈:2019-02-04
不需要匯入百度地圖的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"/>