转载请注明地址http://blog.csdn.net/sun6223508/archive/2011/06/21/6559384.aspx
List<Address> addList = null; Geocoder ge = new Geocoder(activity); try { addList = ge.getFromLocation(经度, 纬度,1); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
在android2.1上面这段代码可以通过经纬度取得设备(或者说用户)所在的具体位置,而且很快。
但是在android2.2上面这段代码每次执行都是报IO异常的,通过经纬度得不到具体位置。这是因为上面这段代码在android2.2是一个BUG。
解决办法就是在异常处理的时候加上一个方法getaddressLocation(double lat, double lon, int maxResults) ;异常代码如下。
List<Address> addList = null; Geocoder ge = new Geocoder(activity); try { addList = ge.getFromLocation(经度, 纬度,1); } catch (IOException e) { // TODO Auto-generated catch block if("sdk".equals( Build.PRODUCT )) { Log.d(TAG, "Geocoder doesn't work under emulation."); addList= ReverseGeocode.getaddressLocation(location.getLatitude(), location.getLongitude(), 3); } else{ e.printStackTrace(); } }
getaddressLocation(double lat, double lon, int maxResults) 代码如下
public static List<Address> getaddressLocation(double lat, double lon, int maxResults) { String url = "http://maps.google.com/maps/geo?q=" + lat + "," + lon + "&output=json&sensor=false"; String response = ""; List<Address> results = new ArrayList<Address>(); HttpClient client = new DefaultHttpClient(); try { HttpResponse hr = client.execute(new HttpGet(url)); HttpEntity entity = hr.getEntity(); BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); String buff = null; while ((buff = br.readLine()) != null) response += buff; } catch (IOException e) { e.printStackTrace(); } JSONArray responseArray = null; try { JSONObject jsonObject = new JSONObject(response); responseArray = jsonObject.getJSONArray("Placemark"); } catch (JSONException e) { return results; } for(int i = 0; i < responseArray.length() && i < maxResults-1; i++) { Address addy = new Address(Locale.getDefault()); try { JSONObject jsl = responseArray.getJSONObject(i); String addressLine = jsl.getString("address"); if(addressLine.contains(",")) addressLine = addressLine.split(",")[0]; addy.setAddressLine(0, addressLine); jsl = jsl.getJSONObject("AddressDetails").getJSONObject("Country"); addy.setCountryName(jsl.getString("CountryName")); addy.setCountryCode(jsl.getString("CountryNameCode")); jsl = jsl.getJSONObject("AdministrativeArea"); addy.setAdminArea(jsl.getString("AdministrativeAreaName")); jsl = jsl.getJSONObject("Locality"); addy.setLocality(jsl.getString("LocalityName")); addy.setThoroughfare(jsl.getJSONObject("Thoroughfare").getString("ThoroughfareName")); } catch (JSONException e) { e.printStackTrace(); continue; } results.add(addy); } return results; }