根据中文地址查询经纬度(百度地图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();
    }
}

    原文作者:White-Legend
    原文地址: https://blog.csdn.net/qq_30776829/article/details/124497908
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞