Skip To Content

Service Area task

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 to be performed. A Service Area task relies on a Service Area analysis layer.

Learn about creating Network Analyst services

Creating a Service Area task

To instantiate a Service Area task, you need to provide a URL to a REST resource that represents a Service Area layer in a Network Analyst service. If the service is secured, you also need to provide the credentials that can be used to access the service. The following code snippet shows how to create a Service Area task for 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)

Note:

When you create the task, you need to ensure its memory does not get deallocated before it has a chance to execute. To do this, you need to retain the task if you're using manual retain-release, or create a strong reference to it if you're using ARC. See Apple's Memory Management Programming Guide for more information on how to manage object memory.

Preparing the input

You provide input to the Service Area task using an object of the AGSServiceAreaTaskParameters class. You can instantiate a new AGSServiceAreaTaskParameters object and modify its properties to provide the input. But many times, you may want to calculate service areas using the defaults specified in the service. In such cases, you first need to 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's used to constrain the service area. For example, impedance can be set to Time to calculate a service area that encompasses all accessible streets within that time interval. Or it can 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

In the previous example, Length and Time are supported impedances. The following code snippet sets 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 be calculated. For example, if you apply breaks of 5, 10, and 15 when the impedance is set to Time, the service area will include those streets than 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 own breaks. If you're computing service areas for a number of facilities in a batch, you can 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 can be set as a facility to find which areas it can serve within a 10 minute service area. A hospital can be set as the facility to find what proportion of the population is within a 2 mile driving distance.

There are two ways to specify facilities: features and layer definition.

Features

You can create an array of AGSFacilityGraphic objects representing facility features. You can then assign these features to the parameter object using setFacilitiesWithFeatures:. At a minimum, you need to provide a name and a point geometry for each facility, but 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 Classes > Class Name:Facilities section of the Services Directory.

Attributes of facilities

Attributes can 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 Breaks_<Impedance> where <impedance> is the value specified in the impedance property. For example, an attribute of name Breaks_Time with a value of "5 10 15" specifies service areas of 5, 10, and 15 minutes 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 along 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

Layer definition

In addition to specifying facilities by value (that is, providing the actual value for each feature as previously described), you can also specify them by reference. This is useful when you already have a set of well known or commonly used facilities stored along 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 should be included 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 should be used in the analysis. For example, the following code snippet sets up a layer definition referencing features that fall within the City of 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 set up a layer definition identifying the features to use, you can 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 that the service area should avoid toll roads. If the analysis is for an emergency vehicle, you can specify that rules governing one-way streets should be relaxed. The restrictions supported by the service are listed in the Services Directory under Network Dataset > Network Attributes with a Usage Type of esriNAUTRestriction.

Restrictions

The following code snippet applies restrictions in order 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 the traffic. This can be represented by a barrier that allows travel along the freeway but increases the travel time required.

As with facilities, there are two ways to specify barriers: features and layer definition

Features

You can create an array of AGSGraphic objects representing barrier features. You need to provide these features a geometry representing the location and shape of the barrier. 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 type of geometry that was assigned to the feature.

Note:

You need to 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, PolygonBarriers section of the Services Directory. Attributes can 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

In addition to specifying barriers by value (that is, providing the actual value for each feature as previously described), you can also specify barriers by reference. This is useful when you already have a set of well known or commonly used barriers stored along with the Network Analyst service. For instance, the transportation department of a city 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 actual details about each barrier. All it needs to do is set up a layer definition specifying which barriers should be included in the analysis.

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

U-turn policy

You can 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 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 direction of travel, this results in different service areas. The direction you 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

Polygon options

You can 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-like network, the difference between generalized and detailed polygons is 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 5- and 10-minute service areas, the 10-minute service area polygon will include the area under the 5-minute service area polygon as well as the area from the 5-minute to the 10-minute break.

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

Line options

You can also 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 split lines that span multiple breaks by setting the splitLinesAtBreaks property. You can also generate overlapping or non-overlapping lines by setting the overlapLines property.

Geometry options

You can request the geometry of the service areas be generalized by modifying the outputGeometryPrecision and outputGeometryPrecisionUnits properties on AGSServiceAreaTaskParameters. Generalizing a geometry removes vertices that add more detail beyond the precision you specify. Removing vertices makes the geometry smaller, saving time needed to transfer the geometry over the network and also faster to draw as a map graphic.

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

Calculating service areas

Once you set up the input parameters, calculating service areas is as simple as invoking solveServiceAreaWithParameters: on AGSServiceAreaTask and passing 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.

Retrieving results and handling errors

The Service Area task informs its delegate when operations complete successfully or when errors are encountered. To get results from the task and to properly handle any errors, you must set one of your classes as the task's delegate. You do this by making your class (typically the view controller that uses the task) adopt the AGSServiceAreaTaskDelegate protocol.

class MyViewController: UIViewController, 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 that the task performs.

saTask.delegate = self

Finally, your class should implement one or more methods defined in the protocol that pertain to the operation being performed. 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
}
Note:

If your delegate methods are not being invoked when the task finishes execution, check to make sure that the task is not getting deallocated prematurely. You need to retain the task if you're using manual retain-release, or create a strong reference to it if you're using ARC.

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

  • 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 any warnings or errors encountered while calculating the service areas.

Note:

It is a good practice to inspect the messages, at least during development, as it can help troubleshoot any potential problems.

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

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

Note:

If your delegate methods are not being invoked when the task finishes execution, check to make sure that the task is not getting deallocated before it finishes execution. You need to retain the locator if you're using manual retain-release, or create a strong reference to it if you're using ARC.

See also