调用百度地图API实例

本文介绍了如何在国内环境中有效利用百度地图API,特别强调了在使用过程中字符编码问题的重要性。

百度地图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();
        } 
    }
}




评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值