我想在两个坐标之间显示一个地图。我已经使用此代码显示包含两个坐标的地图的矩形。但是我的坐标都没有显示,而是显示了除坐标之外的两个坐标之间的区域。 我该怎么做才能包括我的两个坐标?
let coordinate1 = CLLocationCoordinate2DMake(28.53, 77.39)
let coordinate2 = CLLocationCoordinate2DMake(29.13,76.69)
// convert them to MKMapPoint
let p1 = MKMapPointForCoordinate (coordinate2);
let p2 = MKMapPointForCoordinate (coordinate1);
let mapRect = MKMapRectMake(fmin(p1.x,p2.x), fmin(p1.y,p2.y), fabs(p1.x-p2.x), fabs(p1.y-p2.y));
mapView.setVisibleMapRect(mapRect, animated: true)
答案 0 :(得分:1)
你可以尝试下面的功能,它使传递的点在地图中心:
func centerLocationInMapView(centerPoint: CLLocationCoordinate2D) {
floatForRadiusInMiles = 10.0 // you can ignore this i have taken this for my custom radius property
var scalingFactor: Double = abs((cos(2 * M_PI * centerPoint.latitude / 360.0)))
var coordinateSpan: MKCoordinateSpan = MKCoordinateSpanMake(floatForRadiusInMiles / 69.0, floatForRadiusInMiles / (scalingFactor * 69.0))
var coordinateRegion: MKCoordinateRegion = MKCoordinateRegionMake(centerPoint, coordinateSpan)
self.mapViewForHomeScreen.scrollEnabled = true
mapViewForHomeScreen.setRegion(coordinateRegion, animated: TRUE)
mapViewForHomeScreen.regionThatFits(coordinateRegion)
}
调用此函数
self.centerLocationInMapView( (first latitude + second latitude)/2 , (first longitude + second longitude)/2 )
传递两个lat之间的中心点,长,以便中心将是地图 中心!
答案 1 :(得分:1)
基本上是由于自动布局。我们应该使用mapViewDidFinishLoadingMap(mapView: MKMapView)
方法来设置它。
func mapViewDidFinishLoadingMap(mapView: MKMapView) {
// this is where visible maprect should be set
let coordinate1 = CLLocationCoordinate2DMake(28.53, 77.39)
let coordinate2 = CLLocationCoordinate2DMake(29.13,76.69)
// convert them to MKMapPoint
let p1 = MKMapPointForCoordinate (coordinate2);
let p2 = MKMapPointForCoordinate (coordinate1);
let mapRect = MKMapRectMake(fmin(p1.x,p2.x), fmin(p1.y,p2.y), fabs(p1.x-p2.x), fabs(p1.y-p2.y));
mapView.setVisibleMapRect(mapRect, animated: true)
}