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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
//! # Advanced Example: Fallible Geometry coordinate conversion using `PROJ`
//!
//! ```
//! // activate the [use-proj] feature in cargo.toml in order to access proj functions
//! # #[cfg(feature = "use-proj")]
//! use geo::{Coordinate, Point};
//! # #[cfg(feature = "use-proj")]
//! use geo::algorithm::map_coords::TryMapCoords;
//! # #[cfg(feature = "use-proj")]
//! use proj::Proj;
//! // GeoJSON uses the WGS 84 coordinate system
//! # #[cfg(feature = "use-proj")]
//! let from = "EPSG:4326";
//! // The NAD83 / California zone 6 (ftUS) coordinate system
//! # #[cfg(feature = "use-proj")]
//! let to = "EPSG:2230";
//! # #[cfg(feature = "use-proj")]
//! let to_feet = Proj::new_known_crs(&from, &to, None).unwrap();
//! # #[cfg(feature = "use-proj")]
//! let f = |x: f64, y: f64| {
//!     // proj can accept Point, Coordinate, Tuple, and array values, returning a Result
//!     let shifted = to_feet.convert((x, y))?;
//!     Ok((shifted.x(), shifted.y()))
//! };
//! # #[cfg(feature = "use-proj")]
//! // 👽
//! # #[cfg(feature = "use-proj")]
//! let usa_m = Point::new(-115.797615, 37.2647978);
//! # #[cfg(feature = "use-proj")]
//! let usa_ft = usa_m.try_map_coords(|&(x, y)| f(x, y)).unwrap();
//! # #[cfg(feature = "use-proj")]
//! assert_eq!(6693625.67217475, usa_ft.x());
//! # #[cfg(feature = "use-proj")]
//! assert_eq!(3497301.5918027186, usa_ft.y());
//! ```

use crate::{
    Coordinate, CoordinateType, Geometry, GeometryCollection, Line, LineString, MultiLineString,
    MultiPoint, MultiPolygon, Point, Polygon, Rect, Triangle,
};
use std::error::Error;

/// Map a function over all the coordinates in an object, returning a new one
pub trait MapCoords<T, NT> {
    type Output;

    /// Apply a function to all the coordinates in a geometric object, returning a new object.
    ///
    /// # Examples
    ///
    /// ```
    /// use geo::algorithm::map_coords::MapCoords;
    /// use geo::Point;
    ///
    /// let p1 = Point::new(10., 20.);
    /// let p2 = p1.map_coords(|&(x, y)| (x + 1000., y * 2.));
    ///
    /// assert_eq!(p2, Point::new(1010., 40.));
    /// ```
    ///
    /// You can convert the coordinate type this way as well
    ///
    /// ```
    /// # use geo::Point;
    /// # use geo::algorithm::map_coords::MapCoords;
    ///
    /// let p1: Point<f32> = Point::new(10.0f32, 20.0f32);
    /// let p2: Point<f64> = p1.map_coords(|&(x, y)| (x as f64, y as f64));
    ///
    /// assert_eq!(p2, Point::new(10.0f64, 20.0f64));
    /// ```
    fn map_coords(&self, func: impl Fn(&(T, T)) -> (NT, NT) + Copy) -> Self::Output
    where
        T: CoordinateType,
        NT: CoordinateType;
}

/// Map a fallible function over all the coordinates in a geometry, returning a Result
pub trait TryMapCoords<T, NT> {
    type Output;

    /// Map a fallible function over all the coordinates in a geometry, returning a Result
    ///
    /// # Examples
    ///
    /// ```
    /// use geo::algorithm::map_coords::TryMapCoords;
    /// use geo::Point;
    ///
    /// let p1 = Point::new(10., 20.);
    /// let p2 = p1
    ///     .try_map_coords(|&(x, y)| Ok((x + 1000., y * 2.)))
    ///     .unwrap();
    ///
    /// assert_eq!(p2, Point::new(1010., 40.));
    /// ```
    ///
    /// ## Advanced Example: Geometry coordinate conversion using `PROJ`
    ///
    /// ```
    /// // activate the [use-proj] feature in cargo.toml in order to access proj functions
    /// # #[cfg(feature = "use-proj")]
    /// use geo::{Coordinate, Point};
    /// # #[cfg(feature = "use-proj")]
    /// use geo::algorithm::map_coords::TryMapCoords;
    /// # #[cfg(feature = "use-proj")]
    /// use proj::Proj;
    /// // GeoJSON uses the WGS 84 coordinate system
    /// # #[cfg(feature = "use-proj")]
    /// let from = "EPSG:4326";
    /// // The NAD83 / California zone 6 (ftUS) coordinate system
    /// # #[cfg(feature = "use-proj")]
    /// let to = "EPSG:2230";
    /// # #[cfg(feature = "use-proj")]
    /// let to_feet = Proj::new_known_crs(&from, &to, None).unwrap();
    /// # #[cfg(feature = "use-proj")]
    /// let f = |x: f64, y: f64| {
    ///     // proj can accept Point, Coordinate, Tuple, and array values, returning a Result
    ///     let shifted = to_feet.convert((x, y))?;
    ///     Ok((shifted.x(), shifted.y()))
    /// };
    /// # #[cfg(feature = "use-proj")]
    /// // 👽
    /// # #[cfg(feature = "use-proj")]
    /// let usa_m = Point::new(-115.797615, 37.2647978);
    /// # #[cfg(feature = "use-proj")]
    /// let usa_ft = usa_m.try_map_coords(|&(x, y)| f(x, y)).unwrap();
    /// # #[cfg(feature = "use-proj")]
    /// assert_eq!(6693625.67217475, usa_ft.x());
    /// # #[cfg(feature = "use-proj")]
    /// assert_eq!(3497301.5918027186, usa_ft.y());
    /// ```
    fn try_map_coords(
        &self,
        func: impl Fn(&(T, T)) -> Result<(NT, NT), Box<dyn Error + Send + Sync>> + Copy,
    ) -> Result<Self::Output, Box<dyn Error + Send + Sync>>
    where
        T: CoordinateType,
        NT: CoordinateType;
}

/// Map a function over all the coordinates in an object in place
pub trait MapCoordsInplace<T> {
    /// Apply a function to all the coordinates in a geometric object, in place
    ///
    /// # Examples
    ///
    /// ```
    /// use geo::algorithm::map_coords::MapCoordsInplace;
    /// use geo::Point;
    ///
    /// let mut p = Point::new(10., 20.);
    /// p.map_coords_inplace(|&(x, y)| (x + 1000., y * 2.));
    ///
    /// assert_eq!(p, Point::new(1010., 40.));
    /// ```
    fn map_coords_inplace(&mut self, func: impl Fn(&(T, T)) -> (T, T) + Copy)
    where
        T: CoordinateType;
}

impl<T: CoordinateType, NT: CoordinateType> MapCoords<T, NT> for Point<T> {
    type Output = Point<NT>;

    fn map_coords(&self, func: impl Fn(&(T, T)) -> (NT, NT) + Copy) -> Self::Output {
        let new_point = func(&(self.0.x, self.0.y));
        Point::new(new_point.0, new_point.1)
    }
}

impl<T: CoordinateType, NT: CoordinateType> TryMapCoords<T, NT> for Point<T> {
    type Output = Point<NT>;

    fn try_map_coords(
        &self,
        func: impl Fn(&(T, T)) -> Result<(NT, NT), Box<dyn Error + Send + Sync>>,
    ) -> Result<Self::Output, Box<dyn Error + Send + Sync>> {
        let new_point = func(&(self.0.x, self.0.y))?;
        Ok(Point::new(new_point.0, new_point.1))
    }
}

impl<T: CoordinateType> MapCoordsInplace<T> for Point<T> {
    fn map_coords_inplace(&mut self, func: impl Fn(&(T, T)) -> (T, T)) {
        let new_point = func(&(self.0.x, self.0.y));
        self.0.x = new_point.0;
        self.0.y = new_point.1;
    }
}

impl<T: CoordinateType, NT: CoordinateType> MapCoords<T, NT> for Line<T> {
    type Output = Line<NT>;

    fn map_coords(&self, func: impl Fn(&(T, T)) -> (NT, NT) + Copy) -> Self::Output {
        Line::new(
            self.start_point().map_coords(func).0,
            self.end_point().map_coords(func).0,
        )
    }
}

impl<T: CoordinateType, NT: CoordinateType> TryMapCoords<T, NT> for Line<T> {
    type Output = Line<NT>;

    fn try_map_coords(
        &self,
        func: impl Fn(&(T, T)) -> Result<(NT, NT), Box<dyn Error + Send + Sync>> + Copy,
    ) -> Result<Self::Output, Box<dyn Error + Send + Sync>> {
        Ok(Line::new(
            self.start_point().try_map_coords(func)?.0,
            self.end_point().try_map_coords(func)?.0,
        ))
    }
}

impl<T: CoordinateType> MapCoordsInplace<T> for Line<T> {
    fn map_coords_inplace(&mut self, func: impl Fn(&(T, T)) -> (T, T)) {
        let new_start = func(&(self.start.x, self.start.y));
        self.start.x = new_start.0;
        self.start.y = new_start.1;

        let new_end = func(&(self.end.x, self.end.y));
        self.end.x = new_end.0;
        self.end.y = new_end.1;
    }
}

impl<T: CoordinateType, NT: CoordinateType> MapCoords<T, NT> for LineString<T> {
    type Output = LineString<NT>;

    fn map_coords(&self, func: impl Fn(&(T, T)) -> (NT, NT) + Copy) -> Self::Output {
        LineString::from(
            self.points_iter()
                .map(|p| p.map_coords(func))
                .collect::<Vec<_>>(),
        )
    }
}

impl<T: CoordinateType, NT: CoordinateType> TryMapCoords<T, NT> for LineString<T> {
    type Output = LineString<NT>;

    fn try_map_coords(
        &self,
        func: impl Fn(&(T, T)) -> Result<(NT, NT), Box<dyn Error + Send + Sync>> + Copy,
    ) -> Result<Self::Output, Box<dyn Error + Send + Sync>> {
        Ok(LineString::from(
            self.points_iter()
                .map(|p| p.try_map_coords(func))
                .collect::<Result<Vec<_>, Box<dyn Error + Send + Sync>>>()?,
        ))
    }
}

impl<T: CoordinateType> MapCoordsInplace<T> for LineString<T> {
    fn map_coords_inplace(&mut self, func: impl Fn(&(T, T)) -> (T, T)) {
        for p in &mut self.0 {
            let new_coords = func(&(p.x, p.y));
            p.x = new_coords.0;
            p.y = new_coords.1;
        }
    }
}

impl<T: CoordinateType, NT: CoordinateType> MapCoords<T, NT> for Polygon<T> {
    type Output = Polygon<NT>;

    fn map_coords(&self, func: impl Fn(&(T, T)) -> (NT, NT) + Copy) -> Self::Output {
        Polygon::new(
            self.exterior().map_coords(func),
            self.interiors()
                .iter()
                .map(|l| l.map_coords(func))
                .collect(),
        )
    }
}

impl<T: CoordinateType, NT: CoordinateType> TryMapCoords<T, NT> for Polygon<T> {
    type Output = Polygon<NT>;

    fn try_map_coords(
        &self,
        func: impl Fn(&(T, T)) -> Result<(NT, NT), Box<dyn Error + Send + Sync>> + Copy,
    ) -> Result<Self::Output, Box<dyn Error + Send + Sync>> {
        Ok(Polygon::new(
            self.exterior().try_map_coords(func)?,
            self.interiors()
                .iter()
                .map(|l| l.try_map_coords(func))
                .collect::<Result<Vec<_>, Box<dyn Error + Send + Sync>>>()?,
        ))
    }
}

impl<T: CoordinateType> MapCoordsInplace<T> for Polygon<T> {
    fn map_coords_inplace(&mut self, func: impl Fn(&(T, T)) -> (T, T) + Copy) {
        self.exterior_mut(|line_string| {
            line_string.map_coords_inplace(func);
        });

        self.interiors_mut(|line_strings| {
            for line_string in line_strings {
                line_string.map_coords_inplace(func);
            }
        });
    }
}

impl<T: CoordinateType, NT: CoordinateType> MapCoords<T, NT> for MultiPoint<T> {
    type Output = MultiPoint<NT>;

    fn map_coords(&self, func: impl Fn(&(T, T)) -> (NT, NT) + Copy) -> Self::Output {
        MultiPoint(self.iter().map(|p| p.map_coords(func)).collect())
    }
}

impl<T: CoordinateType, NT: CoordinateType> TryMapCoords<T, NT> for MultiPoint<T> {
    type Output = MultiPoint<NT>;

    fn try_map_coords(
        &self,
        func: impl Fn(&(T, T)) -> Result<(NT, NT), Box<dyn Error + Send + Sync>> + Copy,
    ) -> Result<Self::Output, Box<dyn Error + Send + Sync>> {
        Ok(MultiPoint(
            self.0
                .iter()
                .map(|p| p.try_map_coords(func))
                .collect::<Result<Vec<_>, Box<dyn Error + Send + Sync>>>()?,
        ))
    }
}

impl<T: CoordinateType> MapCoordsInplace<T> for MultiPoint<T> {
    fn map_coords_inplace(&mut self, func: impl Fn(&(T, T)) -> (T, T) + Copy) {
        for p in &mut self.0 {
            p.map_coords_inplace(func);
        }
    }
}

impl<T: CoordinateType, NT: CoordinateType> MapCoords<T, NT> for MultiLineString<T> {
    type Output = MultiLineString<NT>;

    fn map_coords(&self, func: impl Fn(&(T, T)) -> (NT, NT) + Copy) -> Self::Output {
        MultiLineString(self.iter().map(|l| l.map_coords(func)).collect())
    }
}

impl<T: CoordinateType, NT: CoordinateType> TryMapCoords<T, NT> for MultiLineString<T> {
    type Output = MultiLineString<NT>;

    fn try_map_coords(
        &self,
        func: impl Fn(&(T, T)) -> Result<(NT, NT), Box<dyn Error + Send + Sync>> + Copy,
    ) -> Result<Self::Output, Box<dyn Error + Send + Sync>> {
        Ok(MultiLineString(
            self.0
                .iter()
                .map(|l| l.try_map_coords(func))
                .collect::<Result<Vec<_>, Box<dyn Error + Send + Sync>>>()?,
        ))
    }
}

impl<T: CoordinateType> MapCoordsInplace<T> for MultiLineString<T> {
    fn map_coords_inplace(&mut self, func: impl Fn(&(T, T)) -> (T, T) + Copy) {
        for p in &mut self.0 {
            p.map_coords_inplace(func);
        }
    }
}

impl<T: CoordinateType, NT: CoordinateType> MapCoords<T, NT> for MultiPolygon<T> {
    type Output = MultiPolygon<NT>;

    fn map_coords(&self, func: impl Fn(&(T, T)) -> (NT, NT) + Copy) -> Self::Output {
        MultiPolygon(self.iter().map(|p| p.map_coords(func)).collect())
    }
}

impl<T: CoordinateType, NT: CoordinateType> TryMapCoords<T, NT> for MultiPolygon<T> {
    type Output = MultiPolygon<NT>;

    fn try_map_coords(
        &self,
        func: impl Fn(&(T, T)) -> Result<(NT, NT), Box<dyn Error + Send + Sync>> + Copy,
    ) -> Result<Self::Output, Box<dyn Error + Send + Sync>> {
        Ok(MultiPolygon(
            self.0
                .iter()
                .map(|p| p.try_map_coords(func))
                .collect::<Result<Vec<_>, Box<dyn Error + Send + Sync>>>()?,
        ))
    }
}

impl<T: CoordinateType> MapCoordsInplace<T> for MultiPolygon<T> {
    fn map_coords_inplace(&mut self, func: impl Fn(&(T, T)) -> (T, T) + Copy) {
        for p in &mut self.0 {
            p.map_coords_inplace(func);
        }
    }
}

impl<T: CoordinateType, NT: CoordinateType> MapCoords<T, NT> for Geometry<T> {
    type Output = Geometry<NT>;

    fn map_coords(&self, func: impl Fn(&(T, T)) -> (NT, NT) + Copy) -> Self::Output {
        match *self {
            Geometry::Point(ref x) => Geometry::Point(x.map_coords(func)),
            Geometry::Line(ref x) => Geometry::Line(x.map_coords(func)),
            Geometry::LineString(ref x) => Geometry::LineString(x.map_coords(func)),
            Geometry::Polygon(ref x) => Geometry::Polygon(x.map_coords(func)),
            Geometry::MultiPoint(ref x) => Geometry::MultiPoint(x.map_coords(func)),
            Geometry::MultiLineString(ref x) => Geometry::MultiLineString(x.map_coords(func)),
            Geometry::MultiPolygon(ref x) => Geometry::MultiPolygon(x.map_coords(func)),
            Geometry::GeometryCollection(ref x) => Geometry::GeometryCollection(x.map_coords(func)),
            Geometry::Rect(ref x) => Geometry::Rect(x.map_coords(func)),
            Geometry::Triangle(ref x) => Geometry::Triangle(x.map_coords(func)),
        }
    }
}

impl<T: CoordinateType, NT: CoordinateType> TryMapCoords<T, NT> for Geometry<T> {
    type Output = Geometry<NT>;

    fn try_map_coords(
        &self,
        func: impl Fn(&(T, T)) -> Result<(NT, NT), Box<dyn Error + Send + Sync>> + Copy,
    ) -> Result<Self::Output, Box<dyn Error + Send + Sync>> {
        match *self {
            Geometry::Point(ref x) => Ok(Geometry::Point(x.try_map_coords(func)?)),
            Geometry::Line(ref x) => Ok(Geometry::Line(x.try_map_coords(func)?)),
            Geometry::LineString(ref x) => Ok(Geometry::LineString(x.try_map_coords(func)?)),
            Geometry::Polygon(ref x) => Ok(Geometry::Polygon(x.try_map_coords(func)?)),
            Geometry::MultiPoint(ref x) => Ok(Geometry::MultiPoint(x.try_map_coords(func)?)),
            Geometry::MultiLineString(ref x) => {
                Ok(Geometry::MultiLineString(x.try_map_coords(func)?))
            }
            Geometry::MultiPolygon(ref x) => Ok(Geometry::MultiPolygon(x.try_map_coords(func)?)),
            Geometry::GeometryCollection(ref x) => {
                Ok(Geometry::GeometryCollection(x.try_map_coords(func)?))
            }
            Geometry::Rect(ref x) => Ok(Geometry::Rect(x.try_map_coords(func)?)),
            Geometry::Triangle(ref x) => Ok(Geometry::Triangle(x.try_map_coords(func)?)),
        }
    }
}

impl<T: CoordinateType> MapCoordsInplace<T> for Geometry<T> {
    fn map_coords_inplace(&mut self, func: impl Fn(&(T, T)) -> (T, T) + Copy) {
        match *self {
            Geometry::Point(ref mut x) => x.map_coords_inplace(func),
            Geometry::Line(ref mut x) => x.map_coords_inplace(func),
            Geometry::LineString(ref mut x) => x.map_coords_inplace(func),
            Geometry::Polygon(ref mut x) => x.map_coords_inplace(func),
            Geometry::MultiPoint(ref mut x) => x.map_coords_inplace(func),
            Geometry::MultiLineString(ref mut x) => x.map_coords_inplace(func),
            Geometry::MultiPolygon(ref mut x) => x.map_coords_inplace(func),
            Geometry::GeometryCollection(ref mut x) => x.map_coords_inplace(func),
            Geometry::Rect(ref mut x) => x.map_coords_inplace(func),
            Geometry::Triangle(ref mut x) => x.map_coords_inplace(func),
        }
    }
}

impl<T: CoordinateType, NT: CoordinateType> MapCoords<T, NT> for GeometryCollection<T> {
    type Output = GeometryCollection<NT>;

    fn map_coords(&self, func: impl Fn(&(T, T)) -> (NT, NT) + Copy) -> Self::Output {
        GeometryCollection(self.iter().map(|g| g.map_coords(func)).collect())
    }
}

impl<T: CoordinateType, NT: CoordinateType> TryMapCoords<T, NT> for GeometryCollection<T> {
    type Output = GeometryCollection<NT>;

    fn try_map_coords(
        &self,
        func: impl Fn(&(T, T)) -> Result<(NT, NT), Box<dyn Error + Send + Sync>> + Copy,
    ) -> Result<Self::Output, Box<dyn Error + Send + Sync>> {
        Ok(GeometryCollection(
            self.0
                .iter()
                .map(|g| g.try_map_coords(func))
                .collect::<Result<Vec<_>, Box<dyn Error + Send + Sync>>>()?,
        ))
    }
}

impl<T: CoordinateType> MapCoordsInplace<T> for GeometryCollection<T> {
    fn map_coords_inplace(&mut self, func: impl Fn(&(T, T)) -> (T, T) + Copy) {
        for p in &mut self.0 {
            p.map_coords_inplace(func);
        }
    }
}

fn normalize_rect_bounds<T: PartialOrd>(min: &mut (T, T), max: &mut (T, T)) {
    use std::mem::swap;
    if min.0 > max.0 {
        swap(&mut min.0, &mut max.0);
    }
    if min.1 > max.1 {
        swap(&mut min.1, &mut max.1);
    }
}

impl<T: CoordinateType, NT: CoordinateType> MapCoords<T, NT> for Rect<T> {
    type Output = Rect<NT>;

    fn map_coords(&self, func: impl Fn(&(T, T)) -> (NT, NT) + Copy) -> Self::Output {
        let mut new_min = func(&self.min().x_y());
        let mut new_max = func(&self.max().x_y());
        normalize_rect_bounds(&mut new_min, &mut new_max);

        Rect::new(
            Coordinate {
                x: new_min.0,
                y: new_min.1,
            },
            Coordinate {
                x: new_max.0,
                y: new_max.1,
            },
        )
    }
}

impl<T: CoordinateType, NT: CoordinateType> TryMapCoords<T, NT> for Rect<T> {
    type Output = Rect<NT>;

    fn try_map_coords(
        &self,
        func: impl Fn(&(T, T)) -> Result<(NT, NT), Box<dyn Error + Send + Sync>>,
    ) -> Result<Self::Output, Box<dyn Error + Send + Sync>> {
        let mut new_min = func(&(self.min().x, self.min().y))?;
        let mut new_max = func(&(self.max().x, self.max().y))?;
        normalize_rect_bounds(&mut new_min, &mut new_max);

        Ok(Rect::new(
            Coordinate {
                x: new_min.0,
                y: new_min.1,
            },
            Coordinate {
                x: new_max.0,
                y: new_max.1,
            },
        ))
    }
}

impl<T: CoordinateType> MapCoordsInplace<T> for Rect<T> {
    fn map_coords_inplace(&mut self, func: impl Fn(&(T, T)) -> (T, T)) {
        let mut new_min = func(&self.min().x_y());
        let mut new_max = func(&self.max().x_y());

        normalize_rect_bounds(&mut new_min, &mut new_max);
        let mut new_rect = Rect::new(new_min, new_max);

        ::std::mem::swap(self, &mut new_rect);
    }
}

impl<T: CoordinateType, NT: CoordinateType> MapCoords<T, NT> for Triangle<T> {
    type Output = Triangle<NT>;

    fn map_coords(&self, func: impl Fn(&(T, T)) -> (NT, NT) + Copy) -> Self::Output {
        let p1 = func(&self.0.x_y());
        let p2 = func(&self.1.x_y());
        let p3 = func(&self.2.x_y());

        Triangle(
            Coordinate { x: p1.0, y: p1.1 },
            Coordinate { x: p2.0, y: p2.1 },
            Coordinate { x: p3.0, y: p3.1 },
        )
    }
}

impl<T: CoordinateType, NT: CoordinateType> TryMapCoords<T, NT> for Triangle<T> {
    type Output = Triangle<NT>;

    fn try_map_coords(
        &self,
        func: impl Fn(&(T, T)) -> Result<(NT, NT), Box<dyn Error + Send + Sync>>,
    ) -> Result<Self::Output, Box<dyn Error + Send + Sync>> {
        let p1 = func(&self.0.x_y())?;
        let p2 = func(&self.1.x_y())?;
        let p3 = func(&self.2.x_y())?;

        Ok(Triangle(
            Coordinate { x: p1.0, y: p1.1 },
            Coordinate { x: p2.0, y: p2.1 },
            Coordinate { x: p3.0, y: p3.1 },
        ))
    }
}

impl<T: CoordinateType> MapCoordsInplace<T> for Triangle<T> {
    fn map_coords_inplace(&mut self, func: impl Fn(&(T, T)) -> (T, T)) {
        let p1 = func(&self.0.x_y());
        let p2 = func(&self.1.x_y());
        let p3 = func(&self.2.x_y());

        let mut new_triangle = Triangle(
            Coordinate { x: p1.0, y: p1.1 },
            Coordinate { x: p2.0, y: p2.1 },
            Coordinate { x: p3.0, y: p3.1 },
        );

        ::std::mem::swap(self, &mut new_triangle);
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{polygon, Coordinate};

    #[test]
    fn point() {
        let p = Point::new(10., 10.);
        let new_p = p.map_coords(|&(x, y)| (x + 10., y + 100.));
        assert_relative_eq!(new_p.x(), 20.);
        assert_relative_eq!(new_p.y(), 110.);
    }

    #[test]
    fn point_inplace() {
        let mut p2 = Point::new(10f32, 10f32);
        p2.map_coords_inplace(|&(x, y)| (x + 10., y + 100.));
        assert_relative_eq!(p2.x(), 20.);
        assert_relative_eq!(p2.y(), 110.);
    }

    #[test]
    fn rect_inplace() {
        let mut rect = Rect::new((10, 10), (20, 20));
        rect.map_coords_inplace(|&(x, y)| (x + 10, y + 20));
        assert_eq!(rect.min(), Coordinate { x: 20, y: 30 });
        assert_eq!(rect.max(), Coordinate { x: 30, y: 40 });
    }

    #[test]
    fn rect_inplace_normalized() {
        let mut rect = Rect::new((2, 2), (3, 3));
        // Rect's enforce that rect.min is up and left of p2.  Here we test that the points are
        // normalized into a valid rect, regardless of the order they are mapped.
        rect.map_coords_inplace(|&pt| {
            match pt {
                // old min point maps to new max point
                (2, 2) => (4, 4),
                // old max point maps to new min point
                (3, 3) => (1, 1),
                _ => panic!("unexpected point"),
            }
        });

        assert_eq!(rect.min(), Coordinate { x: 1, y: 1 });
        assert_eq!(rect.max(), Coordinate { x: 4, y: 4 });
    }

    #[test]
    fn rect_map_coords() {
        let rect = Rect::new((10, 10), (20, 20));
        let another_rect = rect.map_coords(|&(x, y)| (x + 10, y + 20));
        assert_eq!(another_rect.min(), Coordinate { x: 20, y: 30 });
        assert_eq!(another_rect.max(), Coordinate { x: 30, y: 40 });
    }

    #[test]
    fn rect_try_map_coords() {
        let rect = Rect::new((10, 10), (20, 20));
        let result = rect.try_map_coords(|&(x, y)| Ok((x + 10, y + 20)));
        assert!(result.is_ok());
    }

    #[test]
    fn rect_try_map_coords_normalized() {
        let rect = Rect::new((2, 2), (3, 3));
        // Rect's enforce that rect.min is up and left of p2.  Here we test that the points are
        // normalized into a valid rect, regardless of the order they are mapped.
        let new_rect = rect
            .try_map_coords(|&pt| {
                match pt {
                    // old min point maps to new max point
                    (2, 2) => Ok((4, 4)),
                    // old max point maps to new min point
                    (3, 3) => Ok((1, 1)),
                    _ => panic!("unexpected point"),
                }
            })
            .unwrap();
        assert_eq!(new_rect.min(), Coordinate { x: 1, y: 1 });
        assert_eq!(new_rect.max(), Coordinate { x: 4, y: 4 });
    }

    #[test]
    fn line() {
        let line = Line::from([(0., 0.), (1., 2.)]);
        assert_eq!(
            line.map_coords(|&(x, y)| (x * 2., y)),
            Line::from([(0., 0.), (2., 2.)])
        );
    }

    #[test]
    fn linestring() {
        let line1: LineString<f32> = LineString::from(vec![(0., 0.), (1., 2.)]);
        let line2 = line1.map_coords(|&(x, y)| (x + 10., y - 100.));
        assert_eq!(line2.0[0], Coordinate::from((10., -100.)));
        assert_eq!(line2.0[1], Coordinate::from((11., -98.)));
    }

    #[test]
    fn polygon() {
        let exterior = LineString::from(vec![(0., 0.), (1., 1.), (1., 0.), (0., 0.)]);
        let interiors = vec![LineString::from(vec![
            (0.1, 0.1),
            (0.9, 0.9),
            (0.9, 0.1),
            (0.1, 0.1),
        ])];
        let p = Polygon::new(exterior, interiors);

        let p2 = p.map_coords(|&(x, y)| (x + 10., y - 100.));

        let exterior2 =
            LineString::from(vec![(10., -100.), (11., -99.), (11., -100.), (10., -100.)]);
        let interiors2 = vec![LineString::from(vec![
            (10.1, -99.9),
            (10.9, -99.1),
            (10.9, -99.9),
            (10.1, -99.9),
        ])];
        let expected_p2 = Polygon::new(exterior2, interiors2);

        assert_eq!(p2, expected_p2);
    }

    #[test]
    fn multipoint() {
        let p1 = Point::new(10., 10.);
        let p2 = Point::new(0., -100.);
        let mp = MultiPoint(vec![p1, p2]);

        assert_eq!(
            mp.map_coords(|&(x, y)| (x + 10., y + 100.)),
            MultiPoint(vec![Point::new(20., 110.), Point::new(10., 0.)])
        );
    }

    #[test]
    fn multilinestring() {
        let line1: LineString<f32> = LineString::from(vec![(0., 0.), (1., 2.)]);
        let line2: LineString<f32> = LineString::from(vec![(-1., 0.), (0., 0.), (1., 2.)]);
        let mline = MultiLineString(vec![line1, line2]);
        let mline2 = mline.map_coords(|&(x, y)| (x + 10., y - 100.));
        assert_eq!(
            mline2,
            MultiLineString(vec![
                LineString::from(vec![(10., -100.), (11., -98.)]),
                LineString::from(vec![(9., -100.), (10., -100.), (11., -98.)]),
            ])
        );
    }

    #[test]
    fn multipolygon() {
        let poly1 = polygon![
            (x: 0., y: 0.),
            (x: 10., y: 0.),
            (x: 10., y: 10.),
            (x: 0., y: 10.),
            (x: 0., y: 0.),
        ];
        let poly2 = polygon![
            exterior: [
                (x: 11., y: 11.),
                (x: 20., y: 11.),
                (x: 20., y: 20.),
                (x: 11., y: 20.),
                (x: 11., y: 11.),
            ],
            interiors: [
                [
                    (x: 13., y: 13.),
                    (x: 13., y: 17.),
                    (x: 17., y: 17.),
                    (x: 17., y: 13.),
                    (x: 13., y: 13.),
                ]
            ],
        ];

        let mp = MultiPolygon(vec![poly1, poly2]);
        let mp2 = mp.map_coords(|&(x, y)| (x * 2., y + 100.));
        assert_eq!(mp2.0.len(), 2);
        assert_eq!(
            mp2.0[0],
            polygon![
                (x: 0., y: 100.),
                (x: 20., y: 100.),
                (x: 20., y: 110.),
                (x: 0., y: 110.),
                (x: 0., y: 100.),
            ],
        );
        assert_eq!(
            mp2.0[1],
            polygon![
                exterior: [
                    (x: 22., y: 111.),
                    (x: 40., y: 111.),
                    (x: 40., y: 120.),
                    (x: 22., y: 120.),
                    (x: 22., y: 111.),
                ],
                interiors: [
                    [
                        (x: 26., y: 113.),
                        (x: 26., y: 117.),
                        (x: 34., y: 117.),
                        (x: 34., y: 113.),
                        (x: 26., y: 113.),
                    ],
                ],
            ],
        );
    }

    #[test]
    fn geometrycollection() {
        let p1 = Geometry::Point(Point::new(10., 10.));
        let line1 = Geometry::LineString(LineString::from(vec![(0., 0.), (1., 2.)]));

        let gc = GeometryCollection(vec![p1, line1]);

        assert_eq!(
            gc.map_coords(|&(x, y)| (x + 10., y + 100.)),
            GeometryCollection(vec![
                Geometry::Point(Point::new(20., 110.)),
                Geometry::LineString(LineString::from(vec![(10., 100.), (11., 102.)])),
            ])
        );
    }

    #[test]
    fn convert_type() {
        let p1: Point<f64> = Point::new(1., 2.);
        let p2: Point<f32> = p1.map_coords(|&(x, y)| (x as f32, y as f32));
        assert_relative_eq!(p2.x(), 1f32);
        assert_relative_eq!(p2.y(), 2f32);
    }

    #[cfg(feature = "use-proj")]
    #[test]
    fn test_fallible_proj() {
        use proj::Proj;
        let from = "EPSG:4326";
        let to = "EPSG:2230";
        let to_feet = Proj::new_known_crs(&from, &to, None).unwrap();

        let f = |x: f64, y: f64| {
            let shifted = to_feet.convert((x, y))?;
            Ok((shifted.x(), shifted.y()))
        };
        // 👽
        let usa_m = Point::new(-115.797615, 37.2647978);
        let usa_ft = usa_m.try_map_coords(|&(x, y)| f(x, y)).unwrap();
        assert_eq!(6693625.67217475, usa_ft.x());
        assert_eq!(3497301.5918027186, usa_ft.y());
    }

    #[test]
    fn test_fallible() {
        let f = |x: f64, y: f64| {
            if relative_ne!(x, 2.0) {
                Ok((x * 2., y + 100.))
            } else {
                Err("Ugh".into())
            }
        };
        // this should produce an error
        let bad_ls: LineString<_> = vec![
            Point::new(1.0, 1.0),
            Point::new(2.0, 2.0),
            Point::new(3.0, 3.0),
        ]
        .into();
        // this should be fine
        let good_ls: LineString<_> = vec![
            Point::new(1.0, 1.0),
            Point::new(2.1, 2.0),
            Point::new(3.0, 3.0),
        ]
        .into();
        let bad = bad_ls.try_map_coords(|&(x, y)| f(x, y));
        assert!(bad.is_err());
        let good = good_ls.try_map_coords(|&(x, y)| f(x, y));
        assert!(good.is_ok());
        assert_eq!(
            good.unwrap(),
            vec![
                Point::new(2., 101.),
                Point::new(4.2, 102.),
                Point::new(6.0, 103.),
            ]
            .into()
        );
    }

    #[test]
    fn rect_map_invert_coords() {
        let rect = Rect::new(Coordinate { x: 0., y: 0. }, Coordinate { x: 1., y: 1. });

        // This call should not panic even though Rect::new
        // constructor panics if min coords > max coords
        rect.map_coords(|&(x, y)| (-x, -y));
    }
}