Skip to content

Analyze hotspots

View on GitHub

Use a geoprocessing service and a set of features to identify statistically significant hot spots and cold spots.

Image of analyze hotspots sample

Use case

This tool identifies statistically significant spatial clusters of high values (hot spots) and low values (cold spots). For example, a hotspot analysis based on the frequency of 911 calls within a set region.

How to use the sample

Select a date range (between 1998-01-01 and 1998-05-31) from the dialog. The results will be shown on the map upon successful completion of the geoprocessing job.

How it works

  1. Create a geoprocessing task with the URL set to the endpoint of a geoprocessing service using GeoprocessingTask.init(url:).
  2. Create a query string with the date range and set it as an input of the geoprocessing parameters using GeoprocessingParameters.setInputValue(_:forKey:).
  3. Use the geoprocessing task to create a job with the parameters using GeoprocessingTask.makeJob(parameters:).
  4. Start the geoprocessing job and wait for it to complete and return a result using GeoprocessingJob.output.
  5. Get the resulting ArcGISMapImageLayer instance using GeoprocessingResult.mapImageLayer.
  6. Add the layer to the map's operational layers.

Relevant API

  • GeoprocessingJob
  • GeoprocessingParameters
  • GeoprocessingResult
  • GeoprocessingTask

Tags

analysis, density, geoprocessing, hot spots, hotspots

Sample Code

AnalyzeHotspotsView.swift
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
// Copyright 2025 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
//
//   https://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.

import ArcGIS
import SwiftUI

struct AnalyzeHotspotsView: View {
    /// The map displayed by the map view.
    @State private var map: Map = {
        let map = Map(basemapStyle: .arcGISTopographic)
        map.initialViewpoint = Viewpoint(
            center: Point(x: -13671170.647485, y: 5693633.356735, spatialReference: .webMercator),
            scale: 57_779
        )
        return map
    }()

    /// The task used to perform geoprocessing jobs.
    @State private var geoprocessingTask = GeoprocessingTask(
        url: URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/911CallsHotspot/GPServer/911%20Calls%20Hotspot")!
    )
    /// The error thrown by geoprocessing job.
    @State private var analysisError: Error?
    /// A Boolean value indicating whether the geoprocessing job is running.
    @State private var isAnalyzing = false
    /// A Boolean value that indicates whether the analysis sheet is presented.
    @State private var isAnalysisSheetPresented = false
    /// The from date for the analysis.
    @State private var fromDate = Self.minDate
    /// The to date for the analysis.
    @State private var toDate = Self.maxDate

    /// The date range for the analysis.
    var dateRange: ClosedRange<Date> { fromDate...toDate }

    /// The minimum date for the analysis.
    static var minDate: Date {
        Calendar.current.date(from: DateComponents(year: 1998, month: 1, day: 1))!
    }
    /// The maximum date for the analysis.
    static var maxDate: Date {
        Calendar.current.date(from: DateComponents(year: 1998, month: 05, day: 31))!
    }

    var body: some View {
        MapViewReader { mapView in
            MapView(map: map)
                .task(id: dateRange) {
                    map.removeAllOperationalLayers()
                    // Creates and configures the job's parameters.
                    let parameters = makeParameters(
                        spatialReference: map.spatialReference,
                        dateRange: dateRange
                    )
                    // Creates and runs the job.
                    let geoprocessingJob = geoprocessingTask.makeJob(parameters: parameters)
                    isAnalyzing = true
                    geoprocessingJob.start()
                    do {
                        let result = try await withTaskCancellationHandler {
                            try await geoprocessingJob.output
                        } onCancel: {
                            Task.detached {
                                await geoprocessingJob.cancel()
                            }
                        }
                        guard let mapImageLayer = result.mapImageLayer else {
                            return
                        }
                        try await mapImageLayer.load()
                        map.addOperationalLayer(mapImageLayer)
                        isAnalyzing = false
                        if let extent = mapImageLayer.fullExtent {
                            await mapView.setViewpointGeometry(extent)
                        }
                    } catch {
                        analysisError = error
                    }
                }
                .toolbar {
                    if isAnalyzing {
                        ToolbarItem(placement: .topBarTrailing) {
                            ProgressView()
                                .progressViewStyle(.circular)
                        }
                    }
                    ToolbarItem(placement: .bottomBar) {
                        Button("Analysis") {
                            isAnalysisSheetPresented.toggle()
                        }
                        .popover(isPresented: $isAnalysisSheetPresented) {
                            analysisForm
                                .frame(idealWidth: 250, idealHeight: 150)
                                .presentationCompactAdaptation(.popover)
                        }
                    }
                }
                .errorAlert(presentingError: $analysisError)
        }
    }

    /// The form for customizing the analysis.
    var analysisForm: some View {
        Form {
            Section {
                let displayedComponents: DatePicker<Label>.Components = .date
                DatePicker(
                    "From",
                    selection: $fromDate,
                    in: Self.minDate...toDate,
                    displayedComponents: displayedComponents
                )
                DatePicker(
                    "To",
                    selection: $toDate,
                    in: fromDate...Self.maxDate,
                    displayedComponents: displayedComponents
                )
            }
        }
    }

    /// Creates the parameters for a geoprocessing job.
    /// - Parameters:
    ///   - spatialReference: The process and output spatial reference.
    ///   - dateRange: The minimum and maximum dates.
    /// - Returns: A new geoprocessing parameters object
    func makeParameters(
        spatialReference: SpatialReference?,
        dateRange: ClosedRange<Date>
    ) -> GeoprocessingParameters {
        // Creates the query string.
        let format = Date.ISO8601FormatStyle()
            .year()
            .month()
            .day()
        let fromDateString = dateRange.lowerBound.formatted(format)
        let toDateString = dateRange.upperBound.formatted(format)
        let queryString = "(\"DATE\" > date '\(fromDateString) 00:00:00' AND \"DATE\" < date '\(toDateString) 00:00:00')"

        // Creates and configures the parameters.
        let parameters = GeoprocessingParameters(executionType: .asynchronousSubmit)
        parameters.processSpatialReference = spatialReference
        parameters.outputSpatialReference = spatialReference
        parameters.setInputValue(GeoprocessingString(value: queryString), forKey: "Query")
        return parameters
    }
}

#Preview {
    AnalyzeHotspotsView()
}

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