百度地图操作utils

/**
 * 百度地图操作工具类
 */
public class BaiduMapUtils {
    public static void main(String[] args) {
        String origin = getCoordinate("");
        String destination = getCoordinate("组");
        Double distance = getDistance(origin, destination);
        System.out.println("订单距离:"+distance + "米");
        Integer time = getTime(origin, destination);
        System.out.println("线路耗时"+time+"秒");
    }

    private static String AK = "百度地图开放平台AK";

    /**
     * 调用百度地图地理编码服务接口,根据地址获取坐标(经度、纬度)
     * @param address
     * @return
     */
    public static String getCoordinate(String address){
        String httpUrl = "http://api.map.baidu.com/geocoding/v3/?address=" + address + "&output=json&ak=" + AK;
        String json = loadJSON(httpUrl);
        Map map = JSON.parseObject(json, Map.class);

        String status = map.get("status").toString();
        if(status.equals("0")){
            //返回结果成功,能够正常解析地址信息
            Map result = (Map) map.get("result");
            Map location = (Map) result.get("location");
            String lng = location.get("lng").toString();
            String lat = location.get("lat").toString();

            DecimalFormat df = new DecimalFormat("#.######");
            String lngStr = df.format(Double.parseDouble(lng));
            String latStr = df.format(Double.parseDouble(lat));
            String r = latStr + "," + lngStr;
            return r;
        }

        return null;
    }

    /**
     * 调用百度地图驾车路线规划服务接口,根据寄件人地址和收件人地址坐标计算订单距离
     * @param origin
     * @param destination
     * @return
     */
    public static Double getDistance(String origin,String destination){
        String httpUrl = "http://api.map.baidu.com/directionlite/v1/driving?origin="
                +origin+"&destination="
                +destination+"&ak=" + AK;

        String json = loadJSON(httpUrl);

        Map map = JSON.parseObject(json, Map.class);
        if ("0".equals(map.getOrDefault("status", "500").toString())) {
            Map childMap = (Map) map.get("result");
            JSONArray jsonArray = (JSONArray) childMap.get("routes");
            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
            double distance = Double.parseDouble(jsonObject.get("distance") == null ? "0" : jsonObject.get("distance").toString());
            return distance;
        }

        return null;
    }

    /**
     * 调用百度地图驾车路线规划服务接口,根据寄件人地址和收件人地址坐标计算订单距离
     * @param origin
     * @param destination
     * @return
     */
    public static Integer getTime(String origin,String destination){
        String httpUrl = "http://api.map.baidu.com/directionlite/v1/driving?origin="
                +origin+"&destination="
                +destination+"&ak=" + AK;

        String json = loadJSON(httpUrl);

        Map map = JSON.parseObject(json, Map.class);
        if ("0".equals(map.getOrDefault("status", "500").toString())) {
            Map childMap = (Map) map.get("result");
            JSONArray jsonArray = (JSONArray) childMap.get("routes");
            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
            int time = Integer.parseInt(jsonObject.get("duration") == null ? "0" : jsonObject.get("duration").toString());
            return time;
        }

        return null;
    }

    /**
     * 调用服务接口,返回百度地图服务端的结果
     * @param httpUrl
     * @return
     */
    public static String loadJSON(String httpUrl){
        StringBuilder json = new StringBuilder();
        try {
            URL url = new URL(httpUrl);
            URLConnection urlConnection = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        System.out.println(json.toString());
        return json.toString();
    }



  // 调用百度地图API根据地址,获取坐标
    public static String getCoordinate(String address) {
        if (address != null && !"".equals(address)) {
            address = address.replaceAll("\\s*", "").replace("#", "栋");
            String url = "http://api.map.baidu.com/geocoding/v3/?output=json&ak=" + AK + "&callback=showLocation&address=" + address;
//            String url = "http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak=" + AK;
            String json = loadJSON(url);
            json = StringUtils.substringBetween(json, "showLocation(", ")");
            if (json != null && !"".equals(json)) {
                Map map = JSON.parseObject(json, Map.class);
                if ("0".equals(map.getOrDefault("status", "500").toString())) {
                    Map childMap = (Map) map.get("result");
                    Map posMap = (Map) childMap.get("location");
                    double lng = Double.parseDouble(posMap.getOrDefault("lng", "0").toString()); // 经度
                    double lat = Double.parseDouble(posMap.getOrDefault("lat", "0").toString()); // 纬度
                    DecimalFormat df = new DecimalFormat("#.######");
                    String lngStr = df.format(lng);
                    String latStr = df.format(lat);
                    return lngStr + "," + latStr;
                }
            }
        }
        return null;
    }


    public static Integer getTime(String origin, String destination) {
        String[] originArray = origin.split(",");
        String[] destinationArray = destination.split(",");
        origin = originArray[1] + "," + originArray[0];
        destination = destinationArray[1] + "," + destinationArray[0];
        String url = "http://api.map.baidu.com/directionlite/v1/driving?origin=" + origin + "&destination=" + destination + "&ak=" + AK;
        String json = loadJSON(url);
        System.out.println("json-->" + json);
        if (json != null && !"".equals(json)) {
            Map map = JSON.parseObject(json, Map.class);
            if ("0".equals(map.getOrDefault("status", "500").toString())) {
                Map childMap = (Map) map.get("result");
                JSONArray jsonArray = (JSONArray) childMap.get("routes");
                JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                Map posMap = (Map) jsonObject.get("routes");
                int duration = Integer.parseInt(jsonObject.get("duration") == null ? "0" : jsonObject.get("duration").toString());
                return duration;
            }
        }

        return null;
    }

    public static Double getDistance(String origin, String destination) {
        String[] originArray = origin.split(",");
        String[] destinationArray = destination.split(",");
        origin = originArray[1] + "," + originArray[0];
        destination = destinationArray[1] + "," + destinationArray[0];
        String url = "http://api.map.baidu.com/directionlite/v1/driving?origin=" + origin + "&destination=" + destination + "&ak=" + AK;
        String json = loadJSON(url);
        System.out.println("json-->" + json);
        if (json != null && !"".equals(json)) {
            Map map = JSON.parseObject(json, Map.class);
            if ("0".equals(map.getOrDefault("status", "500").toString())) {
                Map childMap = (Map) map.get("result");
                JSONArray jsonArray = (JSONArray) childMap.get("routes");
                JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                Map posMap = (Map) jsonObject.get("routes");
                double distance = Double.parseDouble(jsonObject.get("distance") == null ? "0" : jsonObject.get("distance").toString());
                return distance;
            }
        }

        return null;
    }

    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(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        return json.toString();
    }

    /**
     *
     * @param location
     * @return map
     * formatted_address:结构化地址信息
     *       "country":"国家",
     *             "country_code":国家编码,
     *             "country_code_iso":"国家英文缩写(三位)",
     *             "country_code_iso2":"国家英文缩写(两位)",
     *             "province":"省名",
     *             "city":"城市名",
     *             "city_level":城市所在级别(仅国外有参考意义。国外行政区划与中国有差异,城市对应的层级不一定为『city』。country、province、city、district、town分别对应0-4级,若city_level=3,则district层级为该国家的city层级),
     *             "district":"区县名",
     *             "town":"乡镇名",
     *             "town_code":"乡镇id",
     *             "adcode":"行政区划代码",
     *             "street":"街道名(行政区划中的街道层级)",
     *             "street_number":"街道门牌号",
     *             "direction":"和当前坐标点的方向",
     *             "distance":"离坐标点距离"
     */
    public static Map getLocationByPosition(String location) {
        String[] originArray = location.split(",");
        location = originArray[1] + "," + originArray[0];
        String url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=" + AK + "&output=json&coordtype=wgs84ll&location=" + location;
//        String url = "http://api.map.baidu.com/directionlite/v1/driving?origin=" + origin + "&destination=" + destination + "&ak=" + AK;
        String json = loadJSON(url);
        System.out.println("json-->" + json);
        if (json != null && !"".equals(json)) {
            Map map = JSON.parseObject(json, Map.class);
            if ("0".equals(map.getOrDefault("status", "500").toString())) {
                Map childMap = (Map) map.get("result");
                Map areaMap = (Map) childMap.get("addressComponent");
                areaMap.put("formatted_address", childMap.getOrDefault("formatted_address", "").toString());
                return areaMap;
            }
        }

        return null;
    }

    /**
     * 判断点是否在区域内
     *
     * @param polygon   区域经纬度集合
     * @param longitude 经度
     * @param latitude  纬度
     * @return
     */
    public static boolean isInScope(List<Map> polygon, double longitude, double latitude) {
        Path2D.Double generalPath = new Path2D.Double();

        //获取第一个起点经纬度的坐标
        Map first = polygon.get(0);

        //通过移动到以double精度指定的指定坐标,把第一个起点添加到路径中
        generalPath.moveTo(Double.parseDouble(first.getOrDefault("lng", "").toString()), Double.parseDouble(first.getOrDefault("lat", "").toString()));

        //把集合中的第一个点删除防止重复添加
        polygon.remove(0);

        //循环集合里剩下的所有经纬度坐标
        for (Map d : polygon) {
            //通过从当前坐标绘制直线到以double精度指定的新指定坐标,将路径添加到路径。
            //从第一个点开始,不断往后绘制经纬度点
            generalPath.lineTo(Double.parseDouble(d.getOrDefault("lng", "").toString()), Double.parseDouble(d.getOrDefault("lat", "").toString()));

        }

        // 最后要多边形进行封闭,起点及终点
        generalPath.lineTo(Double.parseDouble(first.getOrDefault("lng", "").toString()), Double.parseDouble(first.getOrDefault("lat", "").toString()));

        //将直线绘制回最后一个 moveTo的坐标来关闭当前子路径。
        generalPath.closePath();

        //true如果指定的坐标在Shape边界内; 否则为false 。
        return generalPath.contains(longitude, latitude);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个用于创建独立的、基于Spring的应用程序的框架。它简化了Spring应用程序的配置和部署过程,提供了一种快速开发的方式。 百度地图定位是百度地图提供的一项定位服务,可以通过百度地图API获取用户的地理位置信息。在Spring Boot中使用百度地图定位可以通过以下步骤实现: 1. 引入百度地图API的依赖:在Spring Boot项目的pom.xml文件中添加百度地图API的依赖,例如: ```xml <dependency> <groupId>com.baidu</groupId> <artifactId>baidu-map-api</artifactId> <version>3.0.0</version> </dependency> ``` 2. 配置百度地图API的密钥:在Spring Boot项目的配置文件(如application.properties或application.yml)中配置百度地图API的密钥,例如: ```properties baidu.map.api.key=your_api_key ``` 3. 编写代码获取定位信息:在Spring Boot项目中编写代码,使用百度地图API获取用户的地理位置信息,例如: ```java import com.baidu.mapapi.model.LatLng; import com.baidu.mapapi.utils.CoordinateConverter; import com.baidu.mapapi.utils.CoordinateConverter.CoordType; public class LocationService { public String getLocation(double latitude, double longitude) { // 将经纬度转换为百度坐标系 CoordinateConverter converter = new CoordinateConverter(); converter.from(CoordType.COMMON); converter.coord(new LatLng(latitude, longitude)); LatLng baiduLatLng = converter.convert(); // 调用百度地图API获取地理位置信息 // ... return locationInfo; } } ``` 以上是使用Spring Boot和百度地图定位的基本步骤,你可以根据具体需求进行进一步的开发和调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值