Skip To Content

Find the closest facilities

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 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 upon the type of analysis performed. A closest facility task relies on 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 examples of closest facility problems. When finding closest facilities, specify how many to find and whether the travel direction is toward or away from the facilities. 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 a 15 minute drive to an accident. Hospitals that take longer than 15 minutes to reach, will not be included in the results.

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

Create a closest facility task

To instantiate a closest facility task, provide a URL to the REST resource that represents a closest facility layer in a network analyst service. If the service is secured, 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 closest facility 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/Closest%20Facility")
let cfTask = AGSClosestFacilityTask(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 closestFacilityTaskWithURL:, explicitly take ownership by assigning it to a property that retains it.

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

Note:

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

Prepare the input

Provide input to the closest facility task using an object of the AGSClosestFacilityTaskParameters class. Instantiate a new AGSClosestFacilityTaskParameters object and modify its properties to provide the input. However, you may want to use the defaults specified in the service. In such cases, 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 could be set to Time to find a facility that is quickest to reach, or it could be set to Length to find a facility that is nearest to the incident. Impedances supported by the service are listed on the Service Directory page 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 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 be not found. For instance, while locating the closest hospitals from the site of an accident, a cutoff value of 15 minutes indicates 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 return 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 hospital.

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 upon 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 on the Services Directory page.

Attributes of facilities
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 an impedance on each facility if you want 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 a fire station crew to dress in the appropriate protective equipment and exit the fire station.

Output attributes are returned by the service 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.

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 actual 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. The application needs to 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 with 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 have set up a layer definition identifying the features you want 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

You can create an array of AGSIncidentGraphic objects representing incident features. Minimally provide a name and a point geometry for each incident. 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 on the Services Directory page. Attributes may 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

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

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

Travel direction

You can choose to 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. This gives different results on a network with one-way restrictions and different impedances based on the travel direction, . The direction you should 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 is 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.travelDirection = .ToFacility

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 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

You can create an array of AGSGraphic objects representing barrier features. 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:

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, and PolygonBarriers section on the Services Directory page. 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 barriers.

Layer definition

Apart from specifying barriers by value (that is, providing the actual 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, construction work, and so on. In such cases, the application does not need to know the actual details about each barrier. The application needs to set up a layer definition specifying which barriers should be included in the analysis.

Once you have set up a layer definition identifying the features you want 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 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

Drive 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 and use kilometers as the distance units:

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

Result options

The following discusses result options.

Line options

You can choose to 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 for the geometry of the routes to be generalized by modifying the outputGeometryPrecision and outputGeometryPrecisionUnits properties on AGSClosestFacilityTaskParameters. Generalizing a geometry removes vertices that add detail beyond the precision you require. Removing vertices makes the geometry object smaller, saves the time needed to transfer the geometry over the network, and draws the map graphic faster.

You can also request the geometry to 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.

Locate the closest facility

Once you have set up input parameters, find the closest facility by 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.

Retrieve results and handle errors

The closest facility 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 AGSClosestFacilityTaskDelegate protocol.

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

cfTask.delegate = self

Finally, your class should implement one or more methods defined in the protocol that pertains 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 for 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
}

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

  • 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 warnings or errors encountered while finding facilities.

Note:

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

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

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