如何在iPhone地图上显示用户的位置和其他点?

时间:2010-03-29 09:40:52

标签: iphone mkmapview core-location

基本上我想显示用户位置以及地图上所选位置的列表。它甚至可以有标准的iphone注释。但是,我不知道我将采取的一般步骤来实现这一目标。我会使用MKMapView或核心位置,还是两者都使用?有人可以给我一个简单的步骤概述,或者链接到一个好的教程或示例代码。谢谢

为了扩展,我想知道是否有任何关于如何处理位置数组的例子。我猜我需要识别用户位置然后设置一个半径,我想要远离用户引用位置,然后使用适合该半径的位置数组填充该半径。我的想法是否正确?是否有任何关于如何做至少一部分的例子。我已经看到了大量关于如何显示单个位置的示例,但没有一个处理多个位置。

2 个答案:

答案 0 :(得分:5)

这是我正在使用的东西,可以帮助你。它将为您提供适合CLLocations数组的MKCoordinateRegion。然后,您可以使用该区域将其传递给MKMapView setRegion:animated:

// create a region that fill fit all the locations in it
+ (MKCoordinateRegion) getRegionThatFitsLocations:(NSArray *)locations {
    // initialize to minimums, maximums
    CLLocationDegrees minLatitude = 90;
    CLLocationDegrees maxLatitude = -90;
    CLLocationDegrees minLongitude = 180;
    CLLocationDegrees maxLongitude = -180;

    // establish the min and max latitude and longitude
    // of all the locations in the array
    for (CLLocation *location in locations) {
        if (location.coordinate.latitude < minLatitude) {
            minLatitude = location.coordinate.latitude;
        }
        if (location.coordinate.latitude > maxLatitude) {
            maxLatitude = location.coordinate.latitude;
        }
        if (location.coordinate.longitude < minLongitude) {
            minLongitude = location.coordinate.longitude;
        }
        if (location.coordinate.longitude > maxLongitude) {
            maxLongitude = location.coordinate.longitude;
        }
    }

    MKCoordinateSpan span;
    CLLocationCoordinate2D center;
    if ([locations count] > 1) {
        // for more than one location, the span is the diff between
        // min and max latitude and longitude
        span =  MKCoordinateSpanMake(maxLatitude - minLatitude, maxLongitude - minLongitude);
        // and the center is the min + the span (width) / 2
        center.latitude = minLatitude + span.latitudeDelta / 2;
        center.longitude = minLongitude + span.longitudeDelta / 2;
    } else {
        // for a single location make a fixed size span (pretty close in zoom)
        span =  MKCoordinateSpanMake(0.01, 0.01);
        // and the center equal to the coords of the single point
        // which will be the coords of the min (or max) coords 
        center.latitude = minLatitude;
        center.longitude = minLongitude;
    }

    // create a region from the center and span
    return MKCoordinateRegionMake(center, span);
}

由于您可能已经建立,因此您需要使用MKMapView和Core Location来执行您想要的操作。在我的应用程序中,我知道我想要显示的位置,然后使MKMapView足够大以适应它们。上面的方法将帮助你做到这一点。但是,如果你想获得一个适合给定地图区域的位置列表,那么你必须做的或多或少与我上面所做的相反。

答案 1 :(得分:3)

相关问题