How to show my location and pin in map correctly on Swift?

13,244

Solution 1

To display location on map using latitude and longitude.

 var latDelta:CLLocationDegrees = 0.01

 var longDelta:CLLocationDegrees = 0.01

 var theSpan:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
 var pointLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(your latitude, your longitude)

 var region:MKCoordinateRegion = MKCoordinateRegionMake(pointLocation, theSpan)
  mapView.setRegion(region, animated: true)

  var pinLocation : CLLocationCoordinate2D = CLLocationCoordinate2DMake(your latitude, your longitude)
  var objectAnnotation = MKPointAnnotation()
  objectAnnotation.coordinate = pinLocation
  objectAnnotation.title = your title
  self.mapView.addAnnotation(objectAnnotation)

Solution 2

You can do like this:

import UIKit

import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

let locationManager = CLLocationManager()  // Here it is an object to get the user's location.



@IBOutlet weak var mapView: MKMapView!    // It is my map.


override func viewDidLoad() {
    super.viewDidLoad()

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.requestLocation()
    // To initialize locationManager (). Now it can give you the user's location.        


    map.delegate = self
    map.showsUserLocation = true
    // To initialize the map.

}// Here you should initialize locationManager and your map. I send you the code later.

func dropPinZoomIn(placemark: MKPlacemark){   // This function will "poste" the dialogue bubble of the pin.
    var selectedPin: MKPlacemark?

    // cache the pin
    selectedPin = placemark    // MKPlacemark() give the details like location to the dialogue bubble. Place mark is initialize in the function getLocationAddress (location: ) who call this function.

    // clear existing pins to work with only one dialogue bubble.
    mapView.removeAnnotations(mapView.annotations)
    let annotation = MKPointAnnotation()    // The dialogue bubble object.
    annotation.coordinate = placemark.coordinate   
    annotation.title = placemark.name// Here you should test to understand where the location appear in the dialogue bubble.

    if let city = placemark.locality,
        let state = placemark.administrativeArea {
        annotation.subtitle = String((city))+String((state));
    } // To "post" the user's location in the bubble.

    mapView.addAnnotation(annotation)     // To initialize the bubble.
    let span = MKCoordinateSpanMake(0.05, 0.05)
    let region = MKCoordinateRegionMake(placemark.coordinate, span)
    mapView.setRegion(region, animated: true)   // To update the map with a center and a size.
}

func getLocationAddress(location:CLLocation) {    // This function give you the user's address from a location like locationManager.coordinate (it is usually the user's location).
    let geocoder = CLGeocoder()

    print("-> Finding user address...")

    geocoder.reverseGeocodeLocation(location, completionHandler: {(placemarks, error)->Void in
        var placemark:CLPlacemark!

        if error == nil && placemarks!.count > 0 {
            placemark = placemarks![0] as CLPlacemark


            var addressString : String = ""
            if placemark.ISOcountryCode == "TW" /*Address Format in Chinese*/ {
                if placemark.country != nil {  // To have the country
                    addressString = placemark.country!
                }
                if placemark.subAdministrativeArea != nil {  // To have the subAdministrativeArea.
                    addressString = addressString + placemark.subAdministrativeArea! + ", "
                }
                if placemark.postalCode != nil {   // To ...
                    addressString = addressString + placemark.postalCode! + " "
                }
                if placemark.locality != nil {
                    addressString = addressString + placemark.locality!
                }
                if placemark.thoroughfare != nil {
                    addressString = addressString + placemark.thoroughfare!
                }
                if placemark.subThoroughfare != nil {
                    addressString = addressString + placemark.subThoroughfare!
                }
            } else {
                if placemark.subThoroughfare != nil {
                    addressString = placemark.subThoroughfare! + " "
                }
                if placemark.thoroughfare != nil {
                    addressString = addressString + placemark.thoroughfare! + ", "
                }
                if placemark.postalCode != nil {
                    addressString = addressString + placemark.postalCode! + " "
                }
                if placemark.locality != nil {
                    addressString = addressString + placemark.locality! + ", "
                }
                if placemark.administrativeArea != nil {
                    addressString = addressString + placemark.administrativeArea! + " "
                }
                if placemark.country != nil {
                    addressString = addressString + placemark.country!
                }

                let new_placemark: MKPlacemark = MKPlacemark (placemark: placemark)

                // new_placemark initialize a variable of type MKPlacemark () from geocoder to use the function dropPinZoomIn (placemark:).


                self.dropPinZoomIn (new_placemark)

                print (placemark.description)   // You can see the place mark's details like the country.

            }


        }
    })

}

I give you an easily location systeme where you can have the user's address, the user's location and show it in a map with dialogues bubbles who displays the user's location. You can have more documentation in Thorn web site with dialogue or in apple developer web site.

Share:
13,244
user3745888
Author by

user3745888

Updated on June 07, 2022

Comments

  • user3745888
    user3745888 almost 2 years

    I'm trying sshow my location in app Swift but this not show anything, the map is all blue..

    My code is this form a tutorial on internet:

     var latitude:CLLocationDegrees = location.location.coordinate.latitude
        var longitude:CLLocationDegrees = location.location.coordinate.longitude
        var homeLati: CLLocationDegrees = 40.01540192
        var homeLong: CLLocationDegrees = 20.87901079
        var latDelta:CLLocationDegrees = 0.01
        var longDelta:CLLocationDegrees = 0.01
        var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
    
        var myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
        var region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
        self.mapKit.setRegion(region, animated: true)
    
        self.mapKit.showsUserLocation = true
        ///Red Pin
        var myHomePin = MKPointAnnotation()
        myHomePin.coordinate = myHome
        myHomePin.title = "Home"
        myHomePin.subtitle = "Bogdan's home"
        self.mapKit.addAnnotation(myHomePin)
    

    I have imported corresponding configuration in .split.. What is bad on this code?

    Thanks!

    • Anthony Kong
      Anthony Kong almost 10 years
    • user3745888
      user3745888 almost 10 years
      I'm using the code in that question.The problem in that post was adding pin annotation, my problem is showing location in map, I can't show anything in the map. the map is clear
    • user3745888
      user3745888 almost 10 years
      I was forgetting the NSLocationAlwaysUsageDescription in plist, for this reason I can't show never in mapView.. Thanks!! this was said in the other, you were right!
  • Werner Henze
    Werner Henze over 7 years
    Can you please add an Explanation of what you did and why!?