百度地图API还是很有用的,尤其是在国内环境下
需要注意的是字符编码问题
package com.cldknw.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import com.cldknw.place.PlaceInfo;
import com.google.gson.Gson;
public class MapHelper {
private static HttpClient client = new HttpClient();
private static final String prefix = "http://api.map.baidu.com/geocoder?location=";
private static final String key = "ba376eda799ae16ffb8492c9b44af443";
private static Gson gs = new Gson();
public static PlaceInfo getPlaceInfoByLatAndLng(double lat,double lng) throws HttpException, IOException{
String uri = prefix+lat+","+lng+"&output=json&key="+key;
GetMethod get = new GetMethod(uri);
get.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
// client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
int status = client.executeMethod(get);
if(status != 200) return null;
StringBuffer jsonReturn = new StringBuffer();
// BufferedReader br = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(),"UTF-8"));
BufferedReader br = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream()));
String s = "";
while((s = br.readLine())!=null){
jsonReturn.append(s);
}
System.out.println(jsonReturn.toString());
return gs.fromJson(jsonReturn.toString(), PlaceInfo.class);
}
public static void main(String args[]){
try {
PlaceInfo pi = getPlaceInfoByLatAndLng(39.983424,116.322987);
System.out.println(pi.getResult().getFormatted_address());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
本文介绍了如何在国内环境中有效利用百度地图API,特别强调了在使用过程中字符编码问题的重要性。

1670

被折叠的 条评论
为什么被折叠?



