How to check validity of CLLocation in iOS

前端 未结 2 1217
清酒与你
清酒与你 2020-12-10 16:27

How to check validity of CLLocation in iOS?

In fact this is my situation,

I just create a new map

mapView = [[MKMapView alloc] i         


        
2条回答
  •  醉话见心
    2020-12-10 16:58

    To build on Anna K's explanation, it's general good practice to check the validity of a CLLocationCoordinate2DIsValid(YOURLOCATION).

    If you are getting lats and longs from a web service or a SQLite database, you should check and make sure the location is valid before trying to add an annotation to the map. Here's an example of this in action:

    for (int i = 0; i < [yourArray count]; i++) {
    
        YourOBJ *obj = [yourArray objectAtIndex:i];
    
        yourCLLocation2D.latitude = obj.latitude;
        yourCLLocation2D.longitude = obj.longitude;
    
        AnnotationPin *anno = [[AnnotationPin alloc] initWithCoordinate: yourCLLocation2D];
    
        if (CLLocationCoordinate2DIsValid(yourCLLocation2D))
        {
            anno.lat = obj.latitude;//Maybe you want to store lat
            anno.lon = obj.longitude;//and lon
            anno.title = obj.name//define the title
            anno.subtitle = obj.info//and subtitle for your annotation callout
            anno.yourLocation = yourCLLocation2D;//Some of these aren't necessary
            anno.tag = i;//but can really help to define and track pins
    
            [map addAnnotation:anno];
        }
    
        [anno release];
    }
    

    For all those who are having problems where you add a bunch of pins to a map successfully, and with the same code try to add another set of pins but the app crashes, try this asap. For those who have a similar situation in this example, but haven't ran into any problems, do this anyway! Your users might add an incorrect lat/lon combo and crash the app if you give them that functionality.

    Remember, (0,0) is a valid coordinate, so don't worry about this logic removing those if you are concerned about that. This is for those (-200,75) type coordinates that don't physically exist on planet Earth.

提交回复
热议问题