您的位置:首页 > 移动开发 > Android开发

Android2.2调用Google Map api进行位置搜索

2012-05-15 17:23 513 查看
一个让我困惑了很久的问题,最后终于在CSDN论坛中经过大家的帮助,将此问题完美解决。

具体问题可参考:Google Maps API 返回英文的问题

好了,不多说,上代码了:

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

/**
* 提供对地图操作的相关方法
* <P>
* 例如对地址的解析和反向解析,自动定位当前位置,搜索指定位置等操作
* <HR>
* 作者:孙博
* <P>
* 时间:2012-4-27 下午1:10:35
* <P>
* 电子邮件:sunb@hwttnet.com
* <P>
* QQ:497733379
*/
public class MapUtility
{
/**
* 有关该地址的来源与详细说明,请参阅:
*
* <PRE>
* <A href=
* 'https://developers.google.com/maps/documentation/geocoding/?hl=zh-CN'>Google Geocoding API</A>
* </RRE>
*/
private static final String MAPADDRESSURL = "https://maps.googleapis.com/maps/api/geocode/json?address=";

/**
* 根据输入的人类可识别语言文字进行精确的位置搜索
* <P>
* 可将手动输入的<A href=
* 'https://spreadsheets.google.com/pub?key=p9pdwsai2hDMsLkXsoM05KQ&gid=1'>区域语言</A>
* 正 确 解 析 成 经 纬 度 坐 标 值
* <P>
* 最终将远端服务器获取到的数据以<CODE>json</CODE>形式返回
*
* @param address
*            一条正确的地理位置信息,人类可识别的语言文字
* @return 返回从远端服务器获取到的所有数据
* @throws JSONException
*             如果从远端服务器获取数据失败,抛出该异常
* @throws UnsupportedEncodingException
*/
public static JSONObject getLocationInfo(String address)
throws JSONException, UnsupportedEncodingException
{
HttpGet mHttpGet = new HttpGet(MAPADDRESSURL
+ address.replaceAll(" ", "%20") + "&sensor=false&language=zh-CN");
HttpClient mHttpClient = new DefaultHttpClient();
StringBuilder stringBuilder = new StringBuilder();
try
{
HttpResponse response = mHttpClient.execute(mHttpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
String jsonResult = EntityUtils.toString(response.getEntity(),
"UTF-8");
stringBuilder.append(jsonResult);
}
} catch (ClientProtocolException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
mHttpClient.getConnectionManager().shutdown();
return new JSONObject(stringBuilder.toString());
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: