Updating MKMapView to CLPlacemark returned from CLGeocoder

只愿长相守 提交于 2019-12-01 07:09:28

问题


I want to be able to update the region displayed on a MKMapView by allowing the user to type in an address or location in a UIAlertView. I currently have:

        if (geocoder.geocoding)
            [geocoder cancelGeocode];

        [geocoder geocodeAddressString:[[alertView textFieldAtIndex:0] text] completionHandler:^(NSArray *placemarks, NSError *error) {
            if (!error) {
                NSLog(@"Found a location");
            } else {
                NSLog(@"Error in geocoding");
            }

            NSLog(@"Num found: %d", [placemarks count]);

            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            MKCoordinateRegion region;
            region.center.latitude = placemark.region.center.latitude;
            region.center.longitude = placemark.region.center.longitude;
            MKCoordinateSpan span;
            double radius = placemark.region.radius / 1000;

            NSLog(@"Radius is %f", radius);
            span.latitudeDelta = radius / 112.0;
            //span.longitudeDelta = ??? 

            region.span = span;

            NSLog(@"Region is %f %f %f", region.center.latitude, region.center.longitude, span.latitudeDelta);

            [mapView setRegion:region animated:YES];
        }];

My problem is I am unsure how to calculate the longitude delta.


回答1:


You could just set it equal to latitudeDelta and the map view will adjust as needed.

But you don't need to calculate the span yourself in the first place. You can use:

region = MKCoordinateRegionMakeWithDistance(
             placemark.region.center, 
             placemark.region.radius, 
             placemark.region.radius);

Not sure about the second part of your question.


In iOS 7 and higher, the region returned by the CLPlacemark is actually a CLCircularRegion (see Deprecated CLRegion methods - how to get radius?).

Although the original code will still work as-is, you may get a compiler warning that radius and center are deprecated.

To avoid the warning, cast the region as a CLCircularRegion:

CLCircularRegion *pmCircularRegion = (CLCircularRegion *)placemark.region;

region = MKCoordinateRegionMakeWithDistance(
         pmCircularRegion.center,
         pmCircularRegion.radius,
         pmCircularRegion.radius);


来源:https://stackoverflow.com/questions/9164920/updating-mkmapview-to-clplacemark-returned-from-clgeocoder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!