百度地圖獲取位置經緯度

import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by xx on 2018/4/9.
 * Description
 */
public class BaiduMap {
    final static String ak="xxxxxxxxxxxxxx";
    final static String getLngLatUrl = "http://api.map.baidu.com/geocoder/v2/?address=%s&output=json&ak=%s";

    /**
     * @param addr
     * 查詢的地址
     * @return lng lat
     * @throws IOException
     */

    public static Object[] getCoordinate(String addr){
        String lng = null;
        String lat = null;
        String address = null;
        Object[] object=new Object[]{0.0,0.0};
        try {
            address = java.net.URLEncoder.encode(addr, "UTF-8");
        }catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String url = String .format(getLngLatUrl, address, ak);
        String json = loadJSON(url);
        if (StringUtils.isEmpty(json)) {
            return object;
        }
        int len = json.length();
        // 如果不是合法的json格式
        if (json.indexOf("{") != 0 || json.lastIndexOf("}") != len - 1) {
            return object;
        }
        JSONObject obj = JSONObject.fromObject(json);
        if (obj.get("status").toString().equals("0")) {
            JSONObject objects = obj.getJSONObject("result");
            JSONObject routes = objects.getJSONObject("location");
            lng=routes.getString("lng");
            lat=routes.getString("lat");
        }
        return new Object[]{lng,lat};
    }

    public static String loadJSON(String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL urlObj = new URL(url);
            URLConnection uc = urlObj.openConnection();
            BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            String inputLine = null;
            while ((inputLine = br.readLine()) != null) {
                json.append(inputLine);
            }
            br.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        return json.toString();
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章