2017-03-23 34 views
0

我想創建一個MKCoordinateRegion,其中用戶位置在中心,另一個座標應該在該區域內可見。簡而言之,我試圖以用戶位置爲中心,同時可以看到一定數量的註釋。我的方法是查看第N個最遠的座標所在的位置,並嘗試計算距離或座標區域,以此座標形成用戶位置座標。兩個座標之間的緯度/縱向差值是多少?

var topLeftCoord = CLLocationCoordinate2D(latitude: -90.0, longitude: 180.0) 
    var bottomRightCoord = CLLocationCoordinate2D(latitude: 90.0, longitude: -180.0) 

    topLeftCoord.longitude = fmin(topLeftCoord.longitude, outerLongitude) 
    topLeftCoord.latitude = fmax(topLeftCoord.latitude, outerLatitude) 
    bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, outerLongitude) 
    bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, outerLatitude) 

    topLeftCoord.longitude = fmin(topLeftCoord.longitude, userCoordinates.longitude) 
    topLeftCoord.latitude = fmax(topLeftCoord.latitude, userCoordinates.latitude) 
    bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, userCoordinates.longitude) 
    bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, userCoordinates.latitude) 

    let regionSpan = MKCoordinateSpanMake(fabs((topLeftCoord.latitude - bottomRightCoord.latitude)), fabs((bottomRightCoord.longitude - topLeftCoord.longitude))) 
    var region = MKCoordinateRegion(center: userCoordinates, span: regionSpan) 

    region = self.mapView.regionThatFits(region) 
    self.mapView.setRegion(region, animated: true) 

這種作品,但我得到了一點偏離。我相信問題在於,在這裏我沒有考慮到用戶位置應該位於中心位置,因此此代碼只是確保用戶和outerLatitudeouterLongitude的座標位於該範圍內。但是,當以用戶座標爲中心時,外部座標不再可見。

我不能爲我的生活弄清楚這一點。我也試過這樣做:

let outerLocation = CLLocation(latitude: outerLatitude, longitude: outerLongitude) 
    let userLocation = CLLocation(latitude: userCoordinates.latitude, longitude: userCoordinates.longitude) 

    let distance = userLocation.distance(from: outerLocation) 
    var region = MKCoordinateRegionMakeWithDistance(userCoordinates, distance, distance) 

    region = self.mapView.regionThatFits(region) 
    self.mapView.setRegion(region, animated: true) 

但我最終以相同的結果,我真的不明白。我得到了一個340米左右的距離(這很合理)。但MKCoordinateRegionMakeWithDistance要求latitudinalMeterslongitudinalMeters其中我只需發送distance從座標A到B.我找不到方法將組件拆分爲latitudinalMeterslongitudinalMeters,我可以簡單地在兩者之間獲得1個距離。

回答

0

我無法找到一個方法來拆分部件爲latitudinalMeters和longitudinalMeters,我可以簡單地得到兩個

之間距離1創建嘗試與同緯度的一個新的起點爲您的用戶位置並與您的外部位置具有相同的經度並使用它獲得「緯度距離」

然後創建一個與用戶位置相同的緯度和與外部位置相同的緯度的點,並使用它獲得縱向距離。

注意:如果外點比用戶點更靠近赤道,則可能需要使用兩個新點的外點緯度來獲取緯度。

+0

結果幾乎相同。我必須在這裏做其他事情。 – ClockWise

0

還有另一種方式

var region = MKCoordinateRegionMake(userLocation!, MKCoordinateSpanMake(4 * abs(destination.latitude - userLocation!.latitude), 4 * abs(destination.longitude - userLocation!.longitude))) 
self.mapView.setRegion(region2, animated: true) 

我同乘玩了一下,以獲得正確的範圍內 - 但MKCoordinateSpanMake將在經/緯度的差異,你確實有可用的工作。看起來你至少需要將計算出的角度差異加倍,如果你希望你的用戶位置居中,那麼我們應該做一些事情,找出經緯度哪個更大,然後使用它們。

這應該讓你朝着正確的方向前進。

相關問題