您的位置:首页 > 其它

调用百度地图API实例

2013-03-01 10:54 134 查看
百度地图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();
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: