Skip To Content

Calculate a service area

In this topic

A Service area task allows you to calculate areas that can be serviced (reached) from a given location using ArcGIS Network Analyst services.

A Network Analyst service contains one or more network analysis layers. ArcGIS provides different types of analysis layers, such as route, service area, closest facility, and so on, depending on the type of analysis performed. A service area task relies on a service area analysis layer.

Learn about creating Network Analyst services.

Create a service area task

To instantiate a service area task, provide a URL to the REST resource that represents a service area layer in a Network Analyst service. If the service is secured, provide the credentials used to access the service. The following code snippet shows how to create a service area task for the service area layer in the USA service on an ArcGIS Online sample server.

let url = NSURL(string: "http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Network/USA/NAServer/Service%20Area")
let saTask = AGSServiceAreaTask(URL: url)

When you create the task, ensure you take ownership of it. Otherwise, its memory might get deallocated before it has a chance to execute. If you instantiate the task using alloc as shown above, you automatically have ownership. However, if you instantiate the task using a convenience constructor, for instance serviceAreaTaskWithURL:, explicitly take ownership by assigning it to a property that retains it.

When you finish using the task, relinquish ownership so that its memory can be reclaimed. Do this by setting the corresponding property to nil.

For more information on how tasks work please read the Tasks overview topic.

Note:

Please refer to Apple's Memory Management Programming Guide for more information on how to manage object memory.

Prepare the input

Provide input to the service area task using an object of the AGSServiceAreaTaskParameters class. Instantiate a new AGSServiceAreaTaskParameters object and modify its properties to provide the input. However, you may want to calculate service areas using the defaults specified in the service. In such cases, invoke retrieveDefaultServiceAreaTaskParameters on AGSServiceAreaTask to get the default values. The default values are returned to the task's delegate as an AGSServiceAreaTaskParameters object via the serviceAreaTask:operation:didRetrieveDefaultServiceAreaTaskParameters: method.

The following sections describe some of the inputs you can provide to a service area task.

Impedance

Impedance specifies a cost that is used to constrain the service area. For example, impedance could be set to Time to calculate a service area that encompasses all accessible streets in that time interval, or it could be set to Length to calculate a service area that encompasses all streets reachable within that distance. Impedances supported by the service are listed in the services directory under Network Dataset > Network Attributes with a Usage Type of esriNAUTCost

Impedances
Impedances

In the example shown above, Length and Time are supported impedances. The following code snippets set the impedance to Time.

let params:AGSServiceAreaTaskParameters = ...
params.impedanceAttributeName = "Time"

Breaks

Breaks specify the quantity of the impedance to apply. They constrain the extent of the service area to calculate. For example, if you apply breaks of 5, 10, and 15 when the impedance is set to Time, the service area includes all those streets that can be reached within 5, 10, and 15 minutes.

let breaks = [5, 10, 15]
params.defaultBreaks = breaks

The breaks you specify in the defaultBreaks property are applied to all facilities that don't contain their breaks. If you are computing service areas for several facilities in a batch, provide different breaks for each facility by setting their attributes accordingly.

Facilities

Facilities represent locations from which service areas need to be calculated. For example, a fire station could be set as a facility to find areas it can serve within a 10 minute service area. A hospital could be set as the facility to determine what proportion of the population is within a two mile driving distance.

There are two ways to specify facilities:

Features

You can create an array of AGSFacilityGraphic objects representing facility features. You can then assign these features to the parameter object using setFacilitiesWithFeatures:. Minimally provide a name and point geometry for each facility. You can also provide additional attributes depending on how the service area layer in the Network Analyst service is configured. These attributes are listed in the Network Analysis > Class Name: Facilities section on the services directory.

Attributes
Attributes of facilities

Attributes may be of type input, output, or both. Input attributes are specified by the client and are taken into consideration by the service while performing the analysis. For example, you can set breaks on each facility if you want to compute different service areas for different facilities. The attribute should have a name of Breaks_<Impedance> where <impedance> is the value specified in the impedance property. For example, an attribute of the name Breaks_Time with a value of 5 10 14 specifies service areas of 5, 10, and 15 mintue intervals. If the attribute is not specified, the defaultBreaks property is used to calculate service areas for the facility.

Output attributes are returned by the service with the computed result when you enable returnFacilities on AGSServiceAreaTaskParameters. Output attributes provide additional information about facilities pertaining to the results.

Some attributes can be both input and output. These attributes are specified by the client but can be modified or overridden by the service.

Learn more about attributes supported by facility features.

The symbol and infoTemplateDelegate properties on AGSFacilityGraphic are relevant only if you add the facilities to a graphics layer to display them on a map. They are not used in the analysis.

Layer definition

Apart from specifying facilities by value (that is, providing the values for each feature as described above), you can also specify them by reference. This is useful when you already have a set of well known or commonly used facilities stored with the Network Analyst service. In such cases, the application does not need to know the actual details about each facility. All it needs to do is set up a layer definition specifying which facilities to include in the analysis.

A layer definition is represented by an object of the AGSNALayerDefinition class. You can use SQL statements and/or spatial relationships to specify which facilities to use in the analysis. For example, the following code snippets set up a layer definition referencing features that fall within the Los Angeles and have a value of Hospital for the facility_type attribute.

let layerDef = AGSNALayerDefinition()
layerDef.layerName = "<layer_in_the_service_containing_stops>"
layerDef.whereClause = "delivery_type = 'Overnight'"
layerDef.geometry = losangelesPolygon
layerDef.spatialRelationship = .Contains

Once you have set up a layer definition identifying the features you want to use, use it to specify facilities using the setFacilitiesWithLayerDefinition: method on an AGSServiceAreaTaskParameters object.

params.setFacilitiesWithLayerDefinition(layerDef)

Restrictions

Restrictions allow you to place constraints on the analysis. For example, you can specify the service area should avoid toll roads. If the analysis is for an emergency vehicle, you can specify that rules governing one-way streets are relaxed. The restrictions supported by the service are listed on the services directory under Network Dataset > Network Attributes with a Usage TypeUsage Type of esriNAUTRestriction.

Restrictions
Restrictions

The following code snippet applies restrictions to avoid passenger ferries and toll roads.

params.restrictionAttributeNames = ["Avoid Ferries", "Avoid Toll Roads"]

Barriers

Barriers represent ad hoc restrictions that must be taken into consideration when calculating a service area. A barrier can specify a set of roads or a region that must be completely avoided. For example, a bridge that may be closed due to construction work. Some barriers may permit travel through them albeit at an added cost. For example, an accident on a freeway may temporarily slow down traffic. This can be represented by a barrier that allows travel along the freeway but increases the required travel time.

Just as with facilities, there are two ways to specify barriers:

Features

You can create an array of AGSGraphic objects representing barrier features. Provide these features a geometry representing the location and shape. The geometry can be a point, polyline, or polygon. You can then assign these barrier features to the parameter object using setPointBarriersWithFeatures:, setPolylineBarriersWithFeatures:, or setPolygonBarriersWithFeatures: depending on the feature's assigned geometry type.

Note:

Create separate arrays for point, polyline, and polygon barriers.

A barrier can also have additional attributes depending on how the service area layer in the Network Analyst service is configured. These attributes are listed in the Network Analysis Classes > Class Name: Barriers, PolylineBarriers, Polygon Barriers section on the services directory. Attributes may be of type input (specified by the client), output (returned by the server), or both.

Learn more about barriers and the attributes supported by point, polyline, and polygon barrier features.

Layer definition

Apart from specifying barriers by value (that is, providing the values for each feature as described above), you can also specify barriers by reference. This is useful when you already have a set of well known or commonly used barriers stored with the Network Analyst service. For instance, a city's transportation department could provide a Network Analyst service containing information about barriers representing the most recent traffic conditions, incidents, construction work, and so on. In such cases, the application does not need to know the details about each barrier. All it needs to do is set up a layer definition specifying which barriers should to include in the analysis.

Once you have set up a layer definition identifying the features you want to use, use it to specify barriers using the setPointBarriersWithLayerDefinition:, setPolylineBarriersWithLayerDefinition:, or setPolygonBarriersWithLayerDefinition: methods on an AGSServiceAreaTaskParameters object.

U-turn policy

Specify if U-turns are allowed everywhere (AGSNAUTurnAllowBacktrack), nowhere (AGSNAUTurnNoBacktrack), only at dead ends (AGSNAUTurnAtDeadEndsOnly), or only at intersections and dead ends (AGSNAUTurnAtDeadEndsAndIntersections). Allowing U-turns implies the vehicle can turn around at a junction and double back on the same street.

Learn more about U-turns.

The following code snippet allows U-turns only at dead ends and intersections :

params.uTurns = .AtDeadEndsAndIntersections

Travel direction

You can choose to create a service area by accumulating impedance in the direction away from or toward the facility. On a network with one-way restrictions and different impedances based on travel direction, this results in different service areas. The direction you should choose depends on the nature of your service area analysis. The service area for a pizza delivery store, for example, should be created away from the facility since pizzas are delivered from the store to the customer. Alternatively, a hospital should choose the opposite direction, since the urgent part of the trip for an incoming patient is going to the hospital, not returning home afterwards.

params.travelDirection = .ToFacility

Result options

The following discusses result options.

Polygon options

You can choose to generate service areas as detailed or simplified polygons by setting the outputPolygons property on AGSServiceAreaTaskParameters. Detailed polygons take significantly longer to generate but more accurately represent the service area. Simplified polygons can be generated quickly and are reasonably accurate, except at the outer edges. If your data is of an urban area with a grid network, the difference between generalized and detailed polygons are minimal. However, for mountain and rural roads, the detailed polygons may present significantly more accurate results than generalized polygons.

If you use more than one break for generating service areas, you can create concentric service area polygons as disks or rings by setting the splitPolygonsAtBreaks property. Rings are created when you set the property to YES. Rings do not include the area of smaller breaks. This creates polygons going between consecutive breaks. Disks are polygons going from a facility to a break. If you create five and 10 minute service areas, the 10 minute service area polygon includes the area under the five minute service area polygon, as well as the area from the five minute to the 10 minute break.

If you include multiple facilities in the analysis, you can also choose to generate overlapping or non-overlapping polygons by setting the overlapPolygons property. You can also choose to join the polygons of multiple facilities that have the same break values by setting the mergeSimilarPolygonRanges property.

Line options

You can also choose to generate service areas as lines instead of, or in addition to, polygons by setting the outputLines property on AGSServiceAreaTaskParameters. Lines can be straight or true shape. Straight lines are based on " as the crow flies" directions, whereas true shape lines follow the underlying transportation network.

As with polygons, you can choose to split lines that span multiple breaks by setting the splitLinesAtBreaks property. You can also choose to generate overlapping or non-overlapping lines by setting the overlapLines property.

Geometry options

Request for the geometry of the service area to be generalized by modifying the outputGeometryPrecision and outputGeometryPrecisionUnits properties on AGSServiceAreaTaskParameters. Generalizing a geometry removes vertices that add more detail beyond the specified precision. Removing vertices make the geometry smaller, saves time when transferring the geometry over the network, and also draws the geometry faster as a map graphic.

You can also request the geometry to project into a coordinate system of your choice by setting the outSpatialReference property in AGSServiceAreaTaskParameters. This may be useful if your map's spatial reference is different from the spatial reference of the service. If you do not specify an outSpatialReference property, by default, the geometries return in the service's spatial reference.

Calculate service areas

Once you set up the input parameters, calculate service areas by invoking solveServiceAreaWithParameters: on AGSServiceAreaTask and pass in the AGSServiceAreaTaskParameters object to use in the calculation.

let op = saTask.solveServiceAreaWithParameters(params)
The method returns an NSOperation object that you can use to cancel the operation if, for instance, the user is no longer interested in the results of the task.

Retrieve results and handle errors

The service area task informs its delegate when operations complete successfully or when errors occur. To get results from the task and to properly handle errors, set one of your classes as the task's delegate. Do this by making your class (typically the view controller that uses the task) adopt the AGSServiceAreaTaskDelegate protocol.

class MyViewController: NSViewController, AGSServiceAreaTaskDelegate {
 ...   
}

An instance of your class must also be set as the task's delegate. This allows the task to invoke methods on your class in response to operations the task performs.

saTask.delegate = self

Finally, your class should implement one or more methods defined in the protocol that pertains to the performed operation . There are a pair of methods for every type of operation: one for success and the other for failure. For instance, the delegate should implement the serviceAreaTask:operation:didSolveServiceAreaWithResult: method for when the operation completes successfully. Results are passed to the delegate method as an AGSServiceAreaTaskResult object.

func serviceAreaTask(serviceAreaTask: AGSServiceAreaTask!, operation op: NSOperation!, didSolveServiceAreaWithResult serviceAreaTaskResult: AGSServiceAreaTaskResult!) {
 //process the results
}

An AGSServiceAreaTaskResult object represents the results of the operation. It contains:

  • An array of polygons and/or lines representing the service areas
  • An array of graphics representing the facilities used in the analysis (if you enabled returnFacilities on AGSServiceAreaTaskParameters). Each graphic contains attributes that correspond to facility properties. These properties provide valuable information about the facility as it pertains to the computed service areas.

The AGSServiceAreaTaskResult object also contains an array of messages providing information about warnings or errors encountered while calculating the service areas.

Note:

Inspect the messages, at least during development, to troubleshoot potential problems.

The delegate should also implement the serviceAreaTask:operation:didFailSolveWithError: method to be informed when an error occurs. The error is passed into the method as an NSError object.

func serviceAreaTask(serviceAreaTask: AGSServiceAreaTask!, operation op: NSOperation!, didFailSolveWithError error: NSError!) {
 println("Error : \(error)")
}