高德 地理编码

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

import net.sf.json.JSONObject;

public class AddressLngLatExchange {

    private static final String HOST = "http://restapi.amap.com/v3/geocode/geo?";
    private static final String KEY = "7f4ffae4074e8b8e4d147190527a4b72";

    public static void main(String[] args)  {
        AddressLngLatExchange addressLngLatExchange=new AddressLngLatExchange();
        System.out.println(addressLngLatExchange.getLngLat("潍坊市高新区潍柴动力"));
        System.out.println("========================");
        String longitudeAndLatitude = addressLngLatExchange.getLongitudeAndLatitude("潍坊市高新区清平小区");
        System.out.println(longitudeAndLatitude);
    }

    private String getLongitudeAndLatitude(String address) {
        StringBuffer stringBuffer = new StringBuffer();
        try {
            URL url = new URL(HOST+"address="+address+"&output=JSON&key="+KEY);
            URLConnection urlConnection = url.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String json;
            while ((json = bufferedReader.readLine())!= null){
                stringBuffer.append(json);
            }
            bufferedReader.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        String string = stringBuffer.toString();
        JSONObject jsonObject = JSONObject.fromObject(string);
        if (jsonObject.getJSONArray("geocodes").size() > 0){
            String  s = jsonObject.getJSONArray("geocodes").getJSONObject(0).get("location").toString();
            return s;
        }
        return null;
    }
    public String getLngLat(String address) {
        StringBuffer json = new StringBuffer();
        try {
            URL u = new URL("http://restapi.amap.com/v3/geocode/geo?address="+address+"&output=JSON&key=7f4ffae4074e8b8e4d147190527a4b72");
            URLConnection yc = u.openConnection();
            //读取返回的数据
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(),"UTF-8"));
            String inputline = null;
            while((inputline=in.readLine())!=null){
                json.append(inputline);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String jsonStr=json.toString();
        JSONObject jsonObject = JSONObject.fromObject(jsonStr);
        //判断输入的位置点是否存在
        if(jsonObject.getJSONArray("geocodes").size()>0)
            return jsonObject.getJSONArray("geocodes").getJSONObject(0).get("location").toString();
        else
            return null;
    }

}

全部评论

相关推荐

头发暂时没有的KFC总裁:找廉价劳动力罢了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务