

Streamlined Implementation for In-App Route Planning
source link: https://forum.xda-developers.com/t/streamlined-implementation-for-in-app-route-planning.4196589/#post-87933017
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Streamlined Implementation for In-App Route Planning
Preface
HUAWEI Map Kit includes a route planning function, which offers a set of HTTPS-based APIs. These APIs are used to plan walking, cycling, and driving routes, as well as calculate route distances. They return route data in JSON format, and comprise the route planning capability.
Route planning APIs are as follows:
Walking route planning API: Provides the function for planning walking routes within distances of 100 kilometers or less.
Cycling route planning API: Provides the function for planning cycling routes within distances of 100 kilometers or less.
Driving route planning API: Provides the function for planning driving routes.
Up to 3 routes can be returned for each request.
Up to 5 waypoints can be specified.
Routes can be planned for future travel.
Routes can be planned based on real-time traffic conditions.
Use Cases
Ride hailing: Real-time route planning and route planning for future travel can provide accurate price estimates for ride-hailing orders. The estimated time of arrival (ETA) can be calculated for multiple routes in batches during order dispatch, for dramatically enhanced efficiency.
Logistics: Driving and cycling route planning provides accurate routes, ETAs, and estimated road tolls for trunk and branch road logistics and logistics delivery.
Tourism: When booking hotels and designing tourism routes, users can determine the distance between hotels, scenic spots, and transport stations with greater ease, thanks to high-level route planning capabilities, and enjoy efficient, hassle-free travel at all times.
Preparations
Before using the route planning function, first obtain the API key in AppGallery Connect.

Note
If the API key contains special characters, you need to encode it using encodeURI. For example, if the original API key is ABC/DFG+, the conversion result is ABC%2FDFG%2B.
Apply for the network access permission in the AndroidManifest.xml file.
<!-- Network permission -->
<uses-permission android:name="android.permission.INTERNET" />
Development Procedure
1. Initialize a map for displaying planned routes.
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);
}
2. Obtain the current user location and use it as the start point for route planning.
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"));
}
3. Add a map long-press event listener to listen to the end point for route planning.
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;
});

4. Generate a route planning request based on the specified start point and end point.
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;
}
5. Draw planned routes on the map based on the route planning response.
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 Effects

</div
Recommend
-
115
Allo v22 is testing streamlined new chat UI, preparing to add transcriptions for audio messages and new camera effects [APK Teardown] By Cody...
-
117
XChange XChange is a Java library providing a simple and consistent API for interacting with 60+ Bitcoin and other crypto currency exchanges, providing a consistent interface for trading and accessing market data. Important!...
-
55
README.md
-
17
Developers karussell February 1...
-
5
Using smartphones’ location data for route planning and logistics Arjun Attam
-
9
Technical Articles
-
15
Deploy React App in 10 minutes with AWS Amplify and Route 53
-
9
Waze is adding electric vehicle charging stations to its route planning tool / The Google-owned navigation tool says its EV charging locator will be the most accurate thanks to its crowdsourced map editing feature.
-
12
Delivery Vehicle Route Planning with Ant Colony Optimization Many real world opti...
-
2
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK