0

In my project I use LocationSearchTable / MKLocalSearch. When a user clicks on an item, my add annotation method is called in MapViewController:

func dropPinZoomIn(placemark: MKPlacemark) {

    // cache the pin
    selectedPin = placemark

    // create the pin
    let annotation = MKPointAnnotation()
    annotation.coordinate = placemark.coordinate
    annotation.title = placemark.name
    if  let streetNumber = placemark.subThoroughfare,
        let city = placemark.locality,
        let state = placemark.administrativeArea {
        annotation.subtitle = "\(streetNumber) \(city) \(state)"
    }

    // add the pin the the mapView
    mapView.addAnnotation(annotation)
    let span = MKCoordinateSpanMake(0.01, 0.01)
    let region = MKCoordinateRegionMake(annotation.coordinate, span)
    mapView.setRegion(region, animated: true)

    print(placemark.coordinate)
    print(placemark.coordinate.latitude)
    print(placemark.coordinate.longitude)

At the end, when I print the coordinate, I get a longer version whereas when I print the latitude and longitude separately, it rounds off the number near the end. This is causing me troubles later when I need to compare coordinates. How can I prevent this rounding? As an example, here are my results:

CLLocationCoordinate2D(latitude: 37.331413259110334, longitude: -122.03048408031462) CLLocationCoordinate2D(latitude: 37.3314132591103, . . longitude: -122.030484080315)

zachenn
  • 115
  • 2
  • 10

1 Answers1

1

Try the following code to prevent rounds off the number.

print(coordinate)
print(coordinate.latitude.debugDescription)
print(coordinate.longitude.debugDescription)

Result:

CLLocationCoordinate2D(latitude: -33.499989999999997, longitude: 150.255) -33.499989999999997 150.255

Note:

The type of coordinate.latitude/coordinate.longitude is CLLocationDegrees. This type is alias for Double. Comparing Double or Float values with == will not give the expected result in most programming languages, which means that numbers that you think should be equal are in fact slightly different. Instead compute the absolute difference and handle the numbers as equal if the difference is below some threshold. See Compare double to zero using epsilon for more explanations.

Kosuke Ogawa
  • 7,383
  • 3
  • 31
  • 52
  • It worked! That's all I needed was to add debugDescription to my latitude and longitude and everything else later falls into place. Thank you Kosuke :) – zachenn Sep 19 '17 at 05:33