I want to expand the tap area of custom annotations in MapKit. Specifically, I want to make the tap area the same size as the image frame, but it doesn't expand as expected and doesn't work correctly.
Details: The custom image is pinned at the coordinates of Yurakucho Station. The tap area is too precise, and I want it to activate when touching this yellow area (which is deliberately expanded and is an ImageView), but it doesn't work well when zooming in or out, as the coordinates shift.
import UIKit
import MapKit
import CoreLocation
class CustomAnnotationView: MKAnnotationView {
private let expandedTapArea: CGFloat = 20 // Amount to expand the tap area
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let targetArea = bounds.insetBy(dx: -expandedTapArea, dy: -expandedTapArea)
if targetArea.contains(point) {
return self
}
return nil
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let targetArea = bounds.insetBy(dx: -expandedTapArea, dy: -expandedTapArea)
return targetArea.contains(point)
}
}
class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
var mapView: MKMapView!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Map setup
mapView = MKMapView()
mapView.frame = view.bounds
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.showsUserLocation = true
view.addSubview(mapView)
// Adding pin for Yurakucho Station
let yurakuchoLocation = CLLocationCoordinate2D(latitude: 35.675069, longitude: 139.763328)
let yurakuchoPin = MKPointAnnotation()
yurakuchoPin.coordinate = yurakuchoLocation
yurakuchoPin.title = "Yurakucho Station"
yurakuchoPin.subtitle = "Potato"
mapView.addAnnotation(yurakuchoPin)
mapView.delegate = self
}
// [The rest of the code continues as in your original text]
}
Thanks,