I want to show live tracking in Map View.I am having latitudes and Longitudes List in separate Array… How to Show this in Map as a point.. Please anybody HelpOut For this Problem.
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
{
let location = locations.last as! CLLocation
let location1 = locations.first as! CLLocation
// Have to get OldLocation And New Location From API
let oldCoordinates = location.coordinate
let newCoordinates = location1.coordinate
var area = [oldCoordinates, newCoordinates]
let polyline = MKPolyline(coordinates: &area, count: area.count)
mapView.add(polyline)
self.currentCLLocation = CLLocationCoordinate2D(latitude: newCoordinates.latitude, longitude: newCoordinates.longitude)
let region = MKCoordinateRegion(center: self.currentCLLocation, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
print("Location Update Details")
print(location.coordinate.latitude)
print(location.coordinate.longitude)
self.mapView.delegate = self
let annotation = MKPointAnnotation()
annotation.coordinate = location1.coordinate
self.mapView.addAnnotation(annotation)
}
Values In Array:
Latitudes Array==>>
["12.988415", "12.988445", "12.988492", "12.988558", "12.988673", "12.988788", "12.988903", "12.989039"]
Longitudes Array==>>
["80.218386", "80.21839199999999", "80.218422", "80.218461", "80.218515", "80.218547", "80.21860100000001"]
How to Loop the latitude and Longitude Values in Location and Location1 Variable?
DidUpdate Method is not getting called Every time we update map?
How To show Polyline based on Lat and Long?
Related
I have 2 locations in the map. First one is users current location with blue dot placemark and the second one is specified restaurant location near of the users current location with red dot placemark. I want to get directions from user's current location to restaurant location. I am getting directions when I define latitude and longitude values like latitude: 38.00001 and longitude: 27.08980.
Also I am getting each restaurants location from api to red dot placemark but do not get directions from user current location to restaurant location.
I am getting restaurant location with these codes:
var viewModel: DetailsViewModel? {
didSet {
updateView()
}
willSet {
updateView()
}
}
func updateView() {
if let viewModel = viewModel {
detailsFoodView?.priceLabel?.text = viewModel.price
detailsFoodView?.hoursLabel?.text = viewModel.isOpen
detailsFoodView?.locationLabel?.text = viewModel.phoneNumber
detailsFoodView?.ratingsLabel?.text = viewModel.rating
detailsFoodView?.collectionView?.reloadData()
centerMap(for: viewModel.coordinate)
print("detail restaurant destination : \(viewModel.coordinate)")
title = viewModel.name
print("title: \(title)")
}
}
func centerMap(for coordinate: CLLocationCoordinate2D) {
let region = MKCoordinateRegion(center: coordinate, latitudinalMeters: 100, longitudinalMeters: 100)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
detailsFoodView?.mapView?.addAnnotation(annotation)
detailsFoodView?.mapView?.setRegion(region, animated: true)
}
}
And in viewDidLoad() getting directions like:
let sourceCoordinates = locationManager.location?.coordinate
Problem is here
I do not get each restaurant's latitude and longitude values to destCoordinates. Normally, I get with viewModel.coordinate.
But if I use
let destCoordinates = CLLocationCoordinate2D(latitude: viewModel?.coordinate.latitude, longitude: viewModel?.coordinate.longitude)
Instead of:
let destCoordinates = CLLocationCoordinate2D(latitude: 38.420183, longitude: 27.205559)
I am getting latitude and longitude values nil or zero.
let sourcePlaceMark = MKPlacemark(coordinate: sourceCoordinates!)
let destPlaceMark = MKPlacemark(coordinate: destCoordinates)
let sourceItem = MKMapItem(placemark: sourcePlaceMark)
let destItem = MKMapItem(placemark: destPlaceMark)
let directionRequest = MKDirections.Request()
directionRequest.source = sourceItem
directionRequest.destination = destItem
directionRequest.transportType = .automobile
let directions = MKDirections(request: directionRequest)
directions.calculate(completionHandler: {response, error in
guard let response = response else {
if error != nil {
print("Something went wrong!")
}
return
}
let route = response.routes[0]
self.detailsFoodView?.mapView?.addOverlay(route.polyline, level: .aboveRoads)
let rect = route.polyline.boundingMapRect
self.detailsFoodView?.mapView?.setRegion(MKCoordinateRegion(rect), animated: true)
Expected result is current user place as blue dot placemark to red dot placemark with red line as you can see in the screen shot.
Image:
Currently I'm setting up location services but for some strange reason the tracker icon isn't appearing:
I know it's working because if I add a pin the pin shows up correctly:
I'm not sure why the tracker isn't showing up, here is the code:
#IBOutlet weak var map: MKMapView!
let locationsManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationsManager.delegate = self
locationsManager.desiredAccuracy = kCLLocationAccuracyBest // sets to best location accuracy
locationsManager.requestWhenInUseAuthorization()// requests user location when app is opened
locationsManager.startUpdatingLocation()// updates user location
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation: CLLocation = locations[0]
let latitude: CLLocationDegrees = userLocation.coordinate.latitude
let longitude: CLLocationDegrees = userLocation.coordinate.longitude
let latDelta: CLLocationDegrees = 0.05
let longDelta: CLLocationDegrees = 0.05
let span: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude,longitude)
let region: MKCoordinateRegion = MKCoordinateRegionMake(location, span)
map.setRegion(region, animated: true)
let pin = MKPointAnnotation()
pin.coordinate.latitude = userLocation.coordinate.latitude
pin.coordinate.longitude = userLocation.coordinate.longitude
pin.title = "My current location"
map.addAnnotation(pin)
}
You need to set the property showsUsersLocation to true. https://developer.apple.com/reference/mapkit/mkmapview/1452682-showsuserlocation
MKMapView can display the user location and track user location for you:
map.showsUserLocation = true
map.userTrackingMode = .follow
There is no need to implement your own location tracking delegate method.
Nevermind, figured it out. In viewDidload():
map.showsUserLocation = true
I want to calculate the distance from my location to another.
I found this line of code:
let distanceInMeters = location1.distanceFromLocation(location2)
But my problem is that I don't know how to take it from latitude and longitude.
So, you just need to create 2 CLLocation objects from your lat and long and then just call the line of code that you found.
let location1 = CLLocation(latitude: 20.0, longitude: 20.0)
let location2 = CLLocation(latitude: 30.0, longitude: 30.0)
let distanceInMeters = location1.distanceFromLocation(location2)
Also, this will return you distance in meters, not in km.
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var userLocation:CLLocation = locations[0] as! CLLocation
let long = userLocation.coordinate.longitude;
let lat = userLocation.coordinate.latitude;
// use it for your code
}
You can try this function, I use it in my code
I am new to Swift and I need to calculate the nearest places around my current location. Would you advice me which function should I use to calculate the distance between my location and the nearest around me. I have to display the distance and the places in the app,so that the user can choose which one fits best for him.I think I should use latitude and longitude coordinates which can be compared with mine. I also found out that I have to use distanceFromLocation , but I do not know how and I would be glad if someone provide me with an example which I can use for my code.
My code so far is:
class ViewThree: UIViewController, CLLocationManagerDelegate{
#IBOutlet weak var SegmentControl: UISegmentedControl!
#IBOutlet weak var Mapview: MKMapView!
var manager = CLLocationManager()
var receiveImeNaSladkarnica: String = ""
var KordaA: String = ""
var KordaB: String = ""
var PodImeNaObekt: String = ""
override func viewDidLoad() {
super.viewDidLoad()
let pinLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake((KordaA as NSString).doubleValue,(KordaB as NSString).doubleValue)
let objectAnn = MKPointAnnotation()
objectAnn.coordinate = pinLocation
objectAnn.title = receiveImeNaSladkarnica
objectAnn.subtitle = PodImeNaObekt
self.Mapview.addAnnotation(objectAnn)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func Directions(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://maps.apple.com/maps?daddr=\((KordaA as NSString).doubleValue),\((KordaB as NSString).doubleValue))")!)
}
#IBAction func MapType(sender: AnyObject) {
if (SegmentControl.selectedSegmentIndex == 0){
Mapview.mapType = MKMapType.Standard
}
if (SegmentControl.selectedSegmentIndex == 1){
Mapview.mapType = MKMapType.Satellite
}
}
#IBAction func LocateMe(sender: AnyObject) {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
Mapview.showsUserLocation = true
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userlocation: CLLocation = locations[0] as CLLocation
manager.stopUpdatingLocation()
let location = CLLocationCoordinate2D(latitude: userlocation.coordinate.latitude, longitude: userlocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.5, 0.5)
let region = MKCoordinateRegion(center: location, span: span)
Mapview.setRegion(region, animated: true )
}
I had the same scenario with an other app.
Within the CLLocation object, there is an instance function:
func distanceFromLocation(location: CLLocation) -> CLLocationDistance
//Get your two locations that you want to calculate the distance from:
let userLocation: CLLocation = ...
let locationToCompare: CLLocation = ...
// Returned value is in meters
let distanceMeters = userLocation.distanceFromLocation(locationToCompare)
// If you want to round it to kilometers
let distanceKilometers = distanceMeters / 1000.00
// Display it in kilometers
let roundedDistanceKilometers = String(Double(round(100 * distanceKilometers) / 100)) + " km"
UPDATED
For your use case
let locations = ... // All locations you want to compare
for location in locations {
let distanceMeters = userLocation.distanceFromLocation(location)
if distanceMeters > 5000 { // Some distance filter
// Don't display this location
} else {
// Display this location
}
}
MY CODE:
IMPROVED
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userlocation:CLLocation = locations[0] as CLLocation
manager.stopUpdatingLocation()
let location = CLLocationCoordinate2D(latitude: userlocation.coordinate.latitude, longitude: userlocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.5, 0.5)
let region = MKCoordinateRegion(center: location, span: span)
Mapview.setRegion(region, animated: true)
let locationStrings = ["42.6977,23.3219","43.6977,24.3219"]
// This array must be an array that contains CLLocation objects
var locations: [CLLocation] = []
// We must retrieve the latitude and longitude from locationStrings array to convert them into CLLocation objects
for locationString in locationStrings {
let location = CLLocation(latitude: <latitude_value>, longitude: <latitude_value>)
locations.append(location)
}
// Then you will be able to enumerate through the array
for location in locations {
let distanceMeters = userLocation.distanceFromLocation(location)
if distanceMeters > 5000 { // Some distance filter
// Don't display this location
} else {
// Display this location
}
}
You can use distanceFromLocation method to get distance
let distance = userlocation.distanceFromLocation(YourPinInMap)
locA = [[CLLocation alloc] initWithLatitude:[[[NSUserDefaults standardUserDefaults]valueForKey:#"startLat"]floatValue] longitude:[[[NSUserDefaults standardUserDefaults]valueForKey:#"startlong"]floatValue]];
locB = [[CLLocation alloc] initWithLatitude:[[[NSUserDefaults standardUserDefaults]valueForKey:#"destLat"]floatValue] longitude:[[[NSUserDefaults standardUserDefaults]valueForKey:#"destLong"]floatValue]];
distance = [locA distanceFromLocation:locB];
where locA and locB are CLLocation type pass the lat long over there
I am building a learning app where i want to create pins and show the distance between current location and the pin but i get a really weird output
func createPin(){
var coord = CLLocationCoordinate2D(latitude: 51.50, longitude: -0.13)
var coord2 = CLLocation(latitude: coord.latitude, longitude: coord.longitude)
var kilometers:CLLocationDistance = coord2.distanceFromLocation(locNow)
var str = NSString(format: "%.2f", kilometers)
let pin = Annotation(coordinate: coord, title: "LocationAlfa", subtitle: "distance : \(str)" + " meters", dist: kilometers)
map.addAnnotation(pin)
println("\(kilometers)")
}
this is my create pin method and here i get my location distance
func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!){
let location = newLocation
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
var region: () = centerMapOnLocation(location)
// self.map.setRegion(region, animated: true)
println("Latitude = \(newLocation.coordinate.latitude)")
println("Longitude = \(newLocation.coordinate.longitude)")
locNow = newLocation
}
and this is the shown distance in meters on the map : 5718215.17 (when the pin is made next to the pointed location on the map as the device location)