0

我正在寻找一种方法以适合所有视图的正确缩放,在我的应用程序实例中是一个注释和用户位置以及表示连接注释和用户位置的路线的整个折线。

我在下面有这段代码,每次地图加载地图视图时我都会调用它:

func mapViewDidFinishLoadingMap(_ mapView: MGLMapView) {
        if let location = mapView.userLocation?.location?.coordinate, let annotations = mapView.annotations {
                let coordinate = annotations.first?.coordinate
                mapView.setVisibleCoordinateBounds(MGLCoordinateBounds(sw: location, ne: coordinate!), edgePadding: UIEdgeInsetsMake(100, 50, 100, 200 ), animated: true)
        }
    }

这适用于路线几乎是线性的坐标,但当路线有点复杂和长时,它就没有帮助。

4

2 回答 2

1

无论多短或多长,此方法都会为您提供折线的边界。在这个例子中,你需要一个位置数组在你的 VC 中某个位置是 locationList: [CLLocation]。

func setCenterAndBounds() -> (center: CLLocationCoordinate2D, bounds: MGLCoordinateBounds)? {
    let latitudes = locationList.map { location -> Double in
        return location.coordinate.latitude
    }

    let longitudes = locationList.map { location -> Double in
        return location.coordinate.longitude
    }

    let maxLat = latitudes.max()!
    let minLat = latitudes.min()!
    let maxLong = longitudes.max()!
    let minLong = longitudes.min()!

    let center = CLLocationCoordinate2D(latitude: (minLat + maxLat) / 2, longitude: (minLong + maxLong) / 2)
    let span = MKCoordinateSpan(latitudeDelta: (maxLat - minLat) * 1.3, longitudeDelta: (maxLong - minLong) * 1.3)
    let region = MKCoordinateRegion(center: center, span: span)
    let southWest = CLLocationCoordinate2D(latitude: center.latitude - (region.span.latitudeDelta  / 2),
        longitude: center.longitude - (region.span.longitudeDelta / 2)
    )
    let northEast = CLLocationCoordinate2D(
        latitude: center.latitude + (region.span.latitudeDelta  / 2),
        longitude: center.longitude + (region.span.longitudeDelta / 2)
    )

    return (center, MGLCoordinateBounds(sw: southWest, ne: northEast))
}

然后你可以像这样设置 mapbox 视图:

func populateMap() {
    guard locationList.count > 0, let centerBounds = setCenterAndBounds() else { return }
    mapboxView.setCenter(centerBounds.center, animated: false)
    mapboxView.setVisibleCoordinateBounds(centerBounds.bounds, animated: true)}
于 2019-11-27T00:33:01.380 回答
0

如果您知道缩放级别使用Truf 的质心功能来获取多边形的质心,则将其应用于 MGL map.flyTo,如下所示:

    var centroid = turf.centroid(myCoolFeatureGeometry);

    map.flyTo({
      center: centroid.geometry.coordinates,
      zoom: 19,
      curve: 1,
      screenSpeed: 4,
      easing(t) {
        return t;
      }
    });

如果您还需要缩放级别,可以使用Turf 的 bbox(或信封)获取它并将其输出应用到 MGL map.fitbounds

var features = turf.featureCollection([
  turf.point([-75.343, 39.984], {"name": "Location A"}),
  turf.point([-75.833, 39.284], {"name": "Location B"}),
  turf.point([-75.534, 39.123], {"name": "Location C"})
]);

var enveloped = turf.envelope(features);

map.fitBounds(enveloped, {
  padding: {top: 10, bottom:25, left: 15, right: 5}
});
于 2017-12-13T19:51:34.537 回答