Skip To Content

Closest Facility task

In this topic

A Closest Facility task allows you to find facilities that are closest to a given incident using ArcGIS Network Analyst services.

A Network Analyst (NA) service contains one or more Network Analysis layers. ArcGIS provides various types of analysis layers, such as Route, Service Area, Closest Facility, and so on, depending on the type of analysis to be performed. A Closest Facility task relies on a NA service that contains a Closest Facility analysis layer.

Learn about creating Network Analyst services

Finding the closest hospital to an accident, the closest police cars to a crime scene, and the closest store to a customer's address are all examples of closest facility problems. When finding closest facilities, you can specify how many to find and whether the direction of travel is toward or away from the facility. Once you've found the closest facilities, you can display the best route to or from them, return the travel cost for each route, and display directions to each facility. Additionally, you can specify an impedance cutoff beyond which a facility should not be searched. For instance, you can set up a closest facility problem to search for hospitals within 15 minutes' drive time of the site of an accident. Any hospitals that take longer than 15 minutes to reach will not be included in the results.

Creating a Closest Facility task

To instantiate a Closest Facility task, you need to provide a URL to a REST resource that represents a Closest Facility 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 Closest Facility task to use the USA service on an ArcGIS Online sample server:

let url = NSURL(string: "http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Network/USA/NAServer/Closest%20Facility")
let cfTask = AGSClosestFacilityTask(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 Memory Management Programming Guide for more information on how to manage object memory.

Preparing the input

You provide input to the Closest Facility task using an object of the AGSClosestFacilityTaskParameters class. You can instantiate a new AGSClosestFacilityTaskParameters object and modify its properties to provide the input. But many times, you may want to use the defaults specified in the service. In such cases, you first need to invoke retrieveDefaultClosestFacilityTaskParameters on AGSClosestFacilityTask to get the default values. The default values are returned to the task's delegate as an AGSClosestFacilityTaskParameters object via the closestFacilityTask:operation:didRetrieveDefaultClosestFacilityTaskParameters: method.

The following sections describe some of the inputs you can provide to a Closest Facility task.

Impedance

Impedance specifies a cost that should be minimized when finding the closest facility. For example, impedance can be set to Time to find a facility that's quickest to reach, or it can be set to Length to find a facility that's nearest to the incident. 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:AGSClosestFacilityTaskParameters = AGSClosestFacilityTaskParameters()
params.impedanceAttributeName = "Time"

Cutoff

You can also specify a cutoff value for the impedance beyond which facilities should not be found. For instance, while locating the closest hospitals from the site of an accident, a cutoff value of 15 minutes means that the service should search for the closest hospital within 15 minutes from the incident. If the closest hospital is 17 minutes away, no hospitals will be returned in the closest facility search. A cutoff value is especially useful when searching for multiple facilities.

Facility count

Sometimes you may want to find multiple closest facilities from an incident, for instance, the nearest three fire stations to a fire. You can do this by setting the defaultTargetFacilityCount property:

params.defaultTargetFacilityCount = 3

Facilities

Facilities represent locations that can serve as the starting point or ending point of a closest facility analysis, for example, a fire station or a hospital.

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 Closest Facility 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 an impedance on each facility to assign an additional cost to that facility. The attribute should have a name Attr_<Impedance> where <impedance> is the value specified in the impedance property. For example, an attribute of name Attr_Time with a value of 5 specifies that an additional cost of 5 minutes be associated with the facility. This may be needed, for example, to account for how much time it takes the crew of a fire station to don the appropriate protective equipment and exit the fire station.

Output attributes are returned by the service along with the computed result when you enable returnFacilities on AGSClosestFacilityTaskParameters. 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 = "facility_type = 'Hospital'"
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 AGSClosestFacilityTaskParameters object:

params.setFacilitiesWithLayerDefinition(layerDef)

Incidents

Incidents also represent locations that can serve as the starting point or ending point of a closest facility analysis, for example, a fire or a traffic accident.

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

Features

You can create an array of AGSIncidentGraphic objects representing incident features. At a minimum, you need to provide a name and a point geometry for each incident, but you can also provide additional attributes depending on how the Closest Facility layer in the Network Analyst service is configured. These attributes are listed in the Network Analysis Classes > Class Name:Incidents 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 the attributes supported by Incident features

Layer definition

In addition to specifying incidents by value (that is, providing the actual value for each feature as previously described), you can also specify incidents by reference. This is useful, for example, if you maintain a live database of incidents along with the Network Analyst service. For instance, the transportation department of a city could provide a Network Analyst service containing information about recent traffic accidents. In such cases, the application does not need to know the actual details about each incident. All it needs to do is set up a layer definition specifying which incidents should be included in the analysis.

Once you set up a layer definition identifying the features to use, you can use it to specify incidents using the setIncidentsWithLayerDefinition: method on an AGSClosestFacilityTaskParameters object.

Travel direction

You can find facilities by accumulating impedance in the direction away from the facility towards the incident or in the reverse direction towards the facility from the incident. On a network with one-way restrictions and different impedances based on direction of travel, different results would be achieved. The direction you choose depends on the nature of your analysis.

The closest facility for a fire response, for example, should be calculated away from the fire station towards the fire, since it's imperative to get fire trucks and personnel quickly to the location of the fire. Alternatively, the closest facility for a traffic accident should choose the opposite direction, since the urgent part of the trip for an incoming patient is going to the hospital.

params.uTurns = .AtDeadEndsAndIntersections

Barriers

Barriers represent ad-hoc restrictions that must be taken into consideration when finding facilities. 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 and incidents, 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 Closest Facility 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 barriers

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, 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: methods on an AGSClosestFacilityTaskParameters object.

U-turn policy

You can specify whether 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 that 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

Driving directions

The task can also return turn-by-turn driving directions for the route if you enable returnDirections on AGSClosestFacilityTaskParameters. You can specify the distance units to use (miles, kilometers, and so on) through the directionsLengthUnits property and, depending on the languages supported by the service, you can also specify which language to use through the directionsLanguage property.

The following code snippet requests driving directions in French, using kilometers as the distance unit:

params.returnDirections = true
params.directionsLanguage = "fr_FR"
params.directionsLengthUnits = .Kilometers

Result options

Line options

You can generate straight lines or true shape lines between the incidents and facilities by setting the outputLines property on AGSClosestFacilityTaskParameters. 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.

Geometry options

You can request the geometry of the routes be generalized by modifying the outputGeometryPrecision and outputGeometryPrecisionUnits properties on AGSClosestFacilityTaskParameters. 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 AGSClosestFacilityTaskParameters. 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.

Finding the closest facility

Once you set up the input parameters, finding the closest facility is as simple as invoking solveClosestFacilityWithParameters: on AGSClosestFacilityTask and passing in the AGSClosestFacilityTaskParameters object to use in the calculation.

let op = cfTask.solveClosestFacilityWithParameters(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 Closest Facility 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 AGSClosestFacilityTaskDelegate protocol.

class MyViewController: UIViewController, AGSClosestFacilityTaskDelegate {
    ...   
}

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.

cfTask.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 closestFacilityTask:operation:didSolveClosestFacilityWithResult: method when the operation completes successfully. Results are passed to the delegate method as an AGSClosestFacilityTaskResult object.

func closestFacilityTask(closestFacilityTask: AGSClosestFacilityTask!, operation op: NSOperation!, didSolveClosestFacilityWithResult closestFacilityTaskResult: AGSClosestFacilityTaskResult!) {
 //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 before it finishes execution. You need to retain th task if you're using manual retain-release, or create a strong reference to it if you're using ARC.

An AGSClosestFacilityTaskResult object contains an array of AGSClosestFacilityResult objects representing the routes that were calculated between incidents and facilities. Each AGSClosestFacilityResult object contains the following:

  • A graphic representing the route feature. The graphic's attributes provide information about the route properties.
  • A set of turn-by-turn driving directions (if you enabled returnDirections on AGSClosestFacilityTaskParameters).

The AGSClosestFacilityTaskResult object also contains an array of messages providing information about any warnings or errors encountered while finding facilities.

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 closestFacilityTask:operation:didFailSolveWithError: method to be informed when an error is encountered. The error is passed into the method as an NSError object.

func closestFacilityTask(closestFacilityTask: AGSClosestFacilityTask!, 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