调用百度Api根据省市区名称获取对应经纬度

好久没写博客了,最近刚好要做这样一个统计分析图,需要用到根据省市区的经纬度,下面代码是调的百度接口,缺点就是好像不能批量获取经纬度,本篇原地址

package com.ziding.product.cooperation;

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;
import java.net.URLEncoder;

public class GetCoordinate {

        public static void main(String[] args) {
            try {
                String[] coordinate = new GetCoordinate().getCoordinate("浙江省嘉兴市平湖市");
                System.out.println(coordinate[0]+"  "+coordinate[1]);//0:经度 1:纬度
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        /**
         * 根据城市名称查询所在经纬度
         * @param addr 要查询的地址
         * 查询的地址
         * @return
         * @throws IOException
         */
        public String[] getCoordinate(String addr) throws IOException {
            String lng = null;//经度
            String lat = null;//纬度
            String address = null;
            try {
                address = URLEncoder.encode(addr, "UTF-8");
            }catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            String key = "tG9KaH7vDut0Ia9Dcu51ujQmkSjM4q54";
            String url = String .format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", address, key);
            URL myURL = null;
            URLConnection httpsConn = null;
            try {
                myURL = new URL(url);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            InputStreamReader insr = null;
            BufferedReader br = null;
            try {
                httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
                if (httpsConn != null) {
                    insr = new InputStreamReader( httpsConn.getInputStream(), "UTF-8");
                    br = new BufferedReader(insr);
                    String data = null;
                    int count = 1;
                    while((data= br.readLine())!=null){
                        if(count==5){
                            lng = (String)data.subSequence(data.indexOf(":")+1, data.indexOf(","));//经度
                            count++;
                        }else if(count==6){
                            lat = data.substring(data.indexOf(":")+1);//纬度
                            count++;
                        }else{
                            count++;
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(insr!=null){
                    insr.close();
                }
                if(br!=null){
                    br.close();
                }
            }
            return new String[]{lng,lat};
        }
}

 

你可能感兴趣的:(开发工具)