根据中文地址查询经纬度(百度地图api)

package com.fc.test.controller.gen;

import com.fc.test.model.custom.vo.LngAndLat;
import net.sf.json.JSONObject;

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

public class SupLocationController {

    public static void main(String[]args){
        getBaiduLngAndLat("四川川省成都市武侯区领事馆路7号");
    }

    /**
     * 百度地图中文地址查询经纬度
     * @param address
     * @return
     */
    public static LngAndLat getBaiduLngAndLat(String address) {
        LngAndLat lngAndLat = new LngAndLat();
        String url = "http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak=您的AK";
        String json = loadJSON(url);
        JSONObject obj = JSONObject.fromObject(json);
        if (obj.get("status").toString().equals("0")) {
            double lng = obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
            double lat = obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
            lngAndLat.setLat(lat);
            lngAndLat.setLng(lng);
        } else {
        }
        return lngAndLat;
    }

    public static String loadJSON(String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                yc.getInputStream()));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (IOException ignored) {
        }
        return json.toString();
    }
}

你可能感兴趣的:(idea,java,java)