SHARE
TWEET

Untitled

a guest Oct 23rd, 2019 93 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.awt.BorderLayout;
  2. import java.awt.Color;
  3. import java.awt.Component;
  4. import java.awt.EventQueue;
  5. import java.awt.FlowLayout;
  6. import java.awt.Font;
  7. import java.awt.event.ActionEvent;
  8. import java.awt.event.ActionListener;
  9. import java.awt.event.WindowAdapter;
  10. import java.awt.event.WindowEvent;
  11. import java.util.ArrayList;
  12. import java.util.HashMap;
  13.  
  14. import javax.swing.BorderFactory;
  15. import javax.swing.JButton;
  16. import javax.swing.JComponent;
  17. import javax.swing.JFrame;
  18. import javax.swing.JLabel;
  19. import javax.swing.JLayeredPane;
  20. import javax.swing.JOptionPane;
  21. import javax.swing.JPanel;
  22. import javax.swing.JScrollPane;
  23. import javax.swing.JTextArea;
  24. import javax.swing.JToolBar;
  25. import javax.swing.SwingConstants;
  26. import javax.swing.border.LineBorder;
  27.  
  28. import com.esri.core.geometry.Envelope;
  29. import com.esri.core.geometry.GeometryEngine;
  30. import com.esri.core.geometry.Polygon;
  31. import com.esri.core.map.Graphic;
  32. import com.esri.core.symbol.SimpleFillSymbol;
  33. import com.esri.core.symbol.SimpleLineSymbol;
  34. import com.esri.core.symbol.SimpleMarkerSymbol;
  35. import com.esri.core.symbol.SimpleMarkerSymbol.Style;
  36. import com.esri.core.symbol.TextSymbol;
  37. import com.esri.core.tasks.na.NAFeaturesAsFeature;
  38. import com.esri.core.tasks.na.Route;
  39. import com.esri.core.tasks.na.RouteDirection;
  40. import com.esri.core.tasks.na.RouteParameters;
  41. import com.esri.core.tasks.na.RouteResult;
  42. import com.esri.core.tasks.na.RouteTask;
  43. import com.esri.map.GraphicsLayer;
  44. import com.esri.map.JMap;
  45. import com.esri.map.MapOptions;
  46. import com.esri.map.MapOptions.MapType;
  47. import com.esri.runtime.ArcGISRuntime;
  48. import com.esri.runtime.ArcGISRuntime.RenderEngine;
  49. import com.esri.toolkit.overlays.DrawingCompleteEvent;
  50. import com.esri.toolkit.overlays.DrawingCompleteListener;
  51. import com.esri.toolkit.overlays.DrawingOverlay;
  52. import com.esri.toolkit.overlays.DrawingOverlay.DrawingMode;
  53.  
  54. public class DrivingDirections {
  55.  
  56.   private JFrame window;
  57.   private JMap map;
  58.     //graphics layer for stops and whole route
  59.     private GraphicsLayer graphicsLayer;
  60.     //graphics layer for route segment graphics
  61.     private GraphicsLayer routeSegmentsLayer;
  62.     //Symbol for routes
  63.     private SimpleLineSymbol routeSymbol = new SimpleLineSymbol(Color.BLUE, 5);
  64.     //Overlay to draw your route stops
  65.     private final DrawingOverlay myDrawingOverlay;
  66.     //object to perform routing
  67.     private RouteTask task;
  68.     //stop graphics
  69.     private NAFeaturesAsFeature stops = new NAFeaturesAsFeature();
  70.     private NAFeaturesAsFeature barriers = new NAFeaturesAsFeature();
  71.     private NAFeaturesAsFeature polygonBarriers = new NAFeaturesAsFeature();
  72.     // routing service
  73.     private static final String ROUTE_URL = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route";
  74.     // solve button string
  75.     private static final String SOLVE_BUTTON = " Solve route ";
  76.     // stop button string
  77.     private static final String STOP_BUTTON = " Add a stop ";
  78.     // turn-by-turn button string
  79.     private static final String TURN_BUTTON = " Turn by turn ";
  80.     // reset button string
  81.     private static final String RESET_BUTTON = " Reset ";
  82.    
  83.     private static final String BARRIERS_BUTTON = "Add a barrier";
  84.    
  85.     private static final String POLYGON_BUTTON = "Add a polygon barrier";
  86.    
  87.    
  88.    
  89.     // text area to display directions
  90.     private JTextArea directionText;
  91.     // turn by turn button
  92.     private JButton stepsButton;
  93.  
  94.     private int numStops = 0;
  95.     private int numBarriers = 0;
  96.     private int numPolygon = 0;
  97.     private int stepRoute = 0;
  98.     ArrayList<Integer> stepIDs = new ArrayList<Integer>();
  99.    
  100.  
  101.   public DrivingDirections() {
  102.     window = new JFrame();
  103.     window.setSize(800, 600);
  104.     window.setLocationRelativeTo(null); // center on screen
  105.     window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  106.     window.getContentPane().setLayout(new BorderLayout(0, 0));
  107.  
  108.     // dispose map just before application window is closed.
  109.     window.addWindowListener(new WindowAdapter() {
  110.       @Override
  111.       public void windowClosing(WindowEvent windowEvent) {
  112.         super.windowClosing(windowEvent);
  113.         map.dispose();
  114.       }
  115.     });
  116.  
  117.     // Before this application is deployed you must register the application on
  118.     // http://developers.arcgis.com and set the Client ID in the application as shown
  119.     // below. This will license your application to use Basic level functionality.
  120.     //
  121.     // If you need to license your application for Standard level functionality, please
  122.     // refer to the documentation on http://developers.arcgis.com
  123.     //
  124.     //ArcGISRuntime.setClientID("your Client ID");
  125.     ArcGISRuntime.setRenderEngine(RenderEngine.OpenGL);
  126.  
  127.     // Using MapOptions allows for a common online basemap to be chosen
  128.     MapOptions mapOptions = new MapOptions(MapType.TOPO);
  129.     map = new JMap(mapOptions);
  130.  
  131.     // If you don't use MapOptions, use the empty JMap constructor and add a tiled layer
  132.     //map = new JMap();
  133.     //ArcGISTiledMapServiceLayer tiledLayer = new ArcGISTiledMapServiceLayer(
  134.     //  "http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer");
  135.     //map.getLayers().add(tiledLayer);
  136.    
  137.  // set map extent to San Diego
  138.     map.setExtent(new Envelope(-13054452, 3847753, -13017762, 3866957.78));
  139.  
  140.     // Graphics layers initialization
  141.     graphicsLayer = new GraphicsLayer();
  142.     routeSegmentsLayer = new GraphicsLayer();
  143.     routeSegmentsLayer.setSelectionColor(Color.RED);
  144.  
  145.     // add segments route layer first
  146.     map.getLayers().add(routeSegmentsLayer);
  147.     // add stops/route layer next, so that stops display above segments
  148.     map.getLayers().add(graphicsLayer);
  149.    
  150.  // create drawing overlay and add to map
  151.     myDrawingOverlay = new DrawingOverlay();
  152.     myDrawingOverlay.addDrawingCompleteListener(new DrawingCompleteListener() {
  153.  
  154.           @Override
  155.           public void drawingCompleted(DrawingCompleteEvent event) {
  156.             // get the user-drawn stop graphic from the overlay
  157.               Graphic graphic = (Graphic) myDrawingOverlay.getAndClearFeature();
  158.               // add it to the graphicsLayer for display
  159.               graphicsLayer.addGraphic(graphic);
  160.               // add to stops list for route task
  161.               if (graphic.getAttributeValue("type").equals("Stop"))
  162.               {
  163.                   stops.addFeature(graphic);
  164.                   numStops++;
  165.                   Graphic textGraphic = new Graphic(
  166.                         graphic.getGeometry(), new TextSymbol(12, String.valueOf(numStops), Color.WHITE), 1);
  167.                         graphicsLayer.addGraphic(textGraphic);  
  168.               }              
  169.               else if (graphic.getAttributeValue("type").equals("Barrier"))
  170.               {
  171.                   barriers.addFeature(graphic);
  172.                   numBarriers++;
  173.                   Graphic textGraphic = new Graphic(
  174.                             graphic.getGeometry(), new TextSymbol(12, String.valueOf(numBarriers), Color.RED), 1);
  175.                           graphicsLayer.addGraphic(textGraphic);  
  176.               }
  177.               else
  178.               {
  179.                   polygonBarriers.addFeature(graphic);
  180.                   numPolygon++;
  181.                   Graphic textGraphic = new Graphic(
  182.                         graphic.getGeometry(), new TextSymbol(12, String.valueOf(numPolygon), Color.RED), 1);
  183.                       graphicsLayer.addGraphic(textGraphic);  
  184.               }
  185.                  
  186.              
  187.           }
  188.         });
  189.     map.addMapOverlay(myDrawingOverlay);
  190.  
  191.     // Add the JMap to the JFrame's content pane
  192.     window.getContentPane().add(map);
  193.    
  194.     JLayeredPane contentPane = new JLayeredPane();
  195.     contentPane.setLayout(new BorderLayout());
  196.     contentPane.setVisible(true);
  197.     window.add(contentPane);
  198.    
  199.     contentPane.add(createPanel());
  200.     contentPane.add(map);
  201.     contentPane.add(createToolBar(myDrawingOverlay), BorderLayout.NORTH);
  202.    
  203.     try {
  204.           task = RouteTask.createOnlineRouteTask(ROUTE_URL, null);
  205.         } catch (Exception e) {
  206.           e.printStackTrace();
  207.           JOptionPane.showMessageDialog(map.getParent(),
  208.             "An error has occurred. " + e.getLocalizedMessage());
  209.         }
  210.  
  211.   }
  212.  
  213.   private Component createToolBar(DrawingOverlay drawingOverlay) {
  214.      
  215.       JToolBar toolBar = new JToolBar();
  216.       toolBar.setLayout(new FlowLayout(FlowLayout.CENTER));
  217.  
  218.       // add stops button
  219.       final JButton stopButton = new JButton(STOP_BUTTON);
  220.       stopButton.addActionListener(new ActionListener() {
  221.           @Override
  222.           public void actionPerformed(ActionEvent e) {
  223.             // Add a new stop graphic in the map overlay
  224.             HashMap<String, Object> attributes = new HashMap<String, Object>();
  225.             attributes.put("type", "Stop");
  226.             drawingOverlay.setUp(
  227.                 DrawingMode.POINT,
  228.                 new SimpleMarkerSymbol(Color.BLUE, 25, Style.CIRCLE),
  229.                 attributes);
  230.           }
  231.         });
  232.       toolBar.add(stopButton);
  233.      
  234.     // add stops button
  235.           final JButton barriersButton = new JButton(BARRIERS_BUTTON);
  236.           barriersButton.addActionListener(new ActionListener() {
  237.               @Override
  238.               public void actionPerformed(ActionEvent e) {
  239.                 // Add a new stop graphic in the map overlay
  240.                 HashMap<String, Object> attributes = new HashMap<String, Object>();
  241.                 attributes.put("type", "Barrier");
  242.                 drawingOverlay.setUp(
  243.                     DrawingMode.POINT,
  244.                     new SimpleMarkerSymbol(Color.BLACK, 25, Style.X),
  245.                     attributes);
  246.               }
  247.             });
  248.           toolBar.add(barriersButton);
  249.          
  250.         // add stops button
  251.           final JButton polygonButton = new JButton(POLYGON_BUTTON);
  252.           polygonButton.addActionListener(new ActionListener() {
  253.               @Override
  254.               public void actionPerformed(ActionEvent e) {
  255.                 // Add a new stop graphic in the map overlay
  256.                 HashMap<String, Object> attributes = new HashMap<String, Object>();
  257.                 attributes.put("type", "Polygon");
  258.                 drawingOverlay.setUp(
  259.                     DrawingMode.POLYGON,
  260.                    new SimpleFillSymbol(Color.CYAN), attributes);
  261.               }
  262.             });
  263.           toolBar.add(polygonButton);  
  264.  
  265.       // solve route button
  266.       final JButton solveRouteButton = new JButton(SOLVE_BUTTON);
  267.       solveRouteButton.addActionListener(new ActionListener() {
  268.           @Override
  269.           public void actionPerformed(ActionEvent e) {
  270.             // disable the toolbar buttons and overlay
  271.             stopButton.setEnabled(false);
  272.             solveRouteButton.setEnabled(false);
  273.             myDrawingOverlay.setEnabled(false);
  274.             // enable turn by turn button
  275.             stepsButton.setEnabled(true);
  276.             doRouting();
  277.           }
  278.          
  279.        
  280.  
  281.         private void doRouting() {
  282.             // initialise route results and parameters
  283.             RouteResult result = null;
  284.             RouteParameters parameters = null;
  285.             try {
  286.               parameters = task.retrieveDefaultRouteTaskParameters();
  287.               parameters.setOutSpatialReference(map.getSpatialReference());
  288.               stops.setSpatialReference(map.getSpatialReference());
  289.               barriers.setSpatialReference(map.getSpatialReference());
  290.               polygonBarriers.setSpatialReference(map.getSpatialReference());
  291.               parameters.setStops(stops);
  292.               parameters.setPointBarriers(barriers);
  293.               parameters.setPolygonBarriers(polygonBarriers);
  294.               // set parameter to return turn by turn directions
  295.               parameters.setReturnDirections(true);
  296.               result = task.solve(parameters);
  297.               showResult(result);
  298.             } catch (Exception e) {
  299.               e.printStackTrace();
  300.               JOptionPane.showMessageDialog(map.getParent(),
  301.                 "An error has occurred. " + e.getLocalizedMessage());
  302.             }
  303.            
  304.         }
  305.  
  306.         private void showResult(RouteResult result) {
  307.               if (result != null) {
  308.                 // get the routing directions from the top route
  309.                 Route topRoute = result.getRoutes().get(0);
  310.                 topRoute.getRoutingDirections();
  311.  
  312.                 // add route segments to the route layer
  313.                 for (RouteDirection rd : topRoute.getRoutingDirections()) {
  314.                   HashMap<String, Object> attribs = new HashMap<String, Object>();
  315.                   attribs.put("text", rd.getText());
  316.                   attribs.put("time", Double.valueOf(rd.getMinutes()));
  317.                   attribs.put("length", Double.valueOf(rd.getLength()));
  318.                   Graphic a = new Graphic(rd.getGeometry(), routeSymbol, attribs);
  319.                   int graphicID = routeSegmentsLayer.addGraphic(a);
  320.                   stepIDs.add(Integer.valueOf(graphicID));
  321.                 }
  322.  
  323.                 // add the whole-route graphic
  324.                 Graphic routeGraphic = new Graphic(topRoute.getRouteGraphic().getGeometry(),
  325.                     new SimpleLineSymbol(Color.BLUE, 2.0f), 0);
  326.                 graphicsLayer.addGraphic(routeGraphic);
  327.              // Get the full route summary and show in text area
  328.                 String routeSummary = String.format(
  329.                   "%s%nTotal time: %.1f minutes %nLength: %.1f miles",
  330.                   topRoute.getRouteName(), Double.valueOf(topRoute.getTotalMinutes()),
  331.                   Double.valueOf(topRoute.getTotalMiles()));
  332.                 directionText.setText(routeSummary);
  333.  
  334.                 // Zoom to the extent of the whole route plus a 500m buffer
  335.                 Polygon bufferedExtent = GeometryEngine.buffer(
  336.                   topRoute.getEnvelope(), map.getSpatialReference(), 500, null);
  337.                 map.setExtent(bufferedExtent);
  338.               }
  339.               else {
  340.                 JOptionPane.showMessageDialog(map.getParent(), "No route found!");
  341.               }
  342.             }
  343.         });
  344.       toolBar.add(solveRouteButton);
  345.  
  346.       // reset button
  347.       JButton resetButton = new JButton(RESET_BUTTON);
  348.       resetButton.addActionListener(new ActionListener() {
  349.           @Override
  350.           public void actionPerformed(ActionEvent e) {
  351.             // enable the toolbar buttons and overlay  
  352.             stopButton.setEnabled(true);
  353.             solveRouteButton.setEnabled(true);
  354.             myDrawingOverlay.setEnabled(true);
  355.             // disable the turn by turn button
  356.             stepsButton.setEnabled(false);
  357.             // reset graphic layers, stop features and global variables
  358.             directionText.setText("");
  359.             graphicsLayer.removeAll();
  360.             routeSegmentsLayer.removeAll();
  361.             stops.clearFeatures();
  362.             stepIDs.clear();
  363.             numStops = 0;
  364.             stepRoute = 0;
  365.           }
  366.         });
  367.       toolBar.add(resetButton);
  368.      
  369.       return toolBar;
  370. }
  371.  
  372. private Component createPanel() {
  373.     // driving directions panel
  374.     JComponent panel = new JPanel();
  375.     panel.setLocation(10, 50);
  376.     panel.setBackground(new Color(0, 0, 0, 100));
  377.     panel.setBorder(new LineBorder(Color.BLACK, 1, false));
  378.     panel.setLayout(new BorderLayout());
  379.     panel.setSize(200, 150);
  380.  
  381.     // panel title
  382.     JLabel txtTitle = new JLabel("Driving Directions");
  383.     txtTitle.setHorizontalAlignment(SwingConstants.CENTER);
  384.     txtTitle.setFont(new Font(txtTitle.getFont().getName(), Font.BOLD, 14));
  385.     txtTitle.setAlignmentX(Component.CENTER_ALIGNMENT);
  386.     txtTitle.setForeground(Color.WHITE);
  387.  
  388.     // scrolling text area to display direction text
  389.     directionText = new JTextArea();
  390.     directionText.setLineWrap(true);
  391.     directionText.setWrapStyleWord(true);
  392.     directionText.setEditable(false);
  393.     directionText.setBorder(BorderFactory.createEmptyBorder(15,15,15,15));
  394.     JScrollPane scrollPane = new JScrollPane(directionText);
  395.  
  396.     // button - when clicked, show turn by turn directions
  397.     stepsButton = new JButton(TURN_BUTTON);
  398.     stepsButton.addActionListener(new ActionListener() {
  399.          
  400.           @Override
  401.           public void actionPerformed(ActionEvent e) {
  402.               doTurnByTurn();  
  403.           }
  404.  
  405.         private void doTurnByTurn() {
  406.             // check there is a next step in the route
  407.             if (stepRoute < routeSegmentsLayer.getNumberOfGraphics()) {
  408.               Graphic selected = routeSegmentsLayer.getGraphic(stepIDs.get(stepRoute).intValue());  
  409.               // Highlight route segment on the map
  410.               routeSegmentsLayer.select(stepIDs.get(stepRoute).intValue());
  411.               String direction = ((String) selected.getAttributeValue("text"));
  412.               Double time = (Double) selected.getAttributeValue("time");
  413.               Double length = (Double) selected.getAttributeValue("length");
  414.               // Update the label with this direction's information
  415.               String label = String.format("%s%nTime: %.1f minutes, Length: %.1f miles",
  416.                 direction, time, length);
  417.               directionText.setText(label);
  418.               stepRoute++;
  419.             } else {
  420.               directionText.setText("End of route");
  421.               stepsButton.setEnabled(false);
  422.             }
  423.         }
  424.         });
  425.     // group the above UI items into the JPanel
  426.     panel.add(txtTitle, BorderLayout.NORTH);
  427.     panel.add(scrollPane, BorderLayout.CENTER);
  428.     panel.add(stepsButton, BorderLayout.SOUTH);
  429.    
  430.     return panel;
  431. }
  432.  
  433. /**
  434.    * Starting point of this application.
  435.    * @param args
  436.    */
  437.   public static void main(String[] args) {
  438.     EventQueue.invokeLater(new Runnable() {
  439.  
  440.       @Override
  441.       public void run() {
  442.         try {
  443.           DrivingDirections application = new DrivingDirections();
  444.           application.window.setVisible(true);
  445.         } catch (Exception e) {
  446.           e.printStackTrace();
  447.         }
  448.       }
  449.     });
  450.   }
  451. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top