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
Related
Currently the user location is logged each time he visits the home screen. It needs to also update when the user is on the move so that the location stays current.
Here I set the location upon login
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let databaseRef = Database.database().reference()
let uid = Auth.auth().currentUser!.uid
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
print("locations = \(locValue.latitude) \(locValue.longitude)")
latestLocation = ["latitude" : locValue.latitude, "longitude" : locValue.longitude]
let lat = locValue.latitude
let lon = locValue.longitude
dict = CLLocation(latitude: lat, longitude: lon)
print("dict", dict)
if let locationDictionary = latestLocation {
databaseRef.child("people").child(uid).child("Coordinates").setValue(locationDictionary)
}
}
Now I just nee it to always setValue when user moves materially.
You can look into startMonitoringSignificantLocationChanges() method and don't for get to call startUpdatingLocation
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?
i'm trying to pass my latitude and longitude to my url params but is returning Nil, but when i print within the delegate it returns the longitude and latitude and i can't seem to find the issue, i've tried many different ways and nothing seems to work
this are the variable where i store my latitude and longitude
var lat: Double!
var long: Double!
this is my delegate
func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]){
currentLocation = manager.location!.coordinate
let locValue:CLLocationCoordinate2D = currentLocation!
self.long = locValue.longitude
self.lat = locValue.latitude
print(lat)
print(long)
}
and here pass them to variables i'm using in my URL parameters but they return nil and i don't understand why
let userLat = String(describing: lat)
let userLong = String(describing: long)
Thank You
Try something like:
Swift 3
func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]){
if let last = locations.last {
sendLocation(last.coordinate)
}
}
func sendLocation(_ coordinate: CLLocationCoordinate2D) {
let userLat = NSString(format: "%f", coordinate.latitude) as String
let userLong = NSString(format: "%f", coordinate.longitude) as String
// Run API Call....
}
I think the Joseph K's answer is not correct. It rounds off the values of the latitude and longitude. It will be something like the code below.
let coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(exactly: 35.6535425)!, longitude: CLLocationDegrees(exactly: 139.7047917)!)
let latitude = coordinate.latitude // 35.6535425
let longitude = coordinate.longitude // 139.7047917
let latitudeString = NSString(format: "%f", latitude) as String // "35.653543"
let longitudeString = NSString(format: "%f", longitude) as String // "139.704792"
So the correct and simpler code is:
Swift 3
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let coordinate = locations.last?.coordinate else { return }
let latitude = "\(coordinate.latitude)"
let longitude = "\(coordinate.longitude)"
// Do whatever you want to make a URL.
}
I am trying to show three things on map :
GPS (the current location) , Marker 1 , Marker 2, but I am not sure I am doing it right or not ! Here is my code :
self.startMarker.position = CLLocationCoordinate2D(latitude: self.startLatitude, longitude: self.startLongitude)
self.startMarker.icon = #imageLiteral(resourceName: "Pin Start")
self.startMarker.map = self.mapView
self.endMarker.position = CLLocationCoordinate2D(latitude: self.endLatitude, longitude: self.endLongitude)
self.endMarker.icon = #imageLiteral(resourceName: "Pin End")
self.endMarker.map = self.mapView
let southWest = CLLocationCoordinate2DMake(self.startLatitude,self.startLongitude)
let northEast = CLLocationCoordinate2DMake(self.endLatitude,self.endLongitude)
let bounds = GMSCoordinateBounds(coordinate: northEast, coordinate: southWest)
let camera = self.mapView.camera(for: bounds, insets:.zero)
self.mapView.camera = camera!
More Code :
// MARK: - Google Map
private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.authorizedWhenInUse {
mapView.isMyLocationEnabled = true
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let newLocation = locations.last
mapView.camera = GMSCameraPosition.camera(withTarget: newLocation!.coordinate, zoom: 14)
mapView.isMyLocationEnabled = true
}
The result is like this :
What I need :
EDITED
if let myLocation = self.mapView.myLocation {
let path = GMSMutablePath()
path.add(myLocation.coordinate)
path.add(self.startMarker.position)
path.add(self.endMarker.position)
let bounds = GMSCoordinateBounds(path: path)
self.mapView.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 40))
}
Showing All Markers with screen bound:
Here I am trying to provide you one simple example, hope this will help you.
Using this, you can show any number of markers on screen.
Example:
let path = GMSMutablePath()
for var i in 0 ..< array.count //Here take your "array" which contains lat and long.
{
let marker = GMSMarker()
let lat = Double(array.objectAtIndex(i).valueForKey(lattitude) as! String)
let long = Double(arrayr.objectAtIndex(i).valueForKey(longitude) as! String)
marker.position = CLLocationCoordinate2DMake(lat!,long!)
path.addCoordinate(marker.position)
marker.map = self.mapView
}
let bounds = GMSCoordinateBounds(path: path)
self.mapView!.animateWithCameraUpdate(GMSCameraUpdate.fitBounds(bounds, withPadding: 30.0))
Can you try the below code, this is converted from ObjC code here is the documentation of includingCoordinate
let bounds = GMSCoordinateBounds()
bounds.includingCoordinate(self.startMarker.position)
bounds.includingCoordinate(self.endMarker.position)
bounds.includingCoordinate(yourCurrentLocationPosition)
self.mapView.animateWithCameraUpdate(GMSCameraUpdate(fitBounds:bounds, padding:20.0f))
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
showMarkers(locations)
//stop updating location when you find suitable
}
func showMarkers(userLocation: [CLLocation]){
let location1: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: self.startLatitude, longitude: self.startLongitude)
let location2: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: self.endLatitude, longitude: self.endLongitude)
let location3: CLLocationCoordinate2D = userLocation[0].coordinate
var locationArray = []
locationArray.append(location1)
locationArray.append(location2)
locationArray.append(location3)
var bounds = GMSCoordinateBounds()
for location in locationArray
{
let latitude = location.valueForKey("latitude")
let longitude = location.valueForKey("longitude")
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
marker.map = self.mapView
bounds = bounds.includingCoordinate(marker.position)
}
let update = GMSCameraUpdate.fitBounds(bounds, withPadding: 100)
mapView.animateWithCameraUpdate(update)
}
Note:
locationArray contains three locations ie. Marker 1, Marker 2, user location.
For someone who is looking for solution with Objective-C, This might help
//Locations
CLLocationCoordinate2D source = CLLocationCoordinate2DMake(19.2880, 72.1587);
CLLocationCoordinate2D userLocation = CLLocationCoordinate2DMake(19.1780, 72.9577);
CLLocationCoordinate2D destination = CLLocationCoordinate2DMake(19.0760, 72.8777);
//Create a GMSMutablePath
GMSMutablePath *path = [GMSMutablePath new];
[path addCoordinate:source];
[path addCoordinate:userLocation];
[path addCoordinate:destination];
//Create bounds
GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc]initWithPath:path];
//Update the camera position
[mapview animateWithCameraUpdate:[GMSCameraUpdate fitBounds:bounds]];
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)