根据地名查询经纬度

public class GetCoordinateUtil {


    public static void main(String[] args) {
        try {
            String[] coordinate = new GetCoordinateUtil().getCoordinate("天安门");
            System.out.println(coordinate[0]+"  "+coordinate[1]);//0:经度 1:纬度
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> map = getURLContent("天安门");
        System.out.println("lng=" + map.get("lng") + ",lat=" + map.get("lat"));
    }


    /**
     * 根据城市名称查询所在经纬度  百度地图
     * @return
     * @throws IOException
     */
    public String[] getCoordinate(String addr) throws IOException {
        String lng = null;//经度
        String lat = null;//纬度
        String address = null;
        try {
            address = java.net.URLEncoder.encode(addr, "UTF-8");
        }catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String key = "自己的KEY"; //这是我的(改过你用不了的) NcMnc57RX48Mjps4fP4ZEW5GVHmCCmeg
        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};
    }

    /***
     *
     * @descibe 根据位置获取经纬度信息  腾讯地图
     */
    public static Map<String, Object> getURLContent(String address) {
        //这里需要使用你的key值
        String urlStr = "https://apis.map.qq.com/ws/geocoder/v1/?address=" + address + "&key=你的KEY";//这是我的(改过你用不了的)CRMBZ-P3DHF-MUVJJ-N25J6-6LL6F-JRBMV
        
        //请求的url
        URL url = null;
        //请求的输入流
        BufferedReader in = null;
        //输入流的缓冲
        StringBuffer sb = new StringBuffer();
        try {
            url = new URL(urlStr);
            in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
            String str = null;
            //一行一行进行读入
            while ((str = in.readLine()) != null) {
                sb.append(str);
            }
        } catch (Exception ex) {

        } finally {
            try {
                if (in != null) {
                    in.close(); //关闭流
                }
            } catch (IOException ex) {

            }
        }
        String result = sb.toString();
        String r = JSONObject.parseObject(result).getString("result");
        String location = JSONObject.parseObject(r).getString("location");
        String lng = JSONObject.parseObject(location).getString("lng");
        String lat = JSONObject.parseObject(location).getString("lat");
        Map<String, Object> map = new HashMap<>();
        map.put("lng", lng);
        map.put("lat", lat);
        return map;
    }
}
个人感觉 腾讯不如百度 查询精准,
拿 “天安门” 举例,百度能搜到,腾讯搜不到
另外,百度地图的经纬度和腾讯地图的经纬度 数据是反的,具体位置也有些许差别
例:查询“天津市”
百度 117.208093,39.091103
腾讯 117.30983,39.71755
需要把腾讯的反过来 39.71755,117.30983
### 使用高德地图API根据地查询经纬度的方法 为了通过高德地图API根据地查询经纬度,可以按照如下方法操作: #### 准备工作 确保已注册并获得高德开放平台的开发者账号以及相应的API Key。 #### 请求URL构建 请求地址应为 `https://restapi.amap.com/v3/geocode/geo` 。此接口用于地理编码服务,即将结构化地址描述转换成坐标。参数设置方面,需提供必要的关键字(即待查询的地)、输出格式(通常为JSON),以及申请的应用程序密钥(API key)[^2]。 #### 参数说明 - **address**: 需要进行解析的具体位置称。 - **key**: 用户自己的应用所对应的API访问Key。 - **output**: 输出数据格式,默认为XML;推荐使用JSON以便于处理返回的数据。 #### Python代码实现示例 下面是一个简单的Python脚本例子来展示如何调用该API获取特定地点的经纬度信息: ```python import requests def get_location(address, api_key): url = 'https://restapi.amap.com/v3/geocode/geo' params = { 'address': address, 'key': api_key, 'output': 'json' # 设置输出格式为 JSON } try: response = requests.get(url, params=params).json() if response['status'] != '1': raise Exception('Request failed') geocodes = response.get('geocodes', []) location_data = None if geocodes: first_geocode = geocodes[0] formatted_address = first_geocode.get('formatted_address') country = first_geocode.get('country') province = first_geocode.get('province') city = first_geocode.get('city') district = first_geocode.get('district') location_str = first_geocode.get('location') # 获取经度和纬度字符串形式 longitude, latitude = map(float, location_str.split(',')) # 分割并转浮点数 location_data = { 'formatted_address': formatted_address, 'country': country, 'province': province, 'city': city, 'district': district, 'longitude': longitude, 'latitude': latitude } return location_data except Exception as e: print(f"Error occurred while fetching data from AMap API: {e}") return None if __name__ == '__main__': ADDRESS_TO_SEARCH = "上海市静安区" YOUR_API_KEY = "<Your_Amap_API_Key_Here>" # 替换成自己有效的API KEY result = get_location(ADDRESS_TO_SEARCH, YOUR_API_KEY) if result is not None: print(result) ``` 上述代码定义了一个为`get_location()` 的函数,它接受两个参数:一个是目标地理位置的字 (`address`) ,另一个则是用户的API密钥(`api_key`). 此外,在主程序部分设置了具体的测试案例——尝试检索“上海市静安区”的地理坐标,并打印出来.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小可乐-我一直在

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值