Mobile map (search and route)

View on GitHubSample viewer app

Display maps and use locators to enable search and routing offline using a mobile map package.

Image of mobile map search and route

Use case

Mobile map packages make it easy to transmit and store the necessary components for an offline map experience including: transportation networks (for routing/navigation), locators (address search, forward and reverse geocoding), and maps.

A field worker might download a mobile map package to support their operations while working offline, for example to navigate remote oil field roads.

How to use the sample

Click the "Open mobile map package" button to bring up a file choosing dialog. Browse to and select a .mmpk file. When chosen, the maps inside the mobile map package will be displayed in a list view. Click on a map in the list to open it.

If the mobile map package has a locator task, the list items will have a pin icon. Click on the map to reverse geocode the clicked locations's address if a locator task is available.

If the map contains transportation networks, it will have a navigation icon. Click on the map to add locations. If transportation networks are available, a route will be calculated between locations.

How it works

  1. Create a MobileMapPackage passing in the path to the local mmpk file.
  2. Get a list of maps inside the package with mobileMapPackage.getMaps().
  3. If the package has a locator, access it with mobileMapPackage.getLocatorTask().
  4. To see if a map contains transportation networks, call map.getTransportationNetworks(). Each TransportationNetworkDataset can be used to construct a RouteTask.

Relevant API

  • GeocodeResult
  • MobileMapPackage
  • ReverseGeocodeParameters
  • Route
  • RouteParameters
  • RouteResult
  • RouteTask
  • TransportationNetworkDataset

Offline data

This sample uses the San Francisco mobile map package and the Yellowstone mobile map package. Both are downloaded from ArcGIS Online automatically.

Tags

disconnected, field mobility, geocode, network, network analysis, offline, routing, search, transportation

Sample Code

MobileMapSearchAndRouteSample.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
/*
 * Copyright 2018 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.mobile_map_search_and_route;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;

import com.esri.arcgisruntime.data.TransportationNetworkDataset;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.loadable.LoadStatus;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.MobileMapPackage;
import com.esri.arcgisruntime.mapping.view.Callout;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.LineSymbol;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.tasks.geocode.GeocodeResult;
import com.esri.arcgisruntime.tasks.geocode.ReverseGeocodeParameters;
import com.esri.arcgisruntime.tasks.networkanalysis.Route;
import com.esri.arcgisruntime.tasks.networkanalysis.RouteTask;
import com.esri.arcgisruntime.tasks.networkanalysis.Stop;

import javafx.application.Application;
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.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Duration;

public class MobileMapSearchAndRouteSample extends Application {

  private MapView mapView;
  private MobileMapPackage mobileMapPackage;

  @Override
  public void start(Stage stage) {

    try {
      // create stack pane and application scene
      var stackPane = new StackPane();
      var scene = new Scene(stackPane);

      // set title, size, and add scene to stage
      stage.setTitle("Mobile Map Search and Route Sample");
      stage.setWidth(800);
      stage.setHeight(700);
      stage.setScene(scene);
      stage.show();

      // create a map view
      mapView = new MapView();

      // create a list view to list the maps in a mobile map package
      ListView<ArcGISMap> mapPackageListView = new ListView<>();
      mapPackageListView.setMaxSize(170, 100);

      // create a file chooser to find local mmpk files
      var fileChooser = new FileChooser();
      FileChooser.ExtensionFilter mmpkFilter = new FileChooser.ExtensionFilter("Map Packages (*.mmpk)", "*.mmpk");
      fileChooser.getExtensionFilters().add(mmpkFilter);
      fileChooser.setInitialDirectory(new File(System.getProperty("data.dir"), Path.of( "samples-data", "mmpk").toString()));

      // click a button to open the file chooser
      Button findMmpkButton = new Button("Open mobile map package");
      findMmpkButton.setOnAction(e -> {
        File selectedMmpk = fileChooser.showOpenDialog(mapView.getScene().getWindow());
        if (selectedMmpk != null) {
          // remember the directory of the mmpk for next time
          fileChooser.setInitialDirectory(selectedMmpk.getParentFile());
          fileChooser.setInitialFileName(selectedMmpk.getAbsolutePath());

          // clear the map and list selection from any previous mmpks
          mapPackageListView.getSelectionModel().clearSelection();
          mapPackageListView.getItems().clear();
          mapView.setMap(null);

          // create a mobile map package from the file path and load it
          mobileMapPackage = new MobileMapPackage(selectedMmpk.getAbsolutePath());
          mobileMapPackage.loadAsync();
          mobileMapPackage.addDoneLoadingListener(() -> {
            if (mobileMapPackage.getLoadStatus() == LoadStatus.LOADED && !mobileMapPackage.getMaps().isEmpty()) {
              if (!mobileMapPackage.getMaps().isEmpty()) {
                // show the maps belonging to the mobile map package in the list view
                mobileMapPackage.getMaps().forEach(map -> mapPackageListView.getItems().add(map));
                // default to displaying the first map in the map view
                mapPackageListView.getSelectionModel().select(mobileMapPackage.getMaps().get(0));
              } else {
                var alert = new Alert(Alert.AlertType.WARNING, "Map package does not have any maps");
                alert.initOwner(mapView.getScene().getWindow());
                alert.show();
              }
            } else {
              new Alert(Alert.AlertType.ERROR, "Failed to load the mobile map package").show();
            }
          });
        }
      });

      // create a custom list item for each of the map package's maps
      mapPackageListView.setCellFactory(list -> new ListCell<>() {
        @Override
        protected void updateItem(ArcGISMap map, boolean bln) {
          super.updateItem(map, bln);
          if (map != null) {
            var hBox = new HBox();
            hBox.setMinWidth(100);

            // show the mobile map package thumbnail image
            var thumbnailImageView = new ImageView();
            hBox.getChildren().add(thumbnailImageView);
            thumbnailImageView.setFitHeight(20);
            thumbnailImageView.setPreserveRatio(true);
            mobileMapPackage.getItem().fetchThumbnailAsync().toCompletableFuture().whenComplete(
              (thumbnailData, exception) -> {
                if (exception == null) {
                  thumbnailImageView.setImage(new Image(new ByteArrayInputStream(thumbnailData)));
                } else {
                  exception.printStackTrace();
                }
              });

            // show a location pin symbol in the list item if the map package includes a locator task
            if (mobileMapPackage.getLocatorTask() != null) {
              var locatorImageView = new ImageView();
              locatorImageView.setFitHeight(20);
              locatorImageView.setPreserveRatio(true);
              locatorImageView.setImage(new Image(getClass().getResourceAsStream("/pinOutlineSymbol.png")));
              hBox.getChildren().add(locatorImageView);
            }

            // show a routing symbol in the list item if the map has transportation networks
            if (!map.getTransportationNetworks().isEmpty()) {
              var routingImageView = new ImageView();
              routingImageView.setFitHeight(20);
              routingImageView.setPreserveRatio(true);
              routingImageView.setImage(new Image(getClass().getResourceAsStream("/routingSymbol.png")));
              hBox.getChildren().add(routingImageView);
            }
            setGraphic(hBox);

            // set the list cell's text to the map's index
            setText("Map " + this.getIndex());
          } else {
            setGraphic(null);
            setText(null);
          }
        }
      });

      // create a graphics overlay for showing geocoded locations (for when the mobile map package has a locator task)
      var locationsGraphicsOverlay = new GraphicsOverlay();
      mapView.getGraphicsOverlays().add(locationsGraphicsOverlay);
      var image = new Image(getClass().getResourceAsStream("/pin.png"), 0, 80, true, true);
      var pinSymbol = new PictureMarkerSymbol(image);
      pinSymbol.loadAsync();

      // create a graphics overlay for showing routes (for when the map has transportation network datasets)
      var routesGraphicsOverlay = new GraphicsOverlay();
      mapView.getGraphicsOverlays().add(routesGraphicsOverlay);
      LineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLUE, 3);

      // switch the map in the map view to the one selected in the list view
      mapPackageListView.getSelectionModel().selectedItemProperty().addListener(o -> {
        ArcGISMap selectedMap = mapPackageListView.getSelectionModel().getSelectedItem();
        if (selectedMap != null) {
          mapView.setMap(selectedMap);
          // clear any previous locations/routes
          locationsGraphicsOverlay.getGraphics().clear();
          routesGraphicsOverlay.getGraphics().clear();
          mapView.getCallout().setVisible(false);
        }
      });

      // perform a reverse geocode where the user clicks on the map view if the mobile map package has a locator task
      mapView.setOnMouseClicked(e -> {
        if (e.isStillSincePress() && e.getButton() == MouseButton.PRIMARY && mobileMapPackage != null && mobileMapPackage.getLocatorTask() != null) {
          Point2D point = new Point2D(e.getX(), e.getY());
          Point mapPoint = mapView.screenToLocation(point);

          // perform a reverse geocode at the clicked location
          var reverseGeocodeParameters = new ReverseGeocodeParameters();
          reverseGeocodeParameters.setMaxResults(1);
          mobileMapPackage.getLocatorTask().reverseGeocodeAsync(mapPoint, reverseGeocodeParameters).toCompletableFuture()
            .whenComplete((geocodeResults, exception) -> {
              if (exception == null) {
                // show a pin graphic and a callout with the geocode's address
                if (!geocodeResults.isEmpty()) {
                  // get the geocode from the singleton list of geocode results
                  GeocodeResult geocode = geocodeResults.get(0);
                  Point location = geocode.getDisplayLocation();

                  // get attributes from the result for the callout
                  String address = geocode.getAttributes().get("Match_addr").toString();
                  HashMap<String, Object> graphicAttributes = new HashMap<>();
                  graphicAttributes.put("title", address.split(",")[0]);
                  graphicAttributes.put("detail", address.substring(address.indexOf(", ") + 2));

                  // create a marker for the location
                  Graphic marker = new Graphic(geocode.getDisplayLocation(), graphicAttributes, pinSymbol);
                  locationsGraphicsOverlay.getGraphics().add(marker);

                  // display the callout at the location
                  Callout callout = mapView.getCallout();
                  callout.setTitle(marker.getAttributes().get("title").toString());
                  callout.setDetail(marker.getAttributes().get("detail").toString());
                  callout.setLeaderPosition(Callout.LeaderPosition.BOTTOM);
                  callout.showCalloutAt(location, new Point2D(0, -24), Duration.ZERO);

                  // if the map has transportation network datasets, solve for a route between the last two locations
                  if (!mapView.getMap().getTransportationNetworks().isEmpty() && locationsGraphicsOverlay.getGraphics().size() > 1) {
                    // use the first transportation network dataset in the map to create a route task
                    TransportationNetworkDataset networkDataset = mapView.getMap().getTransportationNetworks().get(0);
                    var routeTask = new RouteTask(networkDataset);
                    // create route parameters with the last two locations' stops
                    List<Graphic> locationGraphics = locationsGraphicsOverlay.getGraphics();
                    List<Stop> stops = locationGraphics.subList(Math.max(locationGraphics.size() - 2, 0), locationGraphics.size())
                      .stream()
                      .map(g -> new Stop((Point) g.getGeometry()))
                      .toList();
                    routeTask.createDefaultParametersAsync().toCompletableFuture()
                      .thenCompose(routeParameters -> {
                        routeParameters.setStops(stops);
                        // solve the route and display the result graphic
                        return routeTask.solveRouteAsync(routeParameters).toCompletableFuture();
                      }).whenComplete((routeResult, throwable) -> {
                        if (throwable == null) {
                          Route route = routeResult.getRoutes().get(0);
                          Graphic routeGraphic = new Graphic(route.getRouteGeometry(), lineSymbol);
                          routesGraphicsOverlay.getGraphics().add(routeGraphic);
                        } else {
                          var alert = new Alert(Alert.AlertType.WARNING, "No path found between stops");
                          alert.initOwner(mapView.getScene().getWindow());
                          alert.show();
                        }
                      });
                  }
                }
              } else {
                // show warning if reverse geocode completed with an exception
                var alert = new Alert(Alert.AlertType.WARNING, "No address found at this location");
                alert.initOwner(mapView.getScene().getWindow());
                alert.show();
              }
            });
        }
      });

      // add the map view, button, and list view to the stack pane
      stackPane.getChildren().addAll(mapView, findMmpkButton, mapPackageListView);
      StackPane.setAlignment(findMmpkButton, Pos.TOP_LEFT);
      StackPane.setAlignment(mapPackageListView, Pos.TOP_RIGHT);
      StackPane.setMargin(findMmpkButton, new Insets(10));
      StackPane.setMargin(mapPackageListView, new Insets(10));
    } catch (Exception e) {
      // on any error, display the stack trace.
      e.printStackTrace();
    }
  }

  /**
   * 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.