MKMapPoint distance method sometimes returns nan

I have a curious issue. I have a set of map points, and I'm trying to find the limits so I can create a snapshot (in swift).

I iterate over the set of points and find the max/min of the latitude and longitude values.

I then use these to determine width and height. This works great on a set of data once, but if you run it again (on the same set of data) I get -nan for width.

i.e. if you find min latitude, min/max longitude, then use these values to create mappings and calculate distance, you sometimes get NaN.

If I take the exact numbers (I debugged and confirmed the data is not changing) and put them in a test, it always fails with NaN

This always fails:

   func testCalc() {
      let minLatitude:CLLocationDegrees = 37.330144359999998
      let minLongitude:CLLocationDegrees = -122.04162370999998
      let maxLatitude:CLLocationDegrees = 37.33773012999999
      let maxLongitude:CLLocationDegrees = -122.02319471999999
      
      let pointsPerMeter = MKMapPointsPerMeterAtLatitude(minLatitude)
      
      let minPoint = MKMapPoint(CLLocationCoordinate2D(latitude: minLatitude, longitude: minLongitude))
      let widthPoint = MKMapPoint(CLLocationCoordinate2D(latitude: minLatitude, longitude: maxLongitude))
      var width = minPoint.distance(to: widthPoint)//meters
      var oWidth = widthPoint.distance(to: minPoint)//meters
      var height = minPoint.distance(to: MKMapPoint(CLLocationCoordinate2D(latitude: maxLatitude, longitude: minLongitude)))//meters

      // width will be NaN here [oWidth will not]
      XCTAssertTrue(width>0)
      width = minPoint.distance(to: MKMapPoint(CLLocationCoordinate2D(latitude: minLatitude, longitude: maxLongitude)))//meters
      XCTAssertTrue(width>0)
   }

I'll further note the minPoint and widthPoint are valid, but the distance calculation is NaN. If I reverse the two points (oWidth), it calculates correctly.

I guess I'll phrase this as should this be reliable, are there limits or ways to determine when it will be wrong?

I recommend GeographicLib for this sort of thing. It seems reliable, and if you did find any bugs you have the source so you can fix it yourself.

MKMapPoint distance method sometimes returns nan
 
 
Q