调用腾讯地图 输入地址获取经纬度

申请腾讯地图的key

腾讯位置服务
申请顺序
在这里插入图片描述
在这里插入图片描述
以上步骤中需要你的微信扫码,然后绑定你的电话和邮箱,根据提示即可,
进入申请密钥页面后
创建应用
在这里插入图片描述

输入名称和类型(具体不太了解,个人感觉就是便于管理的,也可以随便填)

创建后去添加key
在这里插入图片描述
在这里插入图片描述

注意webserviceAPI这儿,我最开始选择的签名校验,但无法通过(根据官方的写签名还是无法),于是换成了域名白名单,并且因为时个‘栗子’,所以域名填写那儿没有就不填

都完成后就可以开始写代码了

具体代码(两种方式)
使用fastjson(懒得构造json映射的对象)
package com;

import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @描述:
 * @author: DC
 * @create: 2021-12-09 13:57
 */

public class Test {
    /**
     * @param address 需要做url编码
     * @return
     */
    public static Map<String, Object> getURLContent(String address) throws UnsupportedEncodingException {
        String addressEncode = URLEncoder.encode(address, "utf-8");
        //这里需要使用你的key值
        String urlStr = "https://apis.map.qq.com/ws/geocoder/v1/?address=" + addressEncode + "&key=你自己的key";
        //请求的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.fromObject(result).getString("result");
        String location = JSONObject.fromObject(r).getString("location");
        String lng = JSONObject.fromObject(location).getString("lng");
        String lat = JSONObject.fromObject(location).getString("lat");
        Map<String, Object> map = new HashMap<>();
        map.put("lng", lng);
        map.put("lat", lat);
        return map;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        Map<String, Object> map = getURLContent("具体地址信息");
        System.out.println("lng=" + map.get("lng") + ",lat=" + map.get("lat"));
    }

}

使用jackson(懒得构造对应的json映射对象)
public class GetLocationUtils {
    /**
     * @param addressDetail 详细地址
     * @param cityAddress   大地址
     * @return
     * @throws IOException
     */
    public static Map<String, Object> getURLContent(String addressDetail, String cityAddress) throws IOException {
        Map<String, Object> map = new HashMap<>();
        JsonRootBean addressDetailResult = getResult(addressDetail);
        if (addressDetailResult.getStatus() == 0) {
            map.put("status", addressDetailResult.getStatus());
            map.put("lng", addressDetailResult.getResult().getLocation().getLng());
            map.put("lat", addressDetailResult.getResult().getLocation().getLat());
            return map;
        } else {
            JsonRootBean cityAddressResult = getResult(cityAddress);
            if (cityAddressResult.getStatus() == 0) {
                map.put("status", cityAddressResult.getStatus());
                map.put("lng", cityAddressResult.getResult().getLocation().getLng());
                map.put("lat", cityAddressResult.getResult().getLocation().getLat());
                return map;
            }
            map.put("status", cityAddressResult.getStatus());
            return map;
        }
    }
    private static JsonRootBean getResult(String address) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String addressEncode = URLEncoder.encode(address, "utf-8");
        //这里需要使用你的key值
        String urlStr = "https://apis.map.qq.com/ws/geocoder/v1/?address=" + addressEncode + "&key=你的key";
        //请求的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) {
            ex.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close(); //关闭流
                }
            } catch (IOException ex) {

            }
        }
        JsonRootBean jsonRootBean = objectMapper.readValue(sb.toString(), JsonRootBean.class);
        return jsonRootBean;
    }

}

使用jackson(需要构造对应的json映射对象)
public class GetLocationUtils {
    /**
     * @param addressDetail 详细地址
     * @param cityAddress   大地址
     * @return
     * @throws IOException
     */
    public static Map<String, Object> getURLContent(String addressDetail, String cityAddress) throws IOException {
        Map<String, Object> map = new HashMap<>();
        JsonRootBean addressDetailResult = getResult1(addressDetail);
        /** 
         * 0 是查询成功,但不建议使用这样的魔法值,最好使用枚举值替代
         * 注意两个参数 详细地址、大地址 因为详细地址可能查询不到,所以使用大地址(省市县) 总之要保证无论是否查询成功,都需要有返回值
		 */
        if (addressDetailResult.getStatus() == 0) {
            map.put("status", addressDetailResult.getStatus());
            map.put("lng", addressDetailResult.getResult().getLocation().getLng());
            map.put("lat", addressDetailResult.getResult().getLocation().getLat());
            return map;
        } else {
            JsonRootBean cityAddressResult = getResult1(cityAddress);
            if (cityAddressResult.getStatus() == 0) {
                map.put("status", cityAddressResult.getStatus());
                map.put("lng", cityAddressResult.getResult().getLocation().getLng());
                map.put("lat", cityAddressResult.getResult().getLocation().getLat());
                return map;
            }
            map.put("status", cityAddressResult.getStatus());
            return map;
        }
    }

    /**
     * 使用api调用腾讯地图接口获取返回值
     * @param address
     * @return
     * @throws IOException
     */
    private static JsonRootBean getResult1(String address) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String addressEncode = URLEncoder.encode(address, "utf-8");
        //key需要去腾讯位置服务申请
        String urlStr = "https://apis.map.qq.com/ws/geocoder/v1/?address=" + addressEncode + "&key=你的key";
        //请求的url
        URL url = new URL(urlStr);
        JsonRootBean jsonRootBean = objectMapper.readValue(url, JsonRootBean.class);
        return jsonRootBean;
    }
使用jackson 的映射对象构造
public class AddressComponents {

    private String province;
    private String city;
    private String district;
    private String street;
    private String street_number;
    public void setProvince(String province) {
         this.province = province;
     }
     public String getProvince() {
         return province;
     }

    public void setCity(String city) {
         this.city = city;
     }
     public String getCity() {
         return city;
     }

    public void setDistrict(String district) {
         this.district = district;
     }
     public String getDistrict() {
         return district;
     }

    public void setStreet(String street) {
         this.street = street;
     }
     public String getStreet() {
         return street;
     }

    public void setStreet_number(String street_number) {
         this.street_number = street_number;
     }
     public String getStreet_number() {
         return street_number;
     }

}

public class AdInfo {

    private String adcode;
    public void setAdcode(String adcode) {
         this.adcode = adcode;
     }
     public String getAdcode() {
         return adcode;
     }

}

public class JsonRootBean {

    private int status;
    private String message;
    private Result result;
    public void setStatus(int status) {
         this.status = status;
     }
     public int getStatus() {
         return status;
     }

    public void setMessage(String message) {
         this.message = message;
     }
     public String getMessage() {
         return message;
     }

    public void setResult(Result result) {
         this.result = result;
     }
     public Result getResult() {
         return result;
     }

}

public class Location implements Serializable {

    private double lng;
    private double lat;
    public void setLng(double lng) {
         this.lng = lng;
     }
     public double getLng() {
         return lng;
     }

    public void setLat(double lat) {
         this.lat = lat;
     }
     public double getLat() {
         return lat;
     }

}


public class Result {

    private String title;
    private Location location;
    private AdInfo ad_info;
    private AddressComponents address_components;
    private double similarity;
    private int deviation;
    private int reliability;
    private int level;
    public void setTitle(String title) {
         this.title = title;
     }
     public String getTitle() {
         return title;
     }

    public void setLocation(Location location) {
         this.location = location;
     }
     public Location getLocation() {
         return location;
     }

    public void setAd_info(AdInfo ad_info) {
         this.ad_info = ad_info;
     }
     public AdInfo getAd_info() {
         return ad_info;
     }

    public void setAddress_components(AddressComponents address_components) {
         this.address_components = address_components;
     }
     public AddressComponents getAddress_components() {
         return address_components;
     }

    public void setSimilarity(double similarity) {
         this.similarity = similarity;
     }
     public double getSimilarity() {
         return similarity;
     }

    public void setDeviation(int deviation) {
         this.deviation = deviation;
     }
     public int getDeviation() {
         return deviation;
     }

    public void setReliability(int reliability) {
         this.reliability = reliability;
     }
     public int getReliability() {
         return reliability;
     }

    public void setLevel(int level) {
         this.level = level;
     }
     public int getLevel() {
         return level;
     }

}

没有用lombok,想用自己改一下就好
推荐最后一种方式~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值