arcgis 0.1.3

Type-safe Rust SDK for the ArcGIS REST API with compile-time guarantees
Documentation
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
//! Routing Service client for network analysis operations.

use crate::{ArcGISClient, Result};
use tracing::instrument;

use super::{
    ClosestFacilityParameters, ClosestFacilityResult, ODCostMatrixParameters, ODCostMatrixResult,
    RouteParameters, RouteResult, ServiceAreaParameters, ServiceAreaResult,
};

/// Client for interacting with an ArcGIS Routing Service (Network Analyst Server).
///
/// Provides operations for routing, service areas, closest facility, and origin-destination matrices.
///
/// # Example
/// ```no_run
/// use arcgis::{ApiKeyAuth, ArcGISClient, RoutingServiceClient};
///
/// # async fn example() -> arcgis::Result<()> {
/// let auth = ApiKeyAuth::new("YOUR_API_KEY");
/// let client = ArcGISClient::new(auth);
///
/// let routing_service = RoutingServiceClient::new(
///     "https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World",
///     &client,
/// );
/// # Ok(())
/// # }
/// ```
pub struct RoutingServiceClient<'a> {
    /// Base URL of the routing service.
    base_url: String,
    /// Reference to the ArcGIS client for HTTP operations.
    client: &'a ArcGISClient,
}

impl<'a> RoutingServiceClient<'a> {
    /// Creates a new Routing Service client.
    ///
    /// # Arguments
    ///
    /// * `base_url` - The base URL of the routing service (e.g., `https://route.arcgis.com/.../Route_World`)
    /// * `client` - Reference to an authenticated ArcGIS client
    ///
    /// # Example
    /// ```no_run
    /// use arcgis::{ApiKeyAuth, ArcGISClient, RoutingServiceClient};
    ///
    /// let auth = ApiKeyAuth::new("YOUR_API_KEY");
    /// let client = ArcGISClient::new(auth);
    /// let routing_service = RoutingServiceClient::new(
    ///     "https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World",
    ///     &client
    /// );
    /// ```
    pub fn new(base_url: impl Into<String>, client: &'a ArcGISClient) -> Self {
        let base_url = base_url.into();
        tracing::debug!(base_url = %base_url, "Creating RoutingServiceClient");
        Self { base_url, client }
    }

    /// Solves a route between multiple stops.
    ///
    /// Calculates the optimal route connecting all stops, with options for
    /// turn-by-turn directions, barriers, and traffic-aware routing.
    ///
    /// # Arguments
    ///
    /// * `params` - Route parameters including stops and routing options
    ///
    /// # Example
    ///
    /// ```no_run
    /// use arcgis::{ApiKeyAuth, ArcGISClient, RoutingServiceClient, ArcGISPoint, ArcGISGeometry};
    /// use arcgis::{RouteParameters, NALocation};
    ///
    /// # async fn example() -> arcgis::Result<()> {
    /// let auth = ApiKeyAuth::new("YOUR_API_KEY");
    /// let client = ArcGISClient::new(auth);
    /// let routing_service = RoutingServiceClient::new(
    ///     "https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World",
    ///     &client
    /// );
    ///
    /// let stop1 = NALocation::new(ArcGISGeometry::Point(
    ///     ArcGISPoint::new(-122.4194, 37.7749)
    /// )).with_name("San Francisco");
    ///
    /// let stop2 = NALocation::new(ArcGISGeometry::Point(
    ///     ArcGISPoint::new(-118.2437, 34.0522)
    /// )).with_name("Los Angeles");
    ///
    /// let params = RouteParameters::builder()
    ///     .stops(vec![stop1, stop2])
    ///     .return_directions(true)
    ///     .return_routes(true)
    ///     .return_stops(true)
    ///     .build()
    ///     .expect("Valid parameters");
    ///
    /// let result = routing_service.solve_route(params).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip(self, params), fields(stop_count = params.stops().len()))]
    pub async fn solve_route(&self, params: RouteParameters) -> Result<RouteResult> {
        tracing::debug!("Solving route");

        let url = format!("{}/solve", self.base_url);

        tracing::debug!(url = %url, "Sending route solve request");

        // Serialize stops as features
        let stops_json = serde_json::to_string(&serde_json::json!({
            "features": params.stops().iter().map(|stop| {
                serde_json::json!({
                    "geometry": stop.geometry(),
                    "attributes": {
                        "Name": stop.name().as_ref().unwrap_or(&String::new()),
                    }
                })
            }).collect::<Vec<_>>()
        }))?;

        // Prepare string values that need to outlive the form vector
        let out_sr_str = params.out_sr().map(|sr| sr.to_string());

        let mut form = vec![("stops", stops_json.as_str()), ("f", "json")];

        // Add optional parameters
        if let Some(return_directions) = params.return_directions() {
            form.push((
                "returnDirections",
                if *return_directions { "true" } else { "false" },
            ));
        }
        if let Some(return_routes) = params.return_routes() {
            form.push((
                "returnRoutes",
                if *return_routes { "true" } else { "false" },
            ));
        }
        if let Some(return_stops) = params.return_stops() {
            form.push(("returnStops", if *return_stops { "true" } else { "false" }));
        }
        if let Some(ref out_sr) = out_sr_str {
            form.push(("outSR", out_sr.as_str()));
        }

        // Add token if required by auth provider
        let token_opt = self.client.get_token_if_required().await?;
        let token_str;
        if let Some(token) = token_opt {
            token_str = token;
            form.push(("token", token_str.as_str()));
        }

        let response = self.client.http().post(&url).form(&form).send().await?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|e| format!("Failed to read error: {}", e));
            tracing::error!(status = %status, error = %error_text, "solve route request failed");
            return Err(crate::Error::from(crate::ErrorKind::Api {
                code: status.as_u16() as i32,
                message: format!("HTTP {}: {}", status, error_text),
            }));
        }

        let result: RouteResult = response.json().await?;

        tracing::info!(route_count = result.routes().len(), "solve route completed");

        Ok(result)
    }

    /// Calculates service areas (drive-time or distance polygons).
    ///
    /// Generates polygons showing areas reachable from facilities within
    /// specified break values (time or distance).
    ///
    /// # Arguments
    ///
    /// * `params` - Service area parameters including facilities and break values
    ///
    /// # Example
    ///
    /// ```no_run
    /// use arcgis::{ApiKeyAuth, ArcGISClient, RoutingServiceClient, ArcGISPoint, ArcGISGeometry};
    /// use arcgis::{ServiceAreaParameters, NALocation};
    ///
    /// # async fn example() -> arcgis::Result<()> {
    /// let auth = ApiKeyAuth::new("YOUR_API_KEY");
    /// let client = ArcGISClient::new(auth);
    /// let routing_service = RoutingServiceClient::new(
    ///     "https://route.arcgis.com/arcgis/rest/services/World/ServiceAreas/NAServer/ServiceArea_World",
    ///     &client
    /// );
    ///
    /// let facility = NALocation::new(ArcGISGeometry::Point(
    ///     ArcGISPoint::new(-122.4194, 37.7749)
    /// )).with_name("Store");
    ///
    /// let params = ServiceAreaParameters::builder()
    ///     .facilities(vec![facility])
    ///     .default_breaks(vec![5.0, 10.0, 15.0])  // 5, 10, 15 minute drive times
    ///     .build()
    ///     .expect("Valid parameters");
    ///
    /// let result = routing_service.solve_service_area(params).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip(self, params), fields(facility_count = params.facilities().len()))]
    pub async fn solve_service_area(
        &self,
        params: ServiceAreaParameters,
    ) -> Result<ServiceAreaResult> {
        tracing::debug!("Solving service area");

        let url = format!("{}/solveServiceArea", self.base_url);

        tracing::debug!(url = %url, "Sending service area solve request");

        // Serialize facilities as features
        let facilities_json = serde_json::to_string(&serde_json::json!({
            "features": params.facilities().iter().map(|fac| {
                serde_json::json!({
                    "geometry": fac.geometry(),
                    "attributes": {
                        "Name": fac.name().as_ref().unwrap_or(&String::new()),
                    }
                })
            }).collect::<Vec<_>>()
        }))?;

        // Serialize break values
        let breaks_json = serde_json::to_string(params.default_breaks())?;

        let out_sr_str = params.out_sr().map(|sr| sr.to_string());

        let mut form = vec![
            ("facilities", facilities_json.as_str()),
            ("defaultBreaks", breaks_json.as_str()),
            ("f", "json"),
        ];

        if let Some(ref out_sr) = out_sr_str {
            form.push(("outSR", out_sr.as_str()));
        }

        if let Some(return_polygons) = params.return_polygons() {
            form.push((
                "returnPolygons",
                if *return_polygons { "true" } else { "false" },
            ));
        }

        // Add token if required by auth provider
        let token_opt = self.client.get_token_if_required().await?;
        let token_str;
        if let Some(token) = token_opt {
            token_str = token;
            form.push(("token", token_str.as_str()));
        }

        let response = self.client.http().post(&url).form(&form).send().await?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|e| format!("Failed to read error: {}", e));
            tracing::error!(status = %status, error = %error_text, "solve service area request failed");
            return Err(crate::Error::from(crate::ErrorKind::Api {
                code: status.as_u16() as i32,
                message: format!("HTTP {}: {}", status, error_text),
            }));
        }

        let result: ServiceAreaResult = response.json().await?;

        tracing::info!(
            polygon_count = result.service_area_polygons().len(),
            "solve service area completed"
        );

        Ok(result)
    }

    /// Finds the closest facilities from incidents.
    ///
    /// Calculates routes from incidents to the N nearest facilities,
    /// useful for emergency response, service allocation, etc.
    ///
    /// # Arguments
    ///
    /// * `params` - Closest facility parameters including incidents and facilities
    ///
    /// # Example
    ///
    /// ```no_run
    /// use arcgis::{ApiKeyAuth, ArcGISClient, RoutingServiceClient, ArcGISPoint, ArcGISGeometry};
    /// use arcgis::{ClosestFacilityParameters, NALocation};
    ///
    /// # async fn example() -> arcgis::Result<()> {
    /// let auth = ApiKeyAuth::new("YOUR_API_KEY");
    /// let client = ArcGISClient::new(auth);
    /// let routing_service = RoutingServiceClient::new(
    ///     "https://route.arcgis.com/arcgis/rest/services/World/ClosestFacility/NAServer/ClosestFacility_World",
    ///     &client
    /// );
    ///
    /// let incident = NALocation::new(ArcGISGeometry::Point(
    ///     ArcGISPoint::new(-122.4194, 37.7749)
    /// )).with_name("Emergency");
    ///
    /// let facility = NALocation::new(ArcGISGeometry::Point(
    ///     ArcGISPoint::new(-122.4, 37.8)
    /// )).with_name("Hospital");
    ///
    /// let params = ClosestFacilityParameters::builder()
    ///     .incidents(vec![incident])
    ///     .facilities(vec![facility])
    ///     .default_target_facility_count(1)
    ///     .return_routes(true)
    ///     .build()
    ///     .expect("Valid parameters");
    ///
    /// let result = routing_service.solve_closest_facility(params).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip(self, params), fields(incident_count = params.incidents().len(), facility_count = params.facilities().len()))]
    pub async fn solve_closest_facility(
        &self,
        params: ClosestFacilityParameters,
    ) -> Result<ClosestFacilityResult> {
        tracing::debug!("Solving closest facility");

        let url = format!("{}/solveClosestFacility", self.base_url);

        tracing::debug!(url = %url, "Sending closest facility solve request");

        // Serialize incidents and facilities as features
        let incidents_json = serde_json::to_string(&serde_json::json!({
            "features": params.incidents().iter().map(|inc| {
                serde_json::json!({
                    "geometry": inc.geometry(),
                    "attributes": {
                        "Name": inc.name().as_ref().unwrap_or(&String::new()),
                    }
                })
            }).collect::<Vec<_>>()
        }))?;

        let facilities_json = serde_json::to_string(&serde_json::json!({
            "features": params.facilities().iter().map(|fac| {
                serde_json::json!({
                    "geometry": fac.geometry(),
                    "attributes": {
                        "Name": fac.name().as_ref().unwrap_or(&String::new()),
                    }
                })
            }).collect::<Vec<_>>()
        }))?;

        let out_sr_str = params.out_sr().map(|sr| sr.to_string());
        let target_count_str = params
            .default_target_facility_count()
            .map(|c| c.to_string());

        let mut form = vec![
            ("incidents", incidents_json.as_str()),
            ("facilities", facilities_json.as_str()),
            ("f", "json"),
        ];

        if let Some(ref out_sr) = out_sr_str {
            form.push(("outSR", out_sr.as_str()));
        }
        if let Some(ref target_count) = target_count_str {
            form.push(("defaultTargetFacilityCount", target_count.as_str()));
        }
        if let Some(return_routes) = params.return_routes() {
            form.push((
                "returnCFRoutes",
                if *return_routes { "true" } else { "false" },
            ));
        }

        // Always request facilities and incidents in response for validation
        form.push(("returnFacilities", "true"));
        form.push(("returnIncidents", "true"));

        if let Some(travel_direction) = params.travel_direction() {
            let direction_str = match travel_direction {
                crate::TravelDirection::FromFacility => "esriNATravelDirectionFromFacility",
                crate::TravelDirection::ToFacility => "esriNATravelDirectionToFacility",
            };
            form.push(("travelDirection", direction_str));
        }

        // Handle impedance attribute
        let impedance_str;
        if let Some(impedance) = params.impedance_attribute() {
            impedance_str = serde_json::to_string(impedance)?;
            let impedance_value = impedance_str.trim_matches('"');
            form.push(("impedanceAttributeName", impedance_value));
        }

        // Handle accumulate attributes
        let accumulate_str;
        if let Some(accumulate) = params.accumulate_attribute_names() {
            accumulate_str = accumulate.join(",");
            form.push(("accumulateAttributeNames", accumulate_str.as_str()));
        }

        // Add token if required by auth provider
        let token_opt = self.client.get_token_if_required().await?;
        let token_str;
        if let Some(token) = token_opt {
            token_str = token;
            form.push(("token", token_str.as_str()));
        }

        let response = self.client.http().post(&url).form(&form).send().await?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|e| format!("Failed to read error: {}", e));
            tracing::error!(status = %status, error = %error_text, "solve closest facility request failed");
            return Err(crate::Error::from(crate::ErrorKind::Api {
                code: status.as_u16() as i32,
                message: format!("HTTP {}: {}", status, error_text),
            }));
        }

        let result: ClosestFacilityResult = response.json().await?;

        tracing::info!(
            route_count = result.routes().len(),
            facility_count = result.facilities().len(),
            incident_count = result.incidents().len(),
            "solve closest facility completed"
        );

        Ok(result)
    }

    /// Generates an origin-destination cost matrix.
    ///
    /// Calculates travel costs between all origin-destination pairs,
    /// useful for logistics, fleet management, and coverage analysis.
    ///
    /// # Arguments
    ///
    /// * `params` - OD cost matrix parameters including origins and destinations
    ///
    /// # Example
    ///
    /// ```no_run
    /// use arcgis::{ApiKeyAuth, ArcGISClient, RoutingServiceClient, ArcGISPoint, ArcGISGeometry};
    /// use arcgis::{ODCostMatrixParameters, NALocation};
    ///
    /// # async fn example() -> arcgis::Result<()> {
    /// let auth = ApiKeyAuth::new("YOUR_API_KEY");
    /// let client = ArcGISClient::new(auth);
    /// let routing_service = RoutingServiceClient::new(
    ///     "https://route.arcgis.com/arcgis/rest/services/World/OriginDestinationCostMatrix/NAServer/OriginDestinationCostMatrix_World",
    ///     &client
    /// );
    ///
    /// let origin = NALocation::new(ArcGISGeometry::Point(
    ///     ArcGISPoint::new(-122.4194, 37.7749)
    /// )).with_name("Warehouse");
    ///
    /// let destination = NALocation::new(ArcGISGeometry::Point(
    ///     ArcGISPoint::new(-118.2437, 34.0522)
    /// )).with_name("Customer");
    ///
    /// let params = ODCostMatrixParameters::builder()
    ///     .origins(vec![origin])
    ///     .destinations(vec![destination])
    ///     .build()
    ///     .expect("Valid parameters");
    ///
    /// let result = routing_service.generate_od_cost_matrix(params).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip(self, params), fields(origin_count = params.origins().len(), destination_count = params.destinations().len()))]
    pub async fn generate_od_cost_matrix(
        &self,
        params: ODCostMatrixParameters,
    ) -> Result<ODCostMatrixResult> {
        tracing::debug!("Generating OD cost matrix");

        let url = format!("{}/solveODCostMatrix", self.base_url);

        tracing::debug!(url = %url, "Sending OD cost matrix request");

        // Serialize origins and destinations as features
        let origins_json = serde_json::to_string(&serde_json::json!({
            "features": params.origins().iter().map(|org| {
                serde_json::json!({
                    "geometry": org.geometry(),
                    "attributes": {
                        "Name": org.name().as_ref().unwrap_or(&String::new()),
                    }
                })
            }).collect::<Vec<_>>()
        }))?;

        let destinations_json = serde_json::to_string(&serde_json::json!({
            "features": params.destinations().iter().map(|dest| {
                serde_json::json!({
                    "geometry": dest.geometry(),
                    "attributes": {
                        "Name": dest.name().as_ref().unwrap_or(&String::new()),
                    }
                })
            }).collect::<Vec<_>>()
        }))?;

        let out_sr_str = params.out_sr().map(|sr| sr.to_string());

        let mut form = vec![
            ("origins", origins_json.as_str()),
            ("destinations", destinations_json.as_str()),
            ("f", "json"),
        ];

        if let Some(ref out_sr) = out_sr_str {
            form.push(("outSR", out_sr.as_str()));
        }

        // Handle impedance attribute
        let impedance_str;
        if let Some(impedance) = params.impedance_attribute() {
            impedance_str = serde_json::to_string(impedance)?;
            let impedance_value = impedance_str.trim_matches('"');
            form.push(("impedanceAttributeName", impedance_value));
        }

        // Handle accumulate attributes
        let accumulate_str;
        if let Some(accumulate) = params.accumulate_attribute_names() {
            accumulate_str = accumulate.join(",");
            form.push(("accumulateAttributeNames", accumulate_str.as_str()));
        }

        // Add token if required by auth provider
        let token_opt = self.client.get_token_if_required().await?;
        let token_str;
        if let Some(token) = token_opt {
            token_str = token;
            form.push(("token", token_str.as_str()));
        }

        let response = self.client.http().post(&url).form(&form).send().await?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|e| format!("Failed to read error: {}", e));
            tracing::error!(status = %status, error = %error_text, "generate OD cost matrix request failed");
            return Err(crate::Error::from(crate::ErrorKind::Api {
                code: status.as_u16() as i32,
                message: format!("HTTP {}: {}", status, error_text),
            }));
        }

        let result: ODCostMatrixResult = response.json().await?;

        tracing::info!(
            od_line_count = result.od_lines().len(),
            "generate OD cost matrix completed"
        );

        Ok(result)
    }
}