百度地图操作utils

本文介绍了一个用于百度地图操作的工具类,包括地址转坐标、驾车路线距离和时间计算的功能。通过API调用获取地理位置信息,并展示如何在Java中实现这些功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 百度地图操作工具类
 */
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);
    }

}
### 如何在 Flutter 中集成百度地图 API #### 安装依赖包 为了能够在 Flutter 项目中使用百度地图,需要安装 `flutter_baidu_mapapi_utils` 和 `flutter_baidu_mapapi_map` 这两个插件。具体版本可以根据需求选择,在此推荐使用稳定版: ```yaml dependencies: flutter_baidu_mapapi_utils: ^3.2.0 [^1] flutter_baidu_mapapi_map: ^2.0.1 [^3] ``` #### 获取 AK (Access Key) 由于国内通常无法访问 Google 提供的服务,因此建议采用百度地图提供的定位服务[^4]。前往百度地图开放平台注册账号并创建应用来获取专属的 Access Key。 #### 配置 Android 平台 对于 Android 应用程序而言,需修改项目的 `build.gradle` 文件以及 `AndroidManifest.xml` 文件以支持百度地图 SDK 的初始化工作。确保已在 `gradle.properties` 添加如下配置项以便于后续操作顺利进行: ```properties android.enableJetifier=true android.useAndroidX=true ``` 接着编辑 `app/build.gradle`, 将以下内容加入到 dependencies 节点下: ```groovy implementation 'com.baidu.lbssdk:BaiduMapSDK_basic:最新版本号' ``` 最后一步是在 `AndroidManifest.xml` 插入必要的权限声明和 meta-data 设置: ```xml <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <!-- 更多必要权限... --> <meta-data android:name="com.baidu.lbsapi.API_KEY" android:value="${BAIDU_API_KEY}"/> <!-- 替换成自己的AK --> ``` #### 初始化 iOS 环境 针对 iOS 开发者来说,则要调整 `ios/Podfile` 来指定所需库文件,并更新 Info.plist 加入隐私说明等信息。例如可以在 Podfile 中添加: ```ruby pod 'BaiduMapKit', '~> 最新版本' ``` 同时别忘了设置正确的 bundle identifier 及其他相关参数。 #### 编写 Dart 代码实现基本功能 完成上述准备工作之后就可以着手编写 Dart 逻辑了。下面给出一段简单的例子展示如何显示一张带有标记的地图视图: ```dart import 'package:flutter/material.dart'; import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart'; class BaiduMapView extends StatefulWidget { @override _BaiduMapViewState createState() => _BaiduMapViewState(); } class _BaiduMapViewState extends State<BaiduMapView> { BMFPoint? center; void initState(){ super.initState(); // 设置中心坐标为天安门广场位置 center = new BMFPoint(latitude: 39.916527, longitude: 116.397228); } Widget build(BuildContext context){ return Scaffold( appBar: AppBar(title: Text('百度地图')), body: Container( child: BMFMapWidget( mapOptions: BMFMapOptions(center: center), ), ) ); } } ``` 通过以上步骤可以成功地把百度地图嵌入至 Flutter 工程当中去。当然这只是一个入门级的例子,更多高级特性还需要查阅官方文档进一步学习探索。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值