Fetch routes and Draw route lines on a map

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

This example shows how to fetch routes using RouteFetcher and draw route lines on the map view

  1. How to initialize a mapView and bind it to the activity lifecycle

  2. How to fetch routes using RouteFetcher

  3. Draw a route line using navMap.drawRoute(route)

  4. Config to show or hide route duration symbol using navMap.showRouteDurationSymbol(boolean)

  5. How to Frame Map Camera using the given route

For all code examples, refer to Navigation Code Examples

activity_draw_route_line.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    tools:context=".activity.DrawRouteLineActivity">
8
9    <ai.nextbillion.maps.core.MapView
10        android:id="@+id/mapView"
11        android:layout_width="match_parent"
12        android:layout_height="match_parent"
13        app:nbmap_uiAttribution="false">
14    </ai.nextbillion.maps.core.MapView>
15
16    <LinearLayout
17        android:layout_width="wrap_content"
18        android:layout_height="wrap_content"
19        android:paddingLeft="10dp"
20        android:orientation="vertical"
21        android:layout_gravity="bottom">
22        <Button
23            android:id="@+id/fetchRoute"
24            android:layout_width="wrap_content"
25            android:layout_height="wrap_content"
26            android:textSize="12sp"
27            android:text="@string/draw_route"/>
28
29        <Button
30            android:id="@+id/hideRouteDuration"
31            android:layout_width="wrap_content"
32            android:layout_height="wrap_content"
33            android:textSize="12sp"
34            android:text="@string/draw_route_without"/>
35
36        <Button
37            android:id="@+id/startNav"
38            android:layout_width="wrap_content"
39            android:layout_height="wrap_content"
40            android:textSize="12sp"
41            android:text="@string/start_navigation"/>
42
43    </LinearLayout>
44
45    <ProgressBar
46        android:id="@+id/progress"
47        android:visibility="gone"
48        android:layout_width="wrap_content"
49        android:layout_height="wrap_content"
50        android:layout_gravity="center"/>
51</FrameLayout>

DrawRouteLineActivity 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 DrawRouteLineActivity extends AppCompatActivity implements OnMapReadyCallback, View.OnClickListener {
36
37    private static final double DEFAULT_CAMERA_ZOOM = 14;
38
39    private Point origin = Point.fromLngLat(103.75986708439264, 1.312533169133601);
40    private Point destination = Point.fromLngLat(103.77982271935586, 1.310473772283314);
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);
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.locationLayerRenderMode(RenderMode.GPS);
96            configBuilder.shouldSimulateRoute(true);
97            NavigationLauncher.startNavigation(DrawRouteLineActivity.this, configBuilder.build());
98        }
99    }
100
101    private void fetchRoute() {
102        progress.setVisibility(View.VISIBLE);
103
104        RouteRequestParams.Builder builder = RouteRequestParams.builder()
105                .origin(origin)
106                .destination(destination)
107                .language("en")
108                .departureTime((int) (System.currentTimeMillis()/1000));
109
110        RouteFetcher.getRoute(builder.build(), new Callback<DirectionsResponse>() {
111            @Override
112            public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
113                progress.setVisibility(View.GONE);
114                //start navigation with the route we just fetched.
115                if (response.body() != null && !response.body().routes().isEmpty()) {
116                    directionsRoute = response.body().routes().get(0);
117                    directionsRoutes = response.body().routes();
118                    drawRouteLine();
119                    startNav.setEnabled(true);
120                }
121            }
122
123            @Override
124            public void onFailure(Call<DirectionsResponse> call, Throwable t) {
125                progress.setVisibility(View.GONE);
126            }
127        });
128    }
129
130    private void drawRouteLine() {
131        navMap.removeRoute();
132        navMap.clearMarkers();
133        navMap.showRouteDurationSymbol(showRouteDurationSymbol);
134        navMap.drawRoute(directionsRoute);
135        frameCameraToRoute();
136    }
137
138    private void frameCameraToRoute() {
139       int[] padding = CameraAnimateUtils.createPadding(this);
140       CameraAnimateUtils.frameCameraToBounds(navMap, directionsRoutes, padding);
141    }
142
143    @Override
144    protected void onStart() {
145        super.onStart();
146        mapView.onStart();
147    }
148
149    @Override
150    protected void onResume() {
151        super.onResume();
152        mapView.onResume();
153    }
154
155    @Override
156    protected void onPause() {
157        super.onPause();
158        mapView.onPause();
159    }
160
161    @Override
162    public void onLowMemory() {
163        super.onLowMemory();
164        mapView.onLowMemory();
165    }
166
167    @Override
168    protected void onStop() {
169        super.onStop();
170        mapView.onStop();
171    }
172
173    @Override
174    protected void onDestroy() {
175        mapView.onDestroy();
176        super.onDestroy();
177    }
178
179    @Override
180    protected void onSaveInstanceState(@NonNull Bundle outState) {
181        super.onSaveInstanceState(outState);
182        mapView.onSaveInstanceState(outState);
183    }
184
185}

Code Highlights

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

In particular, this example code shows the code logic of displaying or hiding route duration symbol via navMap.showRouteDurationSymbol() function. We could customize the logic based on needs.

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 origin, destination, language, and 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.drawRoute()

  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.

没找到你要找的内容?