首页 > 解决方案 > 在 iOS 的 MapKit 中显示一张特定的国家地图

问题描述

是否有可能使用 Swift在 iOS 中显示特定的国家地图?

我已经搜索了很多,但大多数其他答案都建议仅使用缩放效果绑定地图。

但我认为这对我来说不是正确的解决方案。

标签: iosmapkit

解决方案


请注意以下坐标是随机的,仅作为示例。

在您的快速代码中的某处,您将声明您的MKMapView

@IBOutlet var mapView: MKMapView!

稍后,可能在 中override func viewDidLoad()
您可以设置regionmapview 和span.

var location: CLLocationCoordinate2D!
var region: MKCoordinateRegion!
var span: MKCoordinateSpan!

mapView = MKMapView() // allocating a mapview, so setting the region makes sens.

location = CLLocationCoordinate2DMake(2.0, 1.0)
span = MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
region = MKCoordinateRegion.init(center: location, span: span)
mapView.setRegion(region, animated: true)

请记住,地图没有提供可供选择的国家和边界列表,但有一些服务可以帮助您按地址或国家名称查找位置坐标。

按国家名称查找地图区域的方法之一..
对不起,在objective-c中..

if (@available(iOS 13.0, *)) {
    MKPlacemark *placemark = nil;
    MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] initWithNaturalLanguageQuery:@"USA"];
    request.resultTypes = MKLocalSearchResultTypeAddress;
    MKLocalSearch *search = [[MKLocalSearch alloc] initWithRequest:request];
    [search startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
        if (!error) {
            [self.mapView setRegion:response.boundingRegion];
            
            //or do something with first result..
            //if ([response mapItems].count>0) {
                // MKPlacemark *placemark = [response mapItems].firstObject.placemark;
                // MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
                // and so on..
            //}
        }
    }];
}

或迅速

if #available(iOS 13.0, *) {
    
    let searchRequest = MKLocalSearch.Request()
    searchRequest.naturalLanguageQuery = "USA"
    
    let search = MKLocalSearch(request: searchRequest)
    
    search.start { response, error in
        guard let response = response else {
            print("Error: \(error?.localizedDescription ?? "Unknown error").")
            return
        }
        
        self.mapView.setRegion(response.boundingRegion, animated: true)
    }
}

推荐阅读