Find service area

View inMAUIUWPWPFWinUIView on GitHub

Find the service area within a network from a given point.

Image of find service area

Use case

A service area shows locations that can be reached from a facility based off a certain impedance, such as travel time or distance. Barriers can increase impedance by either adding to the time it takes to pass through the barrier or by altogether preventing passage.

You might calculate the region around a hospital in which ambulances can service in 30 min or less.

How to use the sample

In order to find any service areas at least one facility needs to be added to the map view.

  • To add a facility, tap the facility button, then tap anywhere on the map.
  • To add a barrier, tap the barrier button, and tap multiple locations on map. Hit the barrier button again to finish drawing barrier. Hitting any other button will also stop the barrier from drawing.
  • To show service areas around facilities that were added, tap show service areas button.
  • The reset button clears all graphics and resets the service area task.

How it works

  1. Create a new ServiceAreaTask from a network service.
  2. Create default ServiceAreaParameters from the service area task.
  3. Set the parameters to return polygons (true) to return all service areas.
  4. Add a ServiceAreaFacility to the parameters.
  5. Get the ServiceAreaResult by solving the service area task using the parameters.
  6. Get any ServiceAreaPolygons that were returned.
  7. Display the service area polygons as graphics in a GraphicsOverlay on the MapView.

Relevant API

  • PolylineBarrier
  • ServiceAreaFacility
  • ServiceAreaParameters
  • ServiceAreaPolygon
  • ServiceAreaResult
  • ServiceAreaTask

Tags

barriers, facilities, geometry editor, impedance, logistics, routing

Sample Code

FindServiceArea.xaml.csFindServiceArea.xaml.csFindServiceArea.xaml
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
// Copyright 2022 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.

using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Editing;

namespace ArcGIS.Samples.FindServiceArea
{
    [ArcGIS.Samples.Shared.Attributes.Sample(
        name: "Find service area",
        category: "Network analysis",
        description: "Find the service area within a network from a given point.",
        instructions: "In order to find any service areas at least one facility needs to be added to the map view.",
        tags: new[] { "barriers", "facilities", "geometry editor", "impedance", "logistics", "routing" })]
    public partial class FindServiceArea
    {
        // Uri for the service area around San Diego.
        private Uri _serviceAreaUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ServiceArea");

        // Hold a reference to the geometry type used in the geometry editor.
        private GeometryType _geometryType;

        public FindServiceArea()
        {
            InitializeComponent();

            // Create the map, graphics overlay, and geometry editor.
            Initialize();
        }

        private void Initialize()
        {
            // Center the map on San Diego.
            Map streetsMap = new Map(BasemapStyle.ArcGISLightGray)
            {
                InitialViewpoint = new Viewpoint(32.73, -117.14, 30000)
            };
            MyMapView.Map = streetsMap;

            // Create graphics overlays for all of the elements of the map.
            MyMapView.GraphicsOverlays.Add(new GraphicsOverlay());

            MyMapView.GeoViewDoubleTapped += (s, e) =>
            {
                // Finish the currently drawn barrier.
                if (MyMapView.GeometryEditor.IsStarted && _geometryType == GeometryType.Polyline)
                {
                    FinishBarrier();
                }
            };
        }

        private async void PlaceFacilityButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Let the user tap on the map view using the point geometry type.
                _geometryType = GeometryType.Point;

                // Start the geometry editor.
                MyMapView.GeometryEditor.Start(_geometryType);
                MyMapView.GeometryEditor.PropertyChanged += GeometryEditor_PropertyChanged;
            }
            catch (Exception ex)
            {
                // Report exceptions.
                await Application.Current.MainPage.DisplayAlert("Error", "Error drawing facility:\n" + ex.Message, "OK");
            }
        }


        private void GeometryEditor_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(GeometryEditor.Geometry) && _geometryType == GeometryType.Point)
            {
                // Disconnect event handler to prevent multiple calls.
                MyMapView.GeometryEditor.PropertyChanged -= GeometryEditor_PropertyChanged;

                // Get the active geometry.
                Geometry geometry = MyMapView.GeometryEditor.Geometry;

                // Symbology for a facility.
                PictureMarkerSymbol facilitySymbol = new PictureMarkerSymbol(new Uri("https://static.arcgis.com/images/Symbols/SafetyHealth/Hospital.png"))
                {
                    Height = 30,
                    Width = 30
                };

                // Create a graphic for the facility.
                Graphic facilityGraphic = new Graphic(geometry, new Dictionary<string, object>() { { "Type", "Facility" } }, facilitySymbol)
                {
                    ZIndex = 2
                };

                // Add the graphic to the graphics overlay.
                MyMapView.GraphicsOverlays[0].Graphics.Add(facilityGraphic);

                // Stop the geometry editor to clear the active geometry.
                MyMapView.GeometryEditor.Stop();
            }
        }

        private async void DrawBarrierButton_Click(object sender, EventArgs e)
        {
            // Finish drawing barriers if started.
            if (DrawBarrierButton.Text != "Draw barrier")
            {
                if (MyMapView.GeometryEditor.IsStarted)
                {
                    FinishBarrier();
                }
                DrawBarrierButton.Text = "Draw barrier";
                return;
            }
            try
            {
                // Update the UI.
                DrawBarrierButton.Text = "Finish drawing";

                // Let the user draw on the map view using the polyline geometry type.
                _geometryType = GeometryType.Polyline;

                // Start the geometry editor.
                MyMapView.GeometryEditor.Start(_geometryType);
            }
            catch (Exception ex)
            {
                // Report exceptions.
                await Application.Current.MainPage.DisplayAlert("Error", "Error drawing barrier:\n" + ex.Message, "OK");
            }
        }

        private void FinishBarrier()
        {
            Geometry geometry = MyMapView.GeometryEditor.Stop();

            if (!geometry.IsEmpty)
            {
                // Symbol for the barriers.
                SimpleLineSymbol barrierSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Black, 5.0f);

                // Create the graphic to be used for barriers.
                Graphic barrierGraphic = new Graphic(geometry, new Dictionary<string, object> { { "Type", "Barrier" } }, barrierSymbol)
                {
                    ZIndex = 1
                };

                // Add a graphic from the polyline the user drew.
                MyMapView.GraphicsOverlays[0].Graphics.Add(barrierGraphic);

                // Update button text.
                DrawBarrierButton.Text = "Draw barrier";
            }
        }

        private async void ShowServiceAreasButton_Click(object sender, EventArgs e)
        {
            // Finish any drawings.
            if (MyMapView.GeometryEditor.IsStarted)
            {
                FinishBarrier();
            }

            // Use a local variable for the graphics overlay.
            GraphicCollection allGraphics = MyMapView.GraphicsOverlays[0].Graphics;

            // Get a list of the facilities from the graphics overlay.
            List<ServiceAreaFacility> serviceAreaFacilities = (from g in allGraphics
                                                               where (string)g.Attributes["Type"] == "Facility"
                                                               select new ServiceAreaFacility((MapPoint)g.Geometry)).ToList();

            // Check that there is at least 1 facility to find a service area for.
            if (!serviceAreaFacilities.Any())
            {
                await Application.Current.MainPage.DisplayAlert("Error", "Must have at least one Facility!", "OK");
                return;
            }

            // Create the service area task and parameters based on the Uri.
            ServiceAreaTask serviceAreaTask = await ServiceAreaTask.CreateAsync(_serviceAreaUri);

            // Store the default parameters for the service area in an object.
            ServiceAreaParameters serviceAreaParameters = await serviceAreaTask.CreateDefaultParametersAsync();

            // Add impedance cutoffs for facilities (drive time minutes).
            serviceAreaParameters.DefaultImpedanceCutoffs.Add(2.0);
            serviceAreaParameters.DefaultImpedanceCutoffs.Add(5.0);

            // Set the level of detail for the polygons.
            serviceAreaParameters.PolygonDetail = ServiceAreaPolygonDetail.High;

            // Get a list of the barriers from the graphics overlay.
            List<PolylineBarrier> polylineBarriers = (from g in allGraphics
                                                      where (string)g.Attributes["Type"] == "Barrier"
                                                      select new PolylineBarrier((Polyline)g.Geometry)).ToList();

            // Add the barriers to the service area parameters.
            serviceAreaParameters.SetPolylineBarriers(polylineBarriers);

            // Update the parameters to include all of the placed facilities.
            serviceAreaParameters.SetFacilities(serviceAreaFacilities);

            // Clear existing graphics for service areas.
            foreach (Graphic g in allGraphics.ToList())
            {
                // Check if the graphic g is a service area.
                if ((string)g.Attributes["Type"] == "ServiceArea")
                {
                    allGraphics.Remove(g);
                }
            }

            try
            {
                // Solve for the service area of the facilities.
                ServiceAreaResult result = await serviceAreaTask.SolveServiceAreaAsync(serviceAreaParameters);

                // Loop over each facility.
                for (int i = 0; i < serviceAreaFacilities.Count; i++)
                {
                    // Create list of polygons from a service facility.
                    List<ServiceAreaPolygon> polygons = result.GetResultPolygons(i).ToList();

                    // Symbol for the outline of the service areas.
                    SimpleLineSymbol serviceOutline = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.DarkGray, 3.0f);

                    // Create a list of fill symbols for the polygons.
                    List<SimpleFillSymbol> fillSymbols = new List<SimpleFillSymbol>();
                    fillSymbols.Add(new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, System.Drawing.Color.FromArgb(70, 255, 0, 0), serviceOutline));
                    fillSymbols.Add(new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, System.Drawing.Color.FromArgb(70, 255, 165, 0), serviceOutline));

                    // Loop over every polygon in every facilities result.
                    for (int j = 0; j < polygons.Count; j++)
                    {
                        // Create the graphic for the service areas, alternating between fill symbols.
                        Graphic serviceGraphic = new Graphic(polygons[j].Geometry, new Dictionary<string, object>() { { "Type", "ServiceArea" } }, fillSymbols[j % 2])
                        {
                            ZIndex = 0
                        };

                        // Add graphic for service area. Alternate the color of each polygon.
                        allGraphics.Add(serviceGraphic);
                    }
                }
            }
            catch (Esri.ArcGISRuntime.Http.ArcGISWebException exception)
            {
                if (exception.Message.ToString().Equals("Unable to complete operation."))
                {
                    await Application.Current.MainPage.DisplayAlert("Error", "Facility not within San Diego area!", "OK");
                }
                else
                {
                    await Application.Current.MainPage.DisplayAlert("Error", "An ArcGIS web exception occurred. \n" + exception.Message, "OK");
                }
            }
        }

        private void Reset_Click(object sender, EventArgs e)
        {
            // Clear all of the graphics.
            MyMapView.GraphicsOverlays[0].Graphics.Clear();
        }
    }
}

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