使用Mapbox制作自定义位置注释

时间:2017-11-22 20:30:44

标签: swift geocoding mapbox reverse-geocoding

我正在使用Mapbox创建我的应用。当我点击一个按钮时,我希望它标记我当前的位置,并像现在一样添加一个标记。然后我想要点击这个标记并让它显示当前的位置信息,例如标记点的地址。

现在我所拥有的只是......

https://imgur.com/a/RSx0G

我想说明我使用的是Xcode 9.1和Swift 4.感谢您提前提供所有反馈。

目前swift文件看起来像......

import Foundation
import UIKit
import CoreLocation
import Mapbox
import MapKit
import MapboxGeocoder

class SecondViewController: UIViewController, CLLocationManagerDelegate, MGLMapViewDelegate, UITextFieldDelegate {

let geocoder = Geocoder.shared

let dismissesAutomatically: Bool = false
let isAnchoredToAnnotation: Bool = true

weak var delegate: MGLCalloutViewDelegate?

let tipHeight: CGFloat = 10.0
let tipWidth: CGFloat = 20.0

@IBOutlet var mapView: MGLMapView!
let manager = CLLocationManager()

override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}

@IBAction func markStuff(_ sender: Any) {
}
@IBAction func refLocation(_ sender: Any) {
manager.startUpdatingLocation()

}
func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
return true
}


func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
return nil
}

    func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation)
{

 print("tap on callout")

}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]

let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)

mapView.setCenter(center, zoomLevel: 10, animated: true)

let annotation = MGLPointAnnotation()

annotation.coordinate = location.coordinate

mapView.selectAnnotation(annotation, animated: true)

annotation.title = "Testing"
annotation.subtitle = "\(annotation.coordinate.latitude), \(annotation.coordinate.longitude)"

self.mapView.addAnnotation(annotation)

manager.stopUpdatingLocation()

1 个答案:

答案 0 :(得分:1)

您可以创建MGLUserLocationAnnotationView的子类,然后将其用作YourLocationAnnotationView()注释的视图。

例如,如果您的自定义子类名为func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {This custom view is created below. if annotation is MGLUserLocation && mapView.userLocation != nil { return YourLocationAnnotationView() } return nil } } ,则可以执行以下操作:

env.sh

要完整实施,请从官方文档中see this example