Draw Route line with alternative routes on map

这篇文档目前尚未提供译文,将以原文展示。

This example shows:

  1. How to fetch a route with an alternative route using RouteRequestParams

    1. .origin(origin)
    2. .destination(destination)
    3. .alternatives(true)
    4. .altCount(2)
  2. How to draw a route with alternative routes navMap.drawRoutes(directionsRoutes);

  3. How to show or hide the route duration symbol next to every single route line navMap.showRouteDurationSymbol(boolean);

For all code examples, refer to Navigation Code Examples

activity_draw_route_line_with_alt.xml view source

1<?xml version="1.0" encoding="utf-8"?>
2<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
3    xmlns:app="http://schemas.android.com/apk/res-auto"
4    xmlns:tools="http://schemas.android.com/tools"
5    android:layout_width="match_parent"
6    android:layout_height="match_parent">
7
8    <ai.nextbillion.maps.core.MapView
9        android:id="@+id/mapView"
10        android:layout_width="match_parent"
11        android:layout_height="match_parent"
12        app:nbmap_uiAttribution="false">
13    </ai.nextbillion.maps.core.MapView>
14
15    <LinearLayout
16        android:layout_width="wrap_content"
17        android:layout_height="wrap_content"
18        android:paddingLeft="10dp"
19        android:orientation="vertical"
20        android:layout_gravity="bottom">
21        <Button
22            android:id="@+id/fetchRoute"
23            android:layout_width="wrap_content"
24            android:layout_height="wrap_content"
25            android:textSize="12sp"
26            android:text="@string/draw_route"/>
27
28        <Button
29            android:id="@+id/hideRouteDuration"
30            android:layout_width="wrap_content"
31            android:layout_height="wrap_content"
32            android:textSize="12sp"
33            android:text="@string/draw_route_without"/>
34
35        <Button
36            android:id="@+id/startNav"
37            android:layout_width="wrap_content"
38            android:layout_height="wrap_content"
39            android:textSize="12sp"
40            android:text="@string/start_navigation"/>
41
42    </LinearLayout>
43
44    <ProgressBar
45        android:id="@+id/progress"
46        android:visibility="gone"
47        android:layout_width="wrap_content"
48        android:layout_height="wrap_content"
49        android:layout_gravity="center"/>
50</FrameLayout>

DrawRouteLineWithAltActivity view source

1package ai.nextbillion.navigation.demo.activity;
2
3import android.os.Bundle;
4import android.view.View;
5import android.widget.Button;
6import android.widget.ProgressBar;
7
8import java.util.List;
9
10import ai.nextbillion.kits.directions.models.DirectionsResponse;
11import ai.nextbillion.kits.directions.models.DirectionsRoute;
12import ai.nextbillion.kits.directions.models.RouteRequestParams;
13import ai.nextbillion.kits.geojson.Point;
14import ai.nextbillion.maps.camera.CameraUpdate;
15import ai.nextbillion.maps.camera.CameraUpdateFactory;
16import ai.nextbillion.maps.core.MapView;
17import ai.nextbillion.maps.core.NextbillionMap;
18import ai.nextbillion.maps.core.OnMapReadyCallback;
19import ai.nextbillion.maps.geometry.LatLng;
20import ai.nextbillion.maps.location.modes.RenderMode;
21import ai.nextbillion.navigation.core.routefetcher.RouteFetcher;
22import ai.nextbillion.navigation.demo.R;
23import ai.nextbillion.navigation.demo.utils.CameraAnimateUtils;
24import ai.nextbillion.navigation.ui.NavLauncherConfig;
25import ai.nextbillion.navigation.ui.NavigationLauncher;
26import ai.nextbillion.navigation.ui.camera.CameraUpdateMode;
27import ai.nextbillion.navigation.ui.camera.NavigationCameraUpdate;
28import ai.nextbillion.navigation.ui.map.NavNextbillionMap;
29import androidx.annotation.NonNull;
30import androidx.appcompat.app.AppCompatActivity;
31import retrofit2.Call;
32import retrofit2.Callback;
33import retrofit2.Response;
34
35public class DrawRouteLineWithAltActivity extends AppCompatActivity implements OnMapReadyCallback, View.OnClickListener {
36
37    private static final double DEFAULT_CAMERA_ZOOM = 14;
38
39    private Point origin = Point.fromLngLat(78.37463792413473, 17.457302037173775);
40    private Point destination = Point.fromLngLat(78.3726774987914, 17.466320809357967);
41
42    private MapView mapView;
43    private NavNextbillionMap navMap;
44
45    private Button fetchRoute;
46    private Button fetchRouteWithoutDuration;
47    private Button startNav;
48    private DirectionsRoute directionsRoute;
49    private List<DirectionsRoute> directionsRoutes;
50    private ProgressBar progress;
51    boolean showRouteDurationSymbol = true;
52    @Override
53    protected void onCreate(Bundle savedInstanceState) {
54        super.onCreate(savedInstanceState);
55        setContentView(R.layout.activity_draw_route_line_with_alt);
56        mapView = findViewById(R.id.mapView);
57        mapView.onCreate(savedInstanceState);
58        mapView.getMapAsync(this);
59        fetchRoute = findViewById(R.id.fetchRoute);
60        fetchRouteWithoutDuration = findViewById(R.id.hideRouteDuration);
61        startNav = findViewById(R.id.startNav);
62        progress = findViewById(R.id.progress);
63        fetchRoute.setOnClickListener(this);
64        startNav.setOnClickListener(this);
65        fetchRouteWithoutDuration.setOnClickListener(this);
66        fetchRouteWithoutDuration.setEnabled(false);
67        startNav.setEnabled(false);
68        fetchRoute.setEnabled(false);
69    }
70
71    @Override
72    public void onMapReady(@NonNull NextbillionMap nextbillionMap) {
73        nextbillionMap.getStyle(style -> {
74            navMap = new NavNextbillionMap(mapView, nextbillionMap);
75            CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(origin.latitude(),origin.longitude()), DEFAULT_CAMERA_ZOOM);
76            NavigationCameraUpdate navigationCameraUpdate = new NavigationCameraUpdate(cameraUpdate);
77            navigationCameraUpdate.setMode(CameraUpdateMode.OVERRIDE);
78            navMap.retrieveCamera().update(navigationCameraUpdate, 1000);
79            fetchRoute.setEnabled(true);
80            fetchRouteWithoutDuration.setEnabled(true);
81        });
82    }
83
84
85    @Override
86    public void onClick(View view) {
87        if (view.getId() == R.id.fetchRoute) {
88            showRouteDurationSymbol = true;
89            fetchRoute();
90        } else if (view.getId() == R.id.hideRouteDuration) {
91            showRouteDurationSymbol = false;
92            fetchRoute();
93        } else if (view.getId() == R.id.startNav) {
94            NavLauncherConfig.Builder configBuilder = NavLauncherConfig.builder(directionsRoute);
95            configBuilder.routes(directionsRoutes);
96            configBuilder.locationLayerRenderMode(RenderMode.GPS);
97            configBuilder.shouldSimulateRoute(true);
98            NavigationLauncher.startNavigation(DrawRouteLineWithAltActivity.this, configBuilder.build());
99        }
100    }
101
102    private void fetchRoute() {
103        progress.setVisibility(View.VISIBLE);
104
105        RouteRequestParams.Builder builder = RouteRequestParams.builder()
106                .origin(origin)
107                .destination(destination)
108                .alternatives(true)
109                .altCount(2)
110                .language("en")
111                .departureTime((int) (System.currentTimeMillis()/1000));
112
113        RouteFetcher.getRoute(builder.build(), new Callback<DirectionsResponse>() {
114            @Override
115            public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
116                progress.setVisibility(View.GONE);
117                //start navigation with the route we just fetched.
118                if (response.body() != null && !response.body().routes().isEmpty()) {
119                    directionsRoute = response.body().routes().get(0);
120                    directionsRoutes = response.body().routes();
121                    drawRouteLine();
122                    startNav.setEnabled(true);
123                }
124            }
125
126            @Override
127            public void onFailure(Call<DirectionsResponse> call, Throwable t) {
128                progress.setVisibility(View.GONE);
129            }
130        });
131    }
132
133    private void drawRouteLine() {
134        navMap.removeRoute();
135        navMap.clearMarkers();
136        navMap.showRouteDurationSymbol(showRouteDurationSymbol);
137        navMap.drawRoutes(directionsRoutes);
138        frameCameraToRoute();
139    }
140
141    private void frameCameraToRoute() {
142        int[] padding = CameraAnimateUtils.createPadding(this);
143        CameraAnimateUtils.frameCameraToBounds(navMap, directionsRoutes, padding);
144    }
145
146    @Override
147    protected void onStart() {
148        super.onStart();
149        mapView.onStart();
150    }
151
152    @Override
153    protected void onResume() {
154        super.onResume();
155        mapView.onResume();
156    }
157
158    @Override
159    protected void onPause() {
160        super.onPause();
161        mapView.onPause();
162    }
163
164    @Override
165    public void onLowMemory() {
166        super.onLowMemory();
167        mapView.onLowMemory();
168    }
169
170    @Override
171    protected void onStop() {
172        super.onStop();
173        mapView.onStop();
174    }
175
176    @Override
177    protected void onDestroy() {
178        mapView.onDestroy();
179        super.onDestroy();
180    }
181
182    @Override
183    protected void onSaveInstanceState(@NonNull Bundle outState) {
184        super.onSaveInstanceState(outState);
185        mapView.onSaveInstanceState(outState);
186    }
187
188}

Code Highlights

This Code example includes How to display a MapView and draw route lines with alternative routes on the map using NavNextbillionMap and start navigation with drawn routes using NavigationLauncher

In particular, this example shows we can display or hide the route duration symbol via function navMap.showRouteDurationSymbol(), and we can also let navigation API return more than 1 route result if available, by setting RouteRequestParams.alternatives as true, and RouteRequestParams.altCount as the desired route count you wish to have.

Code summary

Map Initialization:

  1. The onMapReady() method is called when the map is ready to be used.

  2. The NavNextbillionMap class is used to create a navigation-enabled map by passing the MapView and NextbillionMap instances.

  3. The camera position is set to the origin point with a default zoom level using CameraUpdateFactory.newLatLngZoom() and NavigationCameraUpdate.

Fetch route with RouteFetcher

  1. Constructs a RouteRequestParams object with the

    1. origin

    2. destination

    3. language

    4. alternatives

    5. altCount

    6. departure time

  2. The RouteFetcher.getRoute() method is used to fetch the route using the RouteRequestParams.

Draw route with/without duration symbol

  1. The route is drawn on the map using navMap.drawRoutes()

  2. The camera is framed to fit the route using frameCameraToRoute()

  3. To show or hide the duration symbol using navMap.showRouteDurationSymbol(true/false)

  4. To clear the drawn route and markers using navMap.removeRoute() navMap.clearMarkers()

Start Navigation

  1. Creates a NavLauncherConfig.Builder and configures the navigation settings, including the location layer render mode and whether to simulate the route.

  2. The NavigationLauncher.startNavigation() method is called to start the navigation activity with the configured NavLauncherConfig.

没找到你要找的内容?