Offline routing

View on GitHubSample viewer app

Solve a route on-the-fly using offline data.

Image of offline routing

Use case

You can use an offline network to enable routing in disconnected scenarios. For example, you could provide offline location capabilities to field workers repairing critical infrastructure in a disaster when network availability is limited.

How to use the sample

Left-click near a road to add a stop to the route. A number graphic will show its order in the route. After adding at least 2 stops, a route will display. Choose "Fastest" or "Shortest" from the drop down menu to control how the route is optimized. To move a stop, right-click the graphic to select it, move your mouse to reposition and finally right-click again to set the new position. The route will update on-the-fly while moving stops. The green box marks the boundary of the routable area provided by the offline data.

How it works

  1. Create the map's Basemap from a local tile package using a TileCache and ArcGISTiledLayer.
  2. Create a RouteTask with an offline locator geodatabase.
  3. Get the RouteParameters using routeTask.createDefaultParameters().
  4. Create Stops and add them to the route task's parameters.
  5. Solve the Route using routeTask.solveRouteAsync(routeParameters).
  6. Create a graphic with the route's geometry and a SimpleLineSymbol and display it on another GraphicsOverlay.

About the data

This sample uses a pre-packaged sample dataset consisting of a geodatabase with a San Diego road network and a tile package with a streets basemap.

Relevant API

  • RouteParameters
  • RouteResult
  • RouteTask
  • Stop
  • TravelMode

Tags

connectivity, disconnected, fastest, locator, navigation, network analysis, offline, routing, shortest, turn-by-turn

Sample Code

OfflineRoutingSample.java
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/*
 * Copyright 2017 Esri.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.esri.samples.offline_routing;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.StringConverter;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.TileCache;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.ArcGISTiledLayer;
import com.esri.arcgisruntime.loadable.LoadStatus;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.IdentifyGraphicsOverlayResult;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.LineSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.symbology.TextSymbol;
import com.esri.arcgisruntime.tasks.networkanalysis.Route;
import com.esri.arcgisruntime.tasks.networkanalysis.RouteParameters;
import com.esri.arcgisruntime.tasks.networkanalysis.RouteResult;
import com.esri.arcgisruntime.tasks.networkanalysis.RouteTask;
import com.esri.arcgisruntime.tasks.networkanalysis.Stop;
import com.esri.arcgisruntime.tasks.networkanalysis.TravelMode;

public class OfflineRoutingSample extends Application {

  private MapView mapView;
  private GraphicsOverlay stopsOverlay;
  private GraphicsOverlay routeOverlay;
  private RouteTask routeTask;
  private RouteParameters routeParameters;
  private LineSymbol lineSymbol;

  private EventHandler<MouseEvent> mouseMovedListener;

  @Override
  public void start(Stage stage) {

    try {
      // create stack pane and application scene
      StackPane stackPane = new StackPane();
      Scene scene = new Scene(stackPane);
      scene.getStylesheets().add(getClass().getResource("/offline_routing/style.css").toExternalForm());

      // set title, size, and add scene to stage
      stage.setTitle("Offline Routing Sample");
      stage.setWidth(800);
      stage.setHeight(700);
      stage.setScene(scene);
      stage.show();

      // create the map's basemap from a local tile package
      File tpkFile = new File(System.getProperty("data.dir"), "./samples-data/sandiego/streetmap_SD.tpkx");
      TileCache tileCache = new TileCache(tpkFile.getAbsolutePath());
      ArcGISTiledLayer tiledLayer = new ArcGISTiledLayer(tileCache);
      Basemap basemap = new Basemap(tiledLayer);
      ArcGISMap map = new ArcGISMap(basemap);
      mapView = new MapView();
      mapView.setMap(map);

      // create graphics overlays for route and stops
      stopsOverlay = new GraphicsOverlay();
      routeOverlay = new GraphicsOverlay();
      mapView.getGraphicsOverlays().addAll(Arrays.asList(routeOverlay, stopsOverlay));

      ComboBox<TravelMode> travelModes = new ComboBox<>();
      travelModes.getSelectionModel().selectedItemProperty().addListener(o -> {
        routeParameters.setTravelMode(travelModes.getSelectionModel().getSelectedItem());
        updateRoute();
      });
      // display travel mode name within combobox
      travelModes.setConverter(new StringConverter<TravelMode>() {

        @Override
        public String toString(TravelMode travelMode) {

          return travelMode != null ? travelMode.getName() : "";
        }

        @Override
        public TravelMode fromString(String fileName) {

          return null;
        }
      });

      // create an offline RouteTask
      File geodatabaseFile = new File(System.getProperty("data.dir"), "./samples-data/sandiego/sandiego.geodatabase");
      routeTask = new RouteTask(geodatabaseFile.getAbsolutePath(), "Streets_ND");
      routeTask.loadAsync();
      routeTask.addDoneLoadingListener(() -> {
        if (routeTask.getLoadStatus() == LoadStatus.LOADED) {
          try {
            // create route parameters
            routeParameters = routeTask.createDefaultParametersAsync().get();

            travelModes.getItems().addAll(routeTask.getRouteTaskInfo().getTravelModes());
            travelModes.getSelectionModel().select(0);
          } catch (InterruptedException | ExecutionException e) {
            displayMessage("Error getting default route parameters", e.getMessage());
          }
        } else {
          displayMessage("Error loading route task", routeTask.getLoadError().getMessage());
        }
      });

      // add a graphics overlay to show the boundary
      Envelope envelope = new Envelope(new Point(-13045352.223196, 3864910.900750, 0, SpatialReferences.getWebMercator()),
          new Point(-13024588.857198, 3838880.505604, 0, SpatialReferences.getWebMercator()));
      SimpleLineSymbol boundarySymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.DASH, Color.LIME, 5);
      Graphic boundary = new Graphic(envelope, boundarySymbol);
      GraphicsOverlay boundaryOverlay = new GraphicsOverlay();
      boundaryOverlay.getGraphics().add(boundary);
      mapView.getGraphicsOverlays().add(boundaryOverlay);

      // create symbol for route
      lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLUE, 3);

      // create mouse moved event listener to update the route when moving stops
      mouseMovedListener = event -> {

        if (!stopsOverlay.getSelectedGraphics().isEmpty()) {

          Point2D hoverLocation = new Point2D(event.getX(), event.getY());
          Point hoverPoint = mapView.screenToLocation(hoverLocation);

          // update the moving stop and graphic
          Graphic stopGraphic = stopsOverlay.getSelectedGraphics().get(0);
          stopGraphic.setGeometry(hoverPoint);

          // update route
          if (stopsOverlay.getGraphics().size() > 1) {
            updateRoute();
          }
        }

      };

      // use mouse clicks to add and move stops
      mapView.setOnMouseClicked(event -> {

        if (routeTask.getLoadStatus() == LoadStatus.LOADED && event.isStillSincePress()) {

          // get mouse click location
          Point2D clickLocation = new Point2D(event.getX(), event.getY());
          Point point = mapView.screenToLocation(clickLocation);

          // left click adds a stop when not already moving a stop
          if (event.getButton() == MouseButton.PRIMARY && stopsOverlay.getSelectedGraphics().isEmpty()) {

            // create graphic for stop
            TextSymbol stopLabel = new TextSymbol(20, Integer.toString(stopsOverlay.getGraphics().size() + 1),
                Color.RED, TextSymbol.HorizontalAlignment.RIGHT, TextSymbol.VerticalAlignment.TOP);

            // create and add the stop graphic to the graphics overlay and list
            Graphic stopGraphic = new Graphic(point, stopLabel);
            stopsOverlay.getGraphics().add(stopGraphic);

            // update the route
            updateRoute();
          }

          // right click to select/deselect a stop to move
          if (event.getButton() == MouseButton.SECONDARY) {

            // select a stop
            if (stopsOverlay.getSelectedGraphics().isEmpty()) {
              // identify the selected graphic
              ListenableFuture<IdentifyGraphicsOverlayResult> results = mapView.identifyGraphicsOverlayAsync(
                  stopsOverlay, clickLocation, 10, false);
              results.addDoneListener(() -> {
                try {
                  List<Graphic> graphics = results.get().getGraphics();
                  if (graphics.size() > 0) {
                    // set the graphic as selected
                    Graphic graphic = graphics.get(0);
                    graphic.setSelected(true);

                    // add the mouse move event listener to update the route
                    mapView.setOnMouseMoved(mouseMovedListener);
                  }

                } catch (InterruptedException | ExecutionException e) {
                  e.printStackTrace();
                }
              });
            } else {
              stopsOverlay.clearSelection();

              // remove the mouse moved event listener when not moving stops
              mapView.setOnMouseMoved(null);
            }
          }
        }
      });

      // add controls to stackpane
      stackPane.getChildren().addAll(mapView, travelModes);
      StackPane.setAlignment(travelModes, Pos.TOP_LEFT);
      StackPane.setMargin(travelModes, new Insets(10, 0, 0, 10));

    } catch (Exception e) {
      // on any error, display the stack trace.
      e.printStackTrace();
    }
  }

  /**
   * Update the route based on the set or moving stops.
   */
  private void updateRoute() {

    if (stopsOverlay.getGraphics().size() > 1) {
      // remove listener until route task is solved
      if (!stopsOverlay.getSelectedGraphics().isEmpty()) {
        mapView.setOnMouseMoved(null);
      }

      // update stops and solve route
      List<Stop> stops = stopsOverlay.getGraphics().stream()
          .map(g -> new Stop((Point) g.getGeometry()))
          .collect(Collectors.toList());
      routeParameters.setStops(stops);
      ListenableFuture<RouteResult> results = routeTask.solveRouteAsync(routeParameters);
      results.addDoneListener(() -> {
        try {
          RouteResult result = results.get();
          Route route = result.getRoutes().get(0);

          // create graphic for route
          Graphic graphic = new Graphic(route.getRouteGeometry(), lineSymbol);

          // replace route graphic
          routeOverlay.getGraphics().clear();
          routeOverlay.getGraphics().add(graphic);

        } catch (InterruptedException | ExecutionException e) {
          // ignore, no route solution

        } finally {
          // add mouse moved listener back
          if (!stopsOverlay.getSelectedGraphics().isEmpty()) {
            mapView.setOnMouseMoved(mouseMovedListener);
          }
        }
      });
    }
  }

  /**
   * Shows a message in an alert dialog.
   *
   * @param title title of alert
   * @param message message to display
   */
  private void displayMessage(String title, String message) {

    Platform.runLater(() -> {
      Alert dialog = new Alert(Alert.AlertType.INFORMATION);
      dialog.setHeaderText(title);
      dialog.setContentText(message);
      dialog.showAndWait();
    });
  }

  /**
   * Stops and releases all resources used in application.
   */
  @Override
  public void stop() {

    if (mapView != null) {
      mapView.dispose();
    }
  }

  /**
   * Opens and runs application.
   *
   * @param args arguments passed to this application
   */
  public static void main(String[] args) {

    Application.launch(args);
  }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.