最近在做google map 根据地址获取经纬度的时候使用到Geocoder类
- Java 代码复制内容到剪贴板
- /**
- * 将地址转为经纬度
- * @param address
- * @return
- */
- public GeoPoint getGeoPointByAddress(String address) {
- GeoPoint geoPoint = null;
- if (address != "") {
- Geocoder myGeocoder = new Geocoder(RegisterAccountActivity.this);
- List<Address> addressList = null;
- try {
- addressList = myGeocoder.getFromLocationName(address, 1);
- if (!addressList.isEmpty()) {
- Address tempAddress = addressList.get(0);
- double myLatitude = tempAddress.getLatitude() * 1E6;
- double myLongitude = tempAddress.getLongitude() * 1E6;
- geoPoint = new GeoPoint((int) myLatitude, (int) myLongitude);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return geoPoint;
- }
这段代码对2.2和2.3系统居然不起作用,报java.io.IOException: Service not Available的错误,换用2.1系统却可以。
估计这是个bug。于是在网上找到另一种解决方法:
- Java 代码复制内容到剪贴板
- public static JSONObject getLocationInfo(String address) {
- HttpGet httpGet = new HttpGet(
- "http://maps.g...ddress="
- + address + "ka&sensor=false");
- HttpClient client = new DefaultHttpClient();
- HttpResponse response;
- StringBuilder stringBuilder = new StringBuilder();
- try {
- response = client.execute(httpGet);
- HttpEntity entity = response.getEntity();
- InputStream stream = entity.getContent();
- int b;
- while ((b = stream.read()) != -1) {
- stringBuilder.append((char) b);
- }
- } catch (ClientProtocolException e) {
- } catch (IOException e) {
- }
- JSONObject jsonObject = new JSONObject();
- try {
- jsonObject = new JSONObject(stringBuilder.toString());
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return jsonObject;
- }
- public static GeoPoint getGeoPoint(JSONObject jsonObject) {
- Double lon = new Double(0);
- Double lat = new Double(0);
- try {
- lon = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
- .getJSONObject("geometry").getJSONObject("location")
- .getDouble("lng");
- lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
- .getJSONObject("geometry").getJSONObject("location")
- .getDouble("lat");
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));
- }
这样就解决了问题。
本文转自06peng 51CTO博客,原文链接:http://blog.51cto.com/06peng/962513,如需转载请自行联系原作者