Custom map in Swift - ios

I am currently developing an iOS application using location.
But I want to have a customized map to show user's location, not the default map given by MapKit.
A map like this for example :
Is it possible to achieve something like this in Swift 4.0 ?
Thanks a lot

You need to use MKTileOverlay - documentation is here...
As it says:
You use tile overlay objects to represent your own tile-based content
and to coordinate the display of that content in a map view. Your
tiles can supplement the underlying map content or replace it
completely.
(my emphasis)

This is how you can make a map show your live current location.
Full code:
import UIKit
import MapKit
//import CoreLocation
class ViewController: UIViewController, UIScrollViewDelegate ,CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet var map: MKMapView!
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation: CLLocation = locations[0]
let latitude = userLocation.coordinate.latitude
let longitude = userLocation.coordinate.longitude
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta)
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let region = MKCoordinateRegion(center: location, span: span)
self.map.setRegion(region, animated: false)
let annotation = MKPointAnnotation()
annotation.coordinate = location
annotation.title = "My current Location"
map.addAnnotation(annotation)
}
}
Note that you also have to add the permissions to the info.plist file
the permissions are:
Privacy - Location When In Use Usage Description
Privacy - Location Always Usage Description

Here is how you can give fixed location and a pin in a map view
import UIKit
import MapKit
class ViewController: UIViewController {
#IBOutlet weak var myMap: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let latitude : CLLocationDegrees = 86.44999
let longitude : CLLocationDegrees = 54.39
let latitudeDelta : CLLocationAccuracy = 0.05
let longituteDelta : CLLocationAccuracy = 0.05
let myLocation = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let mySpan = MKCoordinateSpanMake(latitudeDelta, longituteDelta)
let myRegion = MKCoordinateRegion(center: myLocation, span: mySpan)
myMap.setRegion(myRegion, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = myLocation
myMap.addAnnotation(annotation)
}
}

Related

MapView that is zoomed in on the users current location in Xcode iOS Development

I've tried the following solutions:
Zoom in on User Location- Swift
Get User's Current Location / Coordinates
Determine User’s Current Location Example in Swift
But all I get is a map zoomed in on some other location, like San Francisco or somewhere in the middle east.
The top answer for solution3 looks like it shows how to print the users current location but it doesn't show how to use it with a map.
My ViewController.swift file
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last! as CLLocation
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
}
}

Swift mapkit not pointing at location

I have an ios application built to use mapkit and corelocation. the application works with no error but the map doesnt pin point my current location in xcode simulator and when run on an actual device it does not show the land scape and other things. just a blank map with a single road and it cannot be zoomed in or out.
below is my code
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//IF we have coordinate from manager
//let location = locations.last as CLLocation
if let location = locationManager.location?.coordinate{
userLocation = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
let region = MKCoordinateRegion(center: userLocation!, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
mapView.setRegion(region, animated: true)
mapView.removeAnnotations(mapView.annotations)
let annotation = MKPointAnnotation()
annotation.coordinate = userLocation!
annotation.title = "Me!"
mapView.addAnnotation(annotation)
}
}
additional codes would be supplied on request
Here, this Class that I use to show a Pin to location -
import UIKit
import MapKit
class ContactViewController: UIViewController,MKMapViewDelegate,CLLocationManagerDelegate {
#IBOutlet var viewBG1: UIView!
#IBOutlet var mapview: MKMapView!
override func showPinLocation() {
let annotation = MKPointAnnotation()
annotation.title = "Title"
var coordinate = CLLocationCoordinate2D()
coordinate.latitude = 28.702466
coordinate.longitude = 77.1016314
annotation.coordinate = coordinate
var region = MKCoordinateRegion()
var span = MKCoordinateSpan()
span.latitudeDelta = 0.002; // 0.0 is min value u van provide for zooming
span.longitudeDelta = 0.002
region.span=span;
region.center = coordinate; // to locate to the center
self.mapview.addAnnotation(annotation)
self.mapview.setRegion(region, animated: true)
self.mapview.regionThatFits(region)
// Do any additional setup after loading the view.
}
The simulator is doing what it is supposed to. You can change the location from the debug menu:
If you're using a storyboard, go to your map view and look for these things to edit your view:
And
You can set the map to hybrid and get streets and satellite, you can also make your mapView scalable and many other things.
If you want to set the type of view programmatically, you can implement a segmented control and do this:
#IBAction func segmentedControlAction(sender: UISegmentedControl!) {
switch (sender.selectedSegmentIndex) {
case 0:
mapView.mapType = .Standard
case 1:
mapView.mapType = .Satellite
default:
mapView.mapType = .Hybrid
}
}
And to programmatically set the UI :
self.mapView.zoomEnabled = true;
self.mapView.scrollEnabled = true;
self.mapView.userInteractionEnabled = true;

Put latitude and longitude on a UILabel programmatically

I can't seem to get the latitude and longitude to show up on the labels. I've tried many things though I'm guessing it might be something simple.
import Foundation
import UIKit
import CoreLocation
import MapKit
class LocationVC: UIViewController, CLLocationManagerDelegate {
var location: CLLocation! {
didSet{
longLabel.text = ("\(location.coordinate.latitude)")
latLabel.text = ("\(location.coordinate.longitude)")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations[0]
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.5, 0.5)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
map.setRegion(region, animated: true)
print("hhhhh\(location.coordinate.latitude)")
print(location.altitude)
print(location.speed)
self.map.showsUserLocation = true
}
All the views are set up correctly.
You did not change the value of the location variable of your class, which would trigger the text change of the label. Append this to didUpdateLocations:
self.location = location
Use this
longLabel.text = location.coordinate.latitude.description
latLabel.text = location.coordinate.longitude.description

Adding Pins to Map using MapKit - Swift 3.0

New coder, trying to figure out how to use MapKit. The goal is to create a map that users can add pins to using their address. However, the step I am at now, I am having trouble figuring out how to add pins to the map at all.
How can I add a pin to the map? I have been struggling to figure out how to use annotations thus far.
That's what I'm hoping for help/direction with. Thanks!
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate
{
#IBOutlet weak var bigMap: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.bigMap.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.02, longitudeDelta: 0.02))
self.bigMap.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Errors " + error.localizedDescription)
}
}
They're called annotations in the MapKit and you should instantiate them like so:
let annotation = MKPointAnnotation()
then in the viewDidLoad() method just set the coordinates and add them to the map like:
annotation.coordinate = CLLocationCoordinate2D(latitude: 11.12, longitude: 12.11)
mapView.addAnnotation(annotation)
The numbers are your coordinates
The way that I learned how to do this is:
In the same function as viewDidLoad(), place the following lines of code:
let annotation = MKPointAnnotation()
annotation.title = "Your text here"
//You can also add a subtitle that displays under the annotation such as
annotation.subtitle = "One day I'll go here..."
annotation.coordinate = center
This is the only place I can see where you have a coordinate
if all else fails, just add the coordinate (search on Google if you
need to know how to create a coordinate) and set it equal to the
"annotation.coordinate" variable
map.addAnnotation(annotation)
Dassit!

Map keeps coming back to the base location

I am trying to add annotations to multiple locations on the Map. I am using Simulator with iPhone 6 selected as the Device. However when I drag the map to other locations in order to add annotations, it keeps coming back to the base location.i.e the original location the simulator displayed at the launch ( note: I have imported CoreLocation, add added NSLocationAlways and WheninUse to the info.plist).
How do I let it stay at the location I drag the map to ?
Here is the code...
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet var theMap: MKMapView!
var locManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locManager.requestWhenInUseAuthorization()
locManager.desiredAccuracy = kCLLocationAccuracyBest
locManager.delegate = self
locManager.startUpdatingLocation()
let longPress = UILongPressGestureRecognizer(target: self, action: "longPressed:")
longPress.minimumPressDuration = 2
self.view.addGestureRecognizer(longPress)
}
func longPressed(theGesture: UIGestureRecognizer) {
if theGesture.state == UIGestureRecognizerState.Began {
print("recognised")
let touchPoint = theGesture.locationInView(self.theMap)
let convertedTouchPoint = theMap.convertPoint(touchPoint, toCoordinateFromView: self.theMap)
let annotation = MKPointAnnotation()
annotation.title = "Place 1"
annotation.subtitle = "Description Place 1"
annotation.coordinate = convertedTouchPoint
theMap.addAnnotation(annotation)
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation = locations[0]
let latitude: CLLocationDegrees = userLocation.coordinate.latitude
let longitude: CLLocationDegrees = userLocation.coordinate.longitude
let latDelta:CLLocationDegrees = 0.01
let longDelta:CLLocationDegrees = 0.01
let center = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: longDelta)
let region = MKCoordinateRegion(center: center, span: span)
theMap.setRegion(region, animated: true)
}
}
Just figured out that, with the Simulator selected , navigate to Debug--> Location and Select 'None'. This fixed the issue. I can now drag to different locations without getting back to the base location.

Resources