在我的当前安卓应用中,我想通过输入城市名、街道名或邮编来获取地理坐标。我该如何实现?
最好的问候
通过网络获取地理坐标
private static JSONObject getLocationInfo(String address)
{
StringBuilder stringBuilder = new StringBuilder();
try {
address = address.replaceAll(" ","%20");
HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
Log.i("getLocationInfo ClientProtocolException", e.toString());
} catch (IOException e) {
Log.i("getLocationInfo IOException", e.toString());
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.i("getLocationInfo JSONException", e.toString());
}
return jsonObject;
}
private static boolean getLatLong(JSONObject jsonObject)
{
try {
longitute = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
Log.i("Log1", longitute1+"");
latitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
Log.i("lat1", latitude1+"");
} catch (JSONException e) {
longitute=0;
latitude = 0;
Log.i("getLatLong", e.toString());
return false;
}
return true;
}
searchedAddress --> 可以是(城市名称/地址/邮编)。
public boolean getLatitudeAndLongitudeFromGoogleMapForAddress(String searchedAddress){
Geocoder coder = new Geocoder(IPlant.iPlantActivity);
List<Address> address;
try
{
address = coder.getFromLocationName(searchedAddress,5);
if (address == null) {
Log.d(TAG, "############Address not correct #########");
}
Address location = address.get(0);
Log.d(TAG, "Address Latitude : "+ location.getLatitude();+ "Address Longitude : "+ location.getLongitude());
return true;
}
catch(Exception e)
{
Log.d(TAG, "MY_ERROR : ############Address Not Found");
return false;
}
}
getFromLocationName
,它会做你想要的事情。你也可以反过来使用这个类,也就是说,输入(纬度、经度),然后获取那里的地址。