80,351
社区成员
发帖
与我相关
我的任务
分享
private static JSONObject geocodeAddr(double lat, double lng)
{
String urlString = "http://ditu.google.com/maps/geo?q=+" + lat + ","
+ lng + "&output=json&oe=utf8&hl=zh-CN&sensor=false";
//String urlString = "http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&language=zh_CN&sensor=false";
StringBuilder sTotalString = new StringBuilder();
try
{
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
InputStream urlStream = httpConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlStream));
String sCurrentLine = "";
while ((sCurrentLine = bufferedReader.readLine()) != null)
{
sTotalString.append(sCurrentLine);
}
bufferedReader.close();
httpConnection.disconnect(); // 关闭http连接
}
catch (Exception e1)
{
e1.printStackTrace();
}
JSONObject jsonObject = new JSONObject();
try
{
jsonObject = new JSONObject(sTotalString.toString());
}
catch (JSONException e)
{
e.printStackTrace();
}
return jsonObject;
}
//获得手机的具体位置。
private String getAddressByLatLng()
{
String address = null;
double latitude = 0.0;
double longitude = 0.0;
// 获取位置管理服务
LocationManager locationManager;
String serviceName = Context.LOCATION_SERVICE;
locationManager = (LocationManager)this.getSystemService(serviceName); // 查找到服务信息
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
String provider = locationManager.getBestProvider(criteria, true); // 获取GPS信息
Location location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
latitude = location.getLatitude();
longitude= location.getLongitude();
JSONObject jsonObject = geocodeAddr(latitude, longitude);
try
{
JSONArray placemarks = jsonObject.getJSONArray("Placemark");
JSONObject place = placemarks.getJSONObject(0);
address = place.getString("address");
}
catch (Exception e)
{
e.printStackTrace();
}
return address;
}