How to Display User's Place on Snippet Google Maps Swift - swift

I have google map and want to display user's place (like city) in snippet.
How to do that?
here's my current code:
class ViewController: UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate{
#IBOutlet weak var mapView: GMSMapView!
var latitude = -7.034323799999999
var longitude = 110.42400399999997
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
mapView.delegate = self
let camera = GMSCameraPosition.camera(withLatitude: Double(latitude), longitude: Double(longitude), zoom: 17)
mapView.animate(to: camera)
let markerImage = UIImage(named: "ic_home_detail_marker_location")
let markerView = UIImageView(image: markerImage)
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(Double(latitude), Double(longitude))
marker.isDraggable = true
marker.snippet = "\(marker.position)"
mapView.selectedMarker = marker
marker.iconView = markerView
mapView.selectedMarker = marker
marker.map = mapView
}
}

If you want to get the user's city or state name you have to use CLGeocoder.
var currentLatitude:Double!
var currentLongitude:Double!
var cityName:String!
var stateName:String!
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("locationManager function called")
// Fetch current location coordinates
let locValue:CLLocationCoordinate2D = (locationManager.location?.coordinate)!
currentLatitude = locValue.latitude
currentLongitude = locValue.longitude
print("Current Location = \(currentLatitude!), \(currentLongitude!)")
// Zoom to current location
let camera: GMSCameraPosition = GMSCameraPosition.camera(withLatitude: currentLatitude!, longitude: currentLongitude!, zoom: 17.0)
viewMap.camera = camera
// check for current city
CLGeocoder().reverseGeocodeLocation(locationManager.location!, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
return
}
if (placemarks?.count)! > 0 {
let pm = placemarks?[0]
self.cityName = (pm?.locality)!
self.stateName = (pm?.administrativeArea)
print("Current City: \(self.cityName!)")
print("Curret State: \(self.stateName!)")
}
else {
print("Problem with the data received from geocoder")
}
})
locationManager.stopUpdatingLocation()
}
Now you have the current city stored in a variable.
The next step is that when the user touches a marker, it should display the cityname. For this to achieve implement this:
This delegate must be added:
GMSMapViewDelegate
and this is the marker function, when user taps on it.
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
mapView.delegate = self
marker.snippet = ("Current city: \(cityName!)")
// return false so as to show the marker details or
// return true to hide marker details.
return false
}

Related

Google Maps does not animate to user's location

I am trying to get my google maps map to center on my user's location. The user's location updates properly and shows the blue dot indicating their location. However, the camera, also set to the same coordinate locations, instead places itself at (0, 0). I have modified the program below so that it does move to the proper location after it loads. However, since my Bool is a state variable, it gives me a warning that I cannot update State variables during view updates. See the code below:
import SwiftUI
import GoogleMaps
import GoogleMapsUtils
struct GoogleMapsView: UIViewRepresentable {
#ObservedObject var locationManager = LocationManager()
var marker: GMSMarker = GMSMarker()
#Binding var heatmapWeightedData: [GMUWeightedLatLng]
#State var heatmapLayer = GMUHeatmapTileLayer()
#State var isCenteredOnCamera = false
func makeUIView(context: Context) -> GMSMapView {
let camera = GMSCameraPosition.camera(withLatitude: locationManager.latitude, longitude: locationManager.longitude, zoom: 15)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
heatmapLayer.radius = 75
heatmapLayer.weightedData = heatmapWeightedData
heatmapLayer.map = mapView
mapView.isMyLocationEnabled = true
return mapView
}
func updateUIView(_ mapView: GMSMapView, context: UIViewRepresentableContext<GoogleMapsView>) {
if self.isCenteredOnCamera == false {
mapView.animate(to: GMSCameraPosition(latitude: locationManager.latitude, longitude: locationManager.longitude, zoom: 15))
self.isCenteredOnCamera = true //Gives me the error
}
heatmapLayer.weightedData = heatmapWeightedData
heatmapLayer.map = mapView
}
}
Here is the locationManager code:
import Foundation
import CoreLocation
class LocationManager: NSObject, ObservableObject {
private let locationManager = CLLocationManager()
#Published var location: CLLocation? {
willSet { objectWillChange.send() }
}
var latitude: CLLocationDegrees {
return location?.coordinate.latitude ?? 0
}
var longitude: CLLocationDegrees {
return location?.coordinate.longitude ?? 0
}
override init() {
super.init()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
}
extension LocationManager: CLLocationManagerDelegate {
func locationManager( manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print(status)
}
func locationManager( manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else {
return
}
self.location = location
}
}
Presumably, the camera is just reading the optional longitude and latitude variables and setting them to 0, for reasons I do not know.
Is there a way for me to update the camera location just once so that it does not infinitely update the camera location? If so, what should I do?

How to focus Google Maps camera on user's current location at startup using swiftUI views

I'm trying to make an app that uses Google Maps and focuses on the user's location when the app is opened.
Right now I have the map initializing and im able to focus on the users location after pressing the 'myLocation' button that is inherent to GoogleMaps, BUT the map's camera keeps focusing to a specified location and not the users location.
I used these 2 tutorials to get to where I'm at now:
- https://developers.google.com/maps/documentation/ios-sdk/start
- https://www.raywenderlich.com/197-google-maps-ios-sdk-tutorial-getting-started
After searching Google and here, it seems like I need to utilize CLLocationManager() to get the user's device coordinates and then use that somehow? Im think my code regarding CLLocationManager() may be placed in the wrong file or is used incorrectly, but im not getting any errors.
My code works like this: SceneDelegate.swift sets my LandmarkList.swift as the rootViewController. Then the LandmarkList calls GoogMapView.swift to display the instance of Google maps.
SceneDelegate.swift:
I think my usage of locationManager here may be wrong?
import UIKit
import SwiftUI
import GoogleMaps
import GooglePlaces
import CoreLocation
class SceneDelegate: UIResponder, UIWindowSceneDelegate, CLLocationManagerDelegate {
var window: UIWindow?
private let locationManager = CLLocationManager()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Use a UIHostingController as window root view controller
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: LandmarkList())
self.window = window
window.makeKeyAndVisible()
}
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
}
}
}
LandmarkList.swift:
import SwiftUI
struct LandmarkList: View {
#State private var searchText = ""
#State private var locationText = ""
var body: some View {
ZStack(alignment: Alignment.top) {
GoogMapView()
.frame(height: 750)
SlideOverCard {
VStack(alignment: .leading) {
List(landmarkData) { landmark in
NavigationLink(destination: LandmarkDetail(landmark: landmark)) {
LandmarkRow(landmark: landmark)
}
}
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: Alignment.topLeading)
}
}
}
}
GoogMapView.swift:
Note: The print statement below only returns 'User's location is unknown'
import SwiftUI
import UIKit
import GoogleMaps
import GooglePlaces
import CoreLocation
struct GoogMapView : UIViewRepresentable {
let marker : GMSMarker = GMSMarker()
//Creates a `UIView` instance to be presented.
func makeUIView(context: Context) -> GMSMapView {
// Create a GMSCameraPosition
let camera = GMSCameraPosition.camera(withLatitude: 42.361145, longitude: -71.057083, zoom: 16.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
mapView.setMinZoom(14, maxZoom: 20)
mapView.settings.compassButton = true
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
mapView.settings.scrollGestures = true
mapView.settings.zoomGestures = true
mapView.settings.rotateGestures = true
mapView.settings.tiltGestures = true
mapView.isIndoorEnabled = false
if let mylocation = mapView.myLocation {
print("User's location: \(mylocation)")
} else {
print("User's location is unknown")
}
return mapView
}
// Updates the presented `UIView` (and coordinator) to the latestconfiguration.
func updateUIView(_ mapView: GMSMapView, context: Context) {
// Creates a marker in the center of the map.
marker.position = CLLocationCoordinate2D(latitude: 42.361145, longitude: -71.057083)
marker.title = "Boston"
marker.snippet = "USA"
marker.map = mapView
}
}
Again, I think my code regarding locationManager in SceneDelegate.swift would make the instance of GoogleMaps camera focus on the users location at startup, but it doesnt.
Anyone know what im doing wrong?
I was finally able to figure out how to focus on "my location" immediately, instead of requiring input from the user. Here are some more details...hope it helps!
updateUIView
You want updateUIView to be called when the user's location is retrieved. From what I have read updateUIView is called when a #State or #Binding object changes (or #ObservedObject). So, the UIViewRepresentable needs to have one of these. In the case of my code below, I use an #ObservedObject. Whenever one of the #ObservedObject's #Published properties changes, updateUIView will be called.
Creating The Observed Object
I created a class (LocationManager) that conforms to the ObservableObject protocol.
Within the class, I exposed the lastKnownLocation as a #Published property. As mentioned above, when the lastKnownLocation is updated, any subscribers to an instance of the LocationManager class will see those updates
Getting The User's Coordinates
CLLocationManager is used to get updates on the user's location.
The LocationManager class I created implements the delegate functions for CLLocationManager
The delegate function didUpdateLocations is called when the user's location is updated. Within that function, I then update the #Published property so that the UIViewRepresentable sees those changes, and updateUIView is automatically called accordingly.
The UIViewRepresentable
import SwiftUI
import GoogleMaps
import Combine
struct HomeView: UIViewRepresentable {
// Listen to changes on the locationManager
#ObservedObject var locationManager = LocationManager()
func makeUIView(context: Self.Context) -> GMSMapView {
// Just default the camera to anywhere (this will be overwritten as soon as myLocation is grabbed
let camera = GMSCameraPosition.camera(withLatitude: 0, longitude: 0, zoom: 16.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
mapView.setMinZoom(14, maxZoom: 20)
mapView.settings.compassButton = true
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
mapView.settings.scrollGestures = true
mapView.settings.zoomGestures = true
mapView.settings.rotateGestures = true
mapView.settings.tiltGestures = true
mapView.isIndoorEnabled = false
return mapView
}
func updateUIView(_ mapView: GMSMapView, context: Self.Context) {
// When the locationManager publishes updates, respond to them
if let myLocation = locationManager.lastKnownLocation {
mapView.animate(toLocation: myLocation.coordinate)
print("User's location: \(myLocation)")
}
}
}
The LocationManager class:
class LocationManager: NSObject, CLLocationManagerDelegate, ObservableObject {
// Publish the user's location so subscribers can react to updates
#Published var lastKnownLocation: CLLocation? = nil
private let manager = CLLocationManager()
override init() {
super.init()
self.manager.delegate = self
self.manager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
self.manager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Notify listeners that the user has a new location
self.lastKnownLocation = locations.last
}
}
Using comments here and others on StackOverflow, I made this solution:
//
// GoogMapView.swift
// Landmarks
//
// Created by Zahr Lyttle on 10/14/19.
// Copyright © 2019 Apple. All rights reserved.
//
import SwiftUI
import UIKit
import GoogleMaps
import GooglePlaces
import CoreLocation
import Foundation
struct GoogMapView: View {
var body: some View {
GoogMapControllerRepresentable()
}
}
class GoogMapController: UIViewController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
var mapView: GMSMapView!
let defaultLocation = CLLocation(latitude: 42.361145, longitude: -71.057083)
var zoomLevel: Float = 15.0
let marker : GMSMarker = GMSMarker()
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.distanceFilter = 50
locationManager.startUpdatingLocation()
locationManager.delegate = self
let camera = GMSCameraPosition.camera(withLatitude: defaultLocation.coordinate.latitude, longitude: defaultLocation.coordinate.longitude, zoom: zoomLevel)
mapView = GMSMapView.map(withFrame: view.bounds, camera: camera)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.isMyLocationEnabled = true
mapView.setMinZoom(14, maxZoom: 20)
mapView.settings.compassButton = true
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
mapView.settings.scrollGestures = true
mapView.settings.zoomGestures = true
mapView.settings.rotateGestures = true
mapView.settings.tiltGestures = true
mapView.isIndoorEnabled = false
// if let mylocation = mapView.myLocation {
// print("User's location: \(mylocation)")
// } else {
// print("User's location is unknown")
// }
marker.position = CLLocationCoordinate2D(latitude: 42.361145, longitude: -71.057083)
marker.title = "Boston"
marker.snippet = "USA"
marker.map = mapView
// Add the map to the view, hide it until we've got a location update.
view.addSubview(mapView)
// mapView.isHidden = true
}
// Handle incoming location events.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location: CLLocation = locations.last!
print("Location: \(location)")
let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude, longitude: location.coordinate.longitude, zoom: zoomLevel)
if mapView.isHidden {
mapView.isHidden = false
mapView.camera = camera
} else {
mapView.animate(to: camera)
}
}
// Handle authorization for the location manager.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .restricted:
print("Location access was restricted.")
case .denied:
print("User denied access to location.")
// Display the map using the default location.
mapView.isHidden = false
case .notDetermined:
print("Location status not determined.")
case .authorizedAlways: fallthrough
case .authorizedWhenInUse:
print("Location status is OK.")
}
}
// Handle location manager errors.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
locationManager.stopUpdatingLocation()
print("Error: \(error)")
}
}
struct GoogMapControllerRepresentable: UIViewControllerRepresentable {
func makeUIViewController(context: UIViewControllerRepresentableContext<GMControllerRepresentable>) -> GMController {
return GMController()
}
func updateUIViewController(_ uiViewController: GMController, context: UIViewControllerRepresentableContext<GMControllerRepresentable>) {
}
}
You can implement this by "pretending" your View is a ViewController. Try setting GoogleMapView as the delegate, instead. Then put your initialization code in makeUIView and then conform to the protocol:
struct GoogMapView : CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
guard status == .authorizedWhenInUse else {
return
}
locationManager.startUpdatingLocation()
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else {
return
}
mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
locationManager.stopUpdatingLocation()
}
}
Above taken from https://www.raywenderlich.com/197-google-maps-ios-sdk-tutorial-getting-started.

Location manager show bad location in gmsMapView swift 4.2

I have a problem that a I cannot resolve. I'm trying to get the current location to update the mapview and center the camera, but when I close the view controller and init a new Mapviewcontroller the "current location" show a location incorrect, near to my position but not the current location. Can anyone guide me o help me? this is my code:
class MapContainerViewController: UIViewController{
#IBOutlet weak var mapView: GMSMapView!
var locationManager = CLLocationManager()
var myLocation: CLLocation?
var autorizeChange: Bool?
var geofire: GeoFire?
var createGeoforme: Bool?
var INITIAL_CENTER: CLLocation?
var searchCircle: GMSCircle?
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
autorizeChange = true
checkLocationServices()
createGeoforme = false
mapView.delegate = self
// Do any additional setup after loading the view.
}
func setupLocationManager(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 100
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.startMonitoringSignificantLocationChanges()
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func checkLocationServices(){
if CLLocationManager.locationServicesEnabled(){
setupLocationManager()
checkLocationAutorization()
} else {
}
}
func checkLocationAutorization(){
switch CLLocationManager.authorizationStatus() {
case .authorizedWhenInUse:
//Do map stuff
if (mapView.isMyLocationEnabled == false ){
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
var ref: DatabaseReference
ref = Database.database().reference()
geofire = GeoFire(firebaseRef: ref)
}
break
case .denied:
//Show alert instructing
break
case .notDetermined:
//location manager
locationManager.requestWhenInUseAuthorization()
break
case .restricted:
//Show alert letting them know
break
case .authorizedAlways:
break
default:
}
}
}
}
extension MapContainerViewController: GMSMapViewDelegate{
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition)
{
mapView.clear()
let coordinate = mapView.projection.coordinate(for: mapView.center)
var cooordinate2d = CLLocationCoordinate2D.init(latitude: coordinate.latitude, longitude: coordinate.longitude)
var circ = GMSCircle.init(position: coordinate, radius: zoomLevelToRadius(zoomLevel: Double(position.zoom)))
circ.fillColor = UIColor.init(displayP3Red: 0, green: 255, blue: 255, alpha: 0.15)
circ.strokeColor = UIColor.init(displayP3Red: 0, green: 0, blue: 0, alpha: 0.15)
circ.strokeWidth = 0.5
circ.map = mapView;
}
func zoomLevelToRadius(zoomLevel: Double) -> Double{
// Approximation to fit circle into view
return (16384000/pow(2, zoomLevel))
}
}
extension MapContainerViewController: CLLocationManagerDelegate{
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation: CLLocation = locations[0]
let location = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
mapView.camera = GMSCameraPosition.camera(withTarget: location, zoom: 14)
let centerLocation = mapView.projection.coordinate(for: mapView.center)
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
checkLocationAutorization()
}
}
This sample code can be your solution you can find here https://github.com/SwiftGuides/Google_Place_Picker
This is sample code i wrote for Google place picker to pick exact pin point custom location (not nearby location)
In your case you can apply this too. Just check the example code you will get you solution

Why the MKPolyline didn't show up in my application?

I am trying to create an application, one of its function is to drawing the line while users are moving.
Here is the class
class traceuserViewController: UIViewController,CLLocationManagerDelegate, MKMapViewDelegate {
var locationManager = CLLocationManager()
var startLocation: CLLocation?
var endLocation: CLLocation?
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
self.locationManager.distanceFilter = 30.0
self.locationManager.startMonitoringSignificantLocationChanges()
self.locationManager.startUpdatingLocation()
mapView.showsUserLocation = true
mapView.mapType = .hybrid
self.mapView.delegate = self
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//user's current location
let nowlocation = locations.last
userLocations.append(nowlocation!)
print("HERE IS THE LOCATION ARRAY")
print(userLocations)
//show the current location region
let center = CLLocationCoordinate2D(latitude: nowlocation!.coordinate.latitude, longitude: nowlocation!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.7, longitudeDelta: 0.7))
self.mapView.setRegion(region, animated: true)
drawRoute(locationArray: userLocations)
}
func drawRoute(locationArray: [CLLocation]) {
if (locationArray.count) > 1 {
var destinationLocIndex = (locationArray.count) - 1
var startLocIndex = (locationArray.count) - 2
let destinationloc = locationArray[destinationLocIndex].coordinate
let startLoc = locationArray[startLocIndex].coordinate
var routeArray = [startLoc, destinationloc]
//test if the function works well or not
print(routeArray)
var geodesicLine = MKGeodesicPolyline(coordinates: routeArray , count: routeArray.count)
mapView.add(geodesicLine, level: .aboveRoads)
}
}
//draw in the mapview
private func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer! {
if overlay is MKPolyline{
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blue
polylineRenderer.lineWidth = 5.0
return polylineRenderer
}else{
os_log("Failed to draw the polyline", log: OSLog.default, type: .debug)
return nil
}
}
After many times trying, I still have no idea why it doesn't draw the route on the map when the user is moving, can anyone please I've me some hints?
cheers
I'm inferring that you are using Swift 3 from the code snippet (e.g. the signature of didUpdateLocations; the use of .hybrid rather than Swift 2.3's .Hybrid; etc.).
But, the signature for mapView(_:rendererFor:) is incorrect. In Swift 3, it is:
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
...
}
If you ever have a delegate method that doesn't appear to work, add a breakpoint in it and you can confirm if it's called at all or not (and if it is called, you can step through it and diagnose the problem further).

Im trying to show my current location on a map but when I run my code in the simulator it doesn't work

// Here is some more info on the problem = Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet var myMap : MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
myMap.showsUserLocation = true }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Errors: " + error.localizedDescription)
}
#IBAction func satelliteView(){
myMap.mapType = MKMapType.Satellite
}
#IBAction func normalView(){
myMap.mapType = MKMapType.Standard
}
#IBAction func pin(sender: UILongPressGestureRecognizer) {
let location = sender.locationInView(self.myMap)
let lCoord = self.myMap.convertPoint(location, toCoordinateFromView: self.myMap)
let anno = MKPointAnnotation()
anno.coordinate = lCoord
anno.title = "store"
anno.subtitle = "loctaion of Store"
self.myMap.removeAnnotations(myMap.annotations)
self.myMap.addAnnotation(anno)
}
}
The simulator does not know your present location. Your need to let the simulator know your location.
In the simulator menu select Debug > Location > Custom Location
You can enter the Lat and Long of your physical location or any other location.
The following is from an app I wrote. You need to call something similar when locationManager(manager:didUpdateLocations: is called
func addPinAtCoordinate(latlong: Vector2D, plotting: Bool = defaultPlotState) {
if self.plotting && !plotting {
self.removeAnnotations(annotationStack)
annotationStack = []
self.plotting = plotting
}
let lat = latlong.x
let lon = latlong.y > 180.0 ? latlong.y - 360.0 : latlong.y
let coord = CLLocationCoordinate2DMake(lat, lon)
let region = self.regionThatFits(MKCoordinateRegionMake(coord, MKCoordinateSpan(latitudeDelta: mapSpanDegrees, longitudeDelta: mapSpanDegrees)))
if region.center.latitude != -180.0 || region.center.longitude != -180.0 {
self.setRegion(region, animated: true)
let note = MKPointAnnotation()
let annotPoint = CLLocationCoordinate2D(latitude: lat, longitude: lon)
note.coordinate = annotPoint
self.addAnnotation(note)
self.annotationStack.append(note)
if annotationStack.count > annotationStackLength {
self.removeAnnotation(annotationStack[0])
annotationStack.removeAtIndex(0)
}
}
else {
NSLog("Can't place invalid cordinate: ", latlong)
}
}
Most specifically useful relative to your problem are the lines creating a region and calling setRegion.