应用内路径规划的简单实现

前言

华为Map Kit提供的路径规划API是一套以HTTPS形式提供的步行、骑行、驾车路径规划以及行驶距离计算接口,通过JSON格式返回路径查询数据,提供路径规划能力。

路径规划具体提供如下功能:

  • 步行路径规划 API提供100km以内的步行路径规划能力。
  • 骑行路径规划 API提供100km以内的骑行路径规划能力。
  • 驾车路径规划 API提供驾车路径规划能力,支持以下功能:
    -支持一次请求返回多条路线,最多支持3条路线。
    -最多支持5个途经点。
    -支持未来出行规划。
    -支持根据实时路况进行合理路线规划。

场景

用车服务:利用即时和未来出行路线规划为订单提供准确的价格预估。在派单场景中,利高性能批量到达时间预估(ETA)服务,提升派单效率。

物流:利用驾车和骑行路线规划,为支干线物流和末端配送提供准确的路线规划、耗时预估和道路收费预测。

旅游:用户在预定酒店、设计旅游线路时,通过路线规划分析酒店、景点、交通站点之间的路线距离,帮助用户更高效规划行程。

开发前准备

l 路径规划服务使用前,需要在开发者联盟网站上获取API KEY。

在这里插入图片描述

说明
如果API KEY包含特殊字符,则需要进行encodeURI编码。例如:原始API KEY:ABC/DFG+ ,转换结果: ABC%2FDFG%2B。

l 在AndroidManifest.xml文件里面申请访问网络权限

<!-- 网络权限 -->

<uses-permission android:name="android.permission.INTERNET" />

代码开发关键步骤

  1. 初始化map,用于路径规划结果的展示
private MapFragment mMapFragment;
private HuaweiMap hMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_directions);

    mMapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapfragment_mapfragmentdemo);
    mMapFragment.getMapAsync(this);
}
  1. 获取用户当前位置,作为路径规划的起点
private void getMyLocation() {
    Task<Location> locationTask = LocationServices.getFusedLocationProviderClient(this).getLastLocation();
    locationTask.addOnCompleteListener(param0 -> {
        if (param0 != null) {
            Location location = param0.getResult();
            double Lat = location.getLatitude();
            double Lng = location.getLongitude();
            myLocation = new LatLng(Lat, Lng);
            Log.d(TAG, " Lat is : " + Lat + ", Lng is : " + Lng);

            CameraUpdate CameraUpdate = CameraUpdateFactory.newLatLng(myLocation);
            hMap.moveCamera(CameraUpdate);
        }
    }).addOnFailureListener(param0 -> Log.d(TAG, "lastLocation is error"));
}
  1. 添加map长按事件,用于响应用户设定的路径规划终点
hMap.setOnMapLongClickListener(latLng -> {
    if (null != mDestinationMarker) {
        mDestinationMarker.remove();
    }
    if (null != mPolylines) {
        for (Polyline polyline : mPolylines) {
            polyline.remove();
        }
    }
    enableAllBtn();
    MarkerOptions options = new MarkerOptions().position(latLng).title("dest");
    mDestinationMarker = hMap.addMarker(options);
    mDestinationMarker.setAnchor(0.5f,1f);

    StringBuilder dest = new StringBuilder(String.format(Locale.getDefault(), "%.6f", latLng.latitude));
    dest.append(", ").append(String.format(Locale.getDefault(), "%.6f", latLng.longitude));
    ((TextInputEditText)findViewById(R.id.dest_input)).setText(dest);
    mDest = latLng;
});

在这里插入图片描述

  1. 根据起点和终点信息,生成路径规划请求
private JSONObject buildRequest() {
    JSONObject request = new JSONObject();
    try {
        JSONObject origin = new JSONObject();
        origin.put("lng", myLocation.longitude);
        origin.put("lat", myLocation.latitude);
        JSONObject destination = new JSONObject();
        destination.put("lng", mDest.longitude);
        destination.put("lat", mDest.latitude);
        request.put("origin", origin);
        request.put("destination", destination);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return request;
}
  1. 根据路径规划响应,在地图上绘制路径规划结果
JSONObject route = new JSONObject(result);
JSONArray routes = route.optJSONArray("routes");
JSONObject route1 = routes.optJSONObject(0);
JSONArray paths = route1.optJSONArray("paths");
JSONObject path1 = paths.optJSONObject(0);
JSONArray steps = path1.optJSONArray("steps");
for (int i = 0; i < steps.length(); i++) {
    PolylineOptions options = new PolylineOptions();
    JSONObject step = steps.optJSONObject(i);
    JSONArray polyline = step.optJSONArray("polyline");
    for (int j = 0; j < polyline.length(); j++) {
        JSONObject polyline_t = polyline.optJSONObject(j);
        options.add(new LatLng(polyline_t.getDouble("lat"), polyline_t.getDouble("lng")));
    }
    Polyline pl = hMap.addPolyline(options.color(Color.BLUE).width(3));
    mPolylines.add(pl);
}

Demo效果

在这里插入图片描述

Github源码

如果你对实现方式感兴趣,可以查看Github上的源码:https://github.com/HMS-Core/hms-mapkit-demo-java

欲了解更多详情,请参阅:

华为开发者联盟官网:https://developer.huawei.com/consumer/cn/hms?ha_source=hms1

获取开发指导文档:https://developer.huawei.com/consumer/cn/doc/development?ha_source=hms1

参与开发者讨论请到Reddit社区:https://www.reddit.com/r/HuaweiDevelopers/

下载demo和示例代码请到Github:https://github.com/HMS-Core

解决集成问题请到Stack Overflow:https://stackoverflow.com/questions/tagged/huawei-mobile-services?tab=Newest


原文链接:https://developer.huawei.com/consumer/cn/forum/topic/0204403880529210184?fid=18

原作者:胡椒

猜你喜欢

转载自blog.51cto.com/14772288/2552865