メインコンテンツまでスキップ

Long tap animation

This example demonstrates how to animate the camera to a long-tapped coordinate on a map using the Mapbox Maps SDK for iOS.

The example uses map gestures and handles the long-press gesture with the onMapLongPress event. When a long press is detected, a blue marker icon is added to the tapped location on the map, the cameraOptions object is updated and the camera smoothly pans to the new coordinate with a duration of 0.5 seconds. Additionally, haptic feedback is provided upon a long press gesture, enhancing the user experience.

iOS Examples App Available

This example code is part of the Maps SDK for iOS Examples App, a working iOS project available on Github. iOS developers are encouraged to run the examples app locally to interact with this example in an emulator and explore other features of the Maps SDK.

See our Run the Maps SDK for iOS Examples App tutorial for step-by-step instructions.

LongTapAnimationExample.swift
import MapboxMaps
import UIKit

// This examples shows how to animate camera to a long-tapped coordinate.
final class ViewController: UIViewController {
private var mapView: MapView!
private var pointAnnotationManager: PointAnnotationManager!
private var cancelables = Set<AnyCancelable>()

override func viewDidLoad() {
super.viewDidLoad()

// Center the map over the United States.
let centerCoordinate = CLLocationCoordinate2D(latitude: 39.368279,
longitude: -97.646484)
let options = MapInitOptions(cameraOptions: CameraOptions(center: centerCoordinate, zoom: 2.4))

mapView = MapView(frame: view.bounds, mapInitOptions: options)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(mapView)

mapView.mapboxMap.onMapLoaded.observeNext { [weak self] _ in
try? self?.mapView.mapboxMap.addImage(UIImage(named: "intermediate-pin")!, id: .blueMarker)



}.store(in: &cancelables)

mapView.gestures.onMapLongPress.observe { [weak self] context in
self?.handleLongPress(at: context.point)
}.store(in: &cancelables)

pointAnnotationManager = mapView.annotations.makePointAnnotationManager()
}

private func handleLongPress(at location: CGPoint) {
haptic()
let coordinate = mapView.mapboxMap.coordinate(for: location)

var annotation = PointAnnotation(point: Point(coordinate))
annotation.iconImage = .blueMarker
annotation.iconOffset = [0, 12]
pointAnnotationManager.annotations.append(annotation)

let camera = CameraOptions(center: coordinate)
mapView.camera.ease(to: camera, duration: 0.5)
}

private func haptic() {
let impactFeedbackGenerator = UIImpactFeedbackGenerator(style: .heavy)
impactFeedbackGenerator.impactOccurred()
}
}

private extension String {
static let blueMarker = "blue-marker"
}
このexampleは役に立ちましたか?