Skip to content

Instantly share code, notes, and snippets.

@alexnikol
Created May 23, 2020
Embed
What would you like to do?
Direction Marker and Google Maps
class ViewController: UIViewController {
var mapView: GMSMapView! //Google Map View
var userMarker: GMSMarker! //Our Car marker
private let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
setupMap()
createMarker()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func setupMap() {
let camera = GMSCameraPosition(latitude: 37.3328113, longitude: -122.0411792, zoom: 15.0) //Start point for Map
let map = GMSMapView(frame: view.bounds, camera: camera) //Creation of Google Map View
self.view.addSubview(map)
mapView = map
}
func createMarker() {
let marker = GMSMarker()
marker.iconView = UserMarker(frame: CGRect(x: 0, y: 0, width: 48, height: 48)) //Our Custom Marker
marker.map = mapView //Draw this marker on the Google Map View
userMarker = marker
}
func updateMarkerWith(position: CLLocationCoordinate2D, angle: Double) {
userMarker.position = position
guard angle >= 0 && angle < 360 else {
return
}
let angleInRadians: CGFloat = CGFloat(angle) * .pi / CGFloat(180) //Form degrees to radians transformation
userMarker.iconView?.transform = CGAffineTransform.identity.rotated(by: angleInRadians) //Rotation of the marker
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else {
return
}
let point = CLLocationCoordinate2D(latitude: location.coordinate.latitude,
longitude: location.coordinate.longitude)
updateMarkerWith(position: point, angle: location.course)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment