Viewdidload method
override func viewDidLoad() {
super.viewDidLoad()
selectedAdressType = "pickup"
mapV.delegate = self
styleOfMap()
mapV.settings.myLocationButton = true
mapV.isMyLocationEnabled = true
// self.pickupAddressTxtF.setLeftPaddingPoints(7)
//self.destinationAddressTxtF.setLeftPaddingPoints(7)
googleLocationTableV.rowHeight = UITableViewAutomaticDimension
googleLocationTableV.estimatedRowHeight = 50
googleLocationTableV.tableFooterView = UIView(frame: .zero)
savedLocationTableV.keyboardDismissMode = .interactive
googleLocationTableV.keyboardDismissMode = .interactive
// Add footer for set pinn location
googleLocationTableV.tableFooterView = AddFooterView()
savedLocationTableV.tableFooterView = AddFooterView()
redirectMap(to: Double("\(latitude)") ?? 0.0, lng: Double("\(longitude)") ?? 0.0)
let userDefaults = UserDefaults.standard
if userDefaults.object(forKey: "LocationInitialData") != nil {
let retriveArrayData = UserDefaults.standard.object(forKey: "LocationInitialData") as? NSData
let dataDic = (NSKeyedUnarchiver.unarchiveObject(with: retriveArrayData! as Data) as? NSDictionary)
print(" saved response = \(dataDic!)")
self.recentSerchList = dataDic?.value(forKey: "recent_search")as! NSArray
self.savedLocationList = dataDic?.value(forKey: "save_address")as! NSArray
self.savedLocationTableV.reloadData()
}
savedLocationTableV.keyboardDismissMode = .onDrag
googleLocationTableV.keyboardDismissMode = .onDrag
// addressSerachApiCall()
if Language.isRTL {
pickupAddressTxtF.textAlignment = .right
}
}
Redirect Method
func redirectMap(to lat: Double, lng: Double) {
// [_mapView clear];
let position: CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat, lng)
let camera = GMSCameraPosition(target: position, zoom: 16, bearing: 0, viewingAngle: 0)
mapV.animate(to: camera)
}
Styling of map show "Unable to find style.json"
func styleOfMap() {
do {
if let styleURL = Bundle.main.url(forResource: "style", withExtension: "json") {
mapV.mapStyle = try GMSMapStyle(contentsOfFileURL: styleURL)
} else {
NSLog("Unable to find style.json")
}
} catch {
NSLog("One or more of the map styles failed to load. \(error)")
}
}
Related
I want to remove this red pins. I am adding custom pins to source (yellow pin) and destination (blue pin, but I still not understand why this red pins also show ?
Here is Code :-
func reDrawRoute(pickupCoordinate : CLLocationCoordinate2D, destinationCoordinate :CLLocationCoordinate2D, type: String) {
// func setMapMarkersRoute(vLoc: CLLocationCoordinate2D, toLoc: CLLocationCoordinate2D) {
self.sourceMarker.map = nil
self.destMarker.map = nil
//add the markers for the 2 locations
if type == "S2D" {
self.sourceMarker = GMSMarker.init(position: pickupCoordinate)
self.sourceMarker.icon = UIImage(named: "source")
self.sourceMarker.map = gMapView
self.destMarker = GMSMarker.init(position: destinationCoordinate)
self.destMarker.icon = UIImage(named: "destination")
self.destMarker.map = gMapView
} else if type == "C2S" {
self.carMarker.position = pickupCoordinate
self.carMarker.icon = UIImage(named: "pin-car")
self.carMarker.map = gMapView
self.destMarker = GMSMarker.init(position: destinationCoordinate)
self.destMarker.icon = UIImage(named: "source")
self.destMarker.map = gMapView
} else if type == "C2D" {
self.carMarker.position = pickupCoordinate
self.carMarker.icon = UIImage(named: "pin-car")
self.carMarker.map = gMapView
self.destMarker = GMSMarker.init(position: destinationCoordinate)
self.destMarker.icon = UIImage(named: "destination")
self.destMarker.map = gMapView
}
//zoom the map to show the desired area
var bounds = GMSCoordinateBounds()
bounds = bounds.includingCoordinate(pickupCoordinate)
bounds = bounds.includingCoordinate(destinationCoordinate)
self.gMapView.moveCamera(GMSCameraUpdate.fit(bounds))
//finally get the route
getRoute(from: pickupCoordinate, to: destinationCoordinate)
}
This is for getting route coordinates between source and destination.
func getRoute(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) {
let source = MKMapItem(placemark: MKPlacemark(coordinate: from))
let destination = MKMapItem(placemark: MKPlacemark(coordinate: to))
let request = MKDirections.Request()
request.source = source
request.destination = destination
request.requestsAlternateRoutes = false
let directions = MKDirections(request: request)
directions.calculate(completionHandler: { (response, error) in
if let res = response {
//the function to convert the result and show
self.show(polyline: self.googlePolylines(from: res))
}
})
}
This code is for showing route.
private func googlePolylines(from response: MKDirections.Response) -> GMSPolyline {
let route = response.routes[0]
var coordinates = [CLLocationCoordinate2D](
repeating: kCLLocationCoordinate2DInvalid,
count: route.polyline.pointCount)
route.polyline.getCoordinates(
&coordinates,
range: NSRange(location: 0, length: route.polyline.pointCount))
let polyline = Polyline(coordinates: coordinates)
let encodedPolyline: String = polyline.encodedPolyline
let path = GMSPath(fromEncodedPath: encodedPolyline)
return GMSPolyline(path: path)
}
I am using this method for adding custom markers..
I am building an application where I have to move multiple marker. These markers will be visible at my end according to the multiple user's live locations. I am able to update only a single marker. but the rest are not updating. I stored these data in firebase and I am getting their data from there.
override func viewDidLoad() {
super.viewDidLoad()
Database.database().reference().child("users").observe(.childChanged, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject]
{
self.hideHUD()
self.latitudeFloatValue = (dictionary["lat"] as! Double)
self.longitudeFloatValue = (dictionary["long"] as! Double)
self.moveMent.delegate = self
//set old coordinate
self.oldCoordinate = CLLocationCoordinate2DMake(self.latitudeFloatValue, self.longitudeFloatValue)
print(self.oldCoordinate)
// Create a GMSCameraPosition that tells the map to display the marker
let camera = GMSCameraPosition.camera(withLatitude: self.latitudeFloatValue, longitude: self.longitudeFloatValue , zoom: 14)
self.mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
self.mapView.isMyLocationEnabled = true
self.mapView.delegate = self
self.view = self.mapView
// Creates a marker in the center of the map.
self.driverMarker = GMSMarker()
self.driverMarker.position = self.oldCoordinate!
self.driverMarker.icon = UIImage(named: "car")
self.driverMarker.map = self.mapView
self.copyCordinates = self.cordinates
print(self.copyCordinates)
print(self.cordinates)
self.cordinates = ["lattitude":self.latitudeFloatValue,"longitude":self.longitudeFloatValue]
print("self.cordinates",self.cordinates)
print(self.oldCordinates)
print(self.newCordinates)
if(self.oldCordinates["lattitude"] == nil)
{
self.oldCordinates = self.cordinates
self.newCordinates = self.cordinates
}
self.newCordinates = self.cordinates
self.oldCordinates = self.copyCordinates
print("oldCordinates",self.oldCordinates)
print("newCordinates",self.newCordinates)
self.movinfMarker()
}
}, withCancel: nil)
//for use in background
self.locman.requestAlwaysAuthorization()
locman.requestWhenInUseAuthorization()
if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways){
guard let currentLocation = locman.location else {
return
}
stringLatitude = currentLocation.coordinate.latitude
stringLongitude = currentLocation.coordinate.longitude
print(currentLocation.coordinate.latitude)
print(currentLocation.coordinate.longitude)
}
// Create a GMSCameraPosition that tells the map to display the marker
let camera = GMSCameraPosition.camera(withLatitude: stringLatitude, longitude: stringLongitude , zoom: 7)
self.mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
self.mapView.isMyLocationEnabled = true
self.mapView.delegate = self
self.view = self.mapView
Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject]
{
self.latitudeFloatValue = (dictionary["lat"] as! Double)
self.longitudeFloatValue = (dictionary["long"] as! Double)
self.titleMarker = (dictionary["username"] as! String)
self.uuidValue = (dictionary["uuid"] as! String)
self.states = [
State(name: self.titleMarker, uuid: self.uuidValue, long: self.longitudeFloatValue, lat: self.latitudeFloatValue),
]
}
for state in self.states {
// Creates a marker in the center of the map.
let state_marker = GMSMarker()
state_marker.position = CLLocationCoordinate2D(latitude: state.lat, longitude: state.long)
state_marker.icon = UIImage(named: "car")
state_marker.title = state.name
state_marker.userData = state.uuid//zIndex = Int32(state.uuid)!
state_marker.snippet = "Hey, this is \(state.name)"
state_marker.map = self.mapView
self.markerDict[state.name] = state_marker
}
}, withCancel: nil)
}
func movinfMarker(){
driverMarker.map = nil
let oldCoodinate: CLLocationCoordinate2D? = CLLocationCoordinate2D(latitude: self.oldCordinates["lattitude"] ?? 0.0 , longitude: self.oldCordinates["longitude"] ?? 0.0)
let newCoodinate: CLLocationCoordinate2D? = CLLocationCoordinate2D(latitude: self.newCordinates["lattitude"] ?? 0.0 , longitude: self.newCordinates["longitude"] ?? 0.0)
print("oldCordinatesNewWala",oldCoodinate as Any)
print("newCordinatesNewWala",newCoodinate as Any)
driverMarker.icon = UIImage(named: "car")
mapView.camera = GMSCameraPosition.camera(withTarget: newCoodinate!, zoom: 17)
driverMarker.groundAnchor = CGPoint(x: CGFloat(0.5), y: CGFloat(0.5))
driverMarker.position = oldCoodinate ?? CLLocationCoordinate2D(latitude: 0.0,longitude: 0.0)
//this can be old position to make car movement to new position
driverMarker.map = mapView
//marker movement animation
CATransaction.begin()
CATransaction.setValue(Int(2.0), forKey: kCATransactionAnimationDuration)
CATransaction.setCompletionBlock({() -> Void in
self.driverMarker.groundAnchor = CGPoint(x: CGFloat(0.5), y: CGFloat(0.5))
//New bearing value from backend after car movement is done
})
driverMarker.position = newCoodinate ?? CLLocationCoordinate2D(latitude: 0.0,longitude: 0.0)
//this can be new position after car moved from old position to new position with animation
driverMarker.map = mapView
driverMarker.groundAnchor = CGPoint(x: CGFloat(0.5), y: CGFloat(0.5))
//found bearing value by calculation
CATransaction.commit()
}
I get this crash error:
MXNet2CoreML[11383:1168377]
*** Terminating app due to uncaught exception 'NSRangeException', reason:
*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'
*** First throw call stack: (0x18333f164 0x182588528 0x18329a020 0x1007894bc 0x1011ef94c 0x1011b0420 0x1021412cc 0x10214128c
0x102145ea0 0x1832e7344 0x1832e4f20 0x183204c58 0x1850b0f84
0x18c95d5c4 0x1007d8894 0x182d2456c)
libc++abi.dylib: terminating with uncaught exception of type
NSException
Here is the Complete Code
//Owais: - Map setup
func resetRegion(){
let region = MKCoordinateRegionMakeWithDistance(annotation.coordinate, 5000, 5000)
mapKit.setRegion(region, animated: true)
}
var myLatitude = ""
var myLongitude = ""
// Array of annotations
let annotation = MKPointAnnotation()
var places = PredictionLocationList().place
var locationsArray = [String]()
var ie: Int = 0
#IBOutlet var mapKit: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let defaults = UserDefaults.standard
let data = defaults.data(forKey: "selectedimage")
let uiimage2 = UIImage(data: data!)
defaults.synchronize()
let image = uiimage2
// imageView.image = image
predictUsingVision(image: image!)
let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
swipeDown.direction = UISwipeGestureRecognizerDirection.down
self.view.addGestureRecognizer(swipeDown)
// Do any additional setup after loading the view.
}
#objc func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
print("Swiped right")
case UISwipeGestureRecognizerDirection.down:
print("Swiped down")
self.dismiss(animated: true, completion: nil)
case UISwipeGestureRecognizerDirection.left:
print("Swiped left")
case UISwipeGestureRecognizerDirection.up:
print("Swiped up")
default:
break
}
}
}
func predictUsingVision(image: UIImage) {
guard let visionModel = try? VNCoreMLModel(for: model.model) else {
fatalError("Something went wrong")
}
let request = VNCoreMLRequest(model: visionModel) { request, error in
if let observations = request.results as? [VNClassificationObservation] {
let top3 = observations.prefix(through: 2)
.map { ($0.identifier, Double($0.confidence)) }
self.show(results: top3)
}
}
request.imageCropAndScaleOption = .centerCrop
let handler = VNImageRequestHandler(cgImage: image.cgImage!)
try? handler.perform([request])
}
typealias Prediction = (String, Double)
func show(results: [Prediction]) {
var s: [String] = []
for (i, pred) in results.enumerated() {
let latLongArr = pred.0.components(separatedBy: "\t")
print("lat long \(latLongArr)")
myLatitude = latLongArr[1]
myLongitude = latLongArr[2]
ie = i
s.append(String(format: "%d: %# %# (%.2f%%)", i + 1, myLatitude, myLongitude, pred.1 * 100))
LocationByCoordinates(latitude: myLatitude, longitude: myLongitude)
// let ew1 = (String(format: "%.2f%", pred.1 * 100))
// print(ew1)
// let double1 = Double(ew1)
// self.doubles.append(double1!)
// print("eueue \(self.doubles)")
// let maxDouble = max(max(double1, double2), double3)
print("first latidue \(myLatitude),,,, \(myLongitude)")
places[i].title = String(i+1)
places[i].coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(myLatitude)!, longitude: CLLocationDegrees(myLongitude)!)
}
// predictionLabel.text = s.joined(separator: "\n")
// Map reset
resetRegion()
mapKit.centerCoordinate = places[0].coordinate
// Show annotations for the predictions on the map
mapKit.addAnnotations(places)
// Zoom map to fit all annotations
zoomMapFitAnnotations()
}
func zoomMapFitAnnotations() {
var zoomRect = MKMapRectNull
for annotation in mapKit.annotations {
let annotationPoint = MKMapPointForCoordinate(annotation.coordinate)
let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0)
if (MKMapRectIsNull(zoomRect)) {
zoomRect = pointRect
} else {
zoomRect = MKMapRectUnion(zoomRect, pointRect)
}
}
self.mapKit.setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsetsMake(50, 50, 50, 50), animated: true)
}
func LocationByCoordinates (latitude: String,longitude:String) {
let mapsKey = UserDefaults.standard.string(forKey: "maps_key") ?? ""
Alamofire.request("https://maps.googleapis.com/maps/api/geocode/json?latlng=\(latitude),\(longitude)&key=\(mapsKey)").responseJSON { response in
if let json = response.result.value {
let request = json as? NSDictionary
if let id = request!["results"] {
// print(id)
let ide = id as? NSArray
let formatted_address = ide![0]
let fors = formatted_address as! NSDictionary
//print(fors.value(forKey: "formatted_address"))
let forss = fors.value(forKey: "formatted_address")
self.locationsArray.append(forss as? String ?? "")
if self.ie == 0 {
self.places[0].identifier = (forss as? String)!
} else if self.ie == 1 {
self.places[1].identifier = (forss as? String)!
} else if self.ie == 2 {
self.places[2].identifier = (forss as? String)!
}
}
}
}
}
}
extension Collection where Indices.Iterator.Element == Index {
subscript (safe index: Index) -> Iterator.Element? {
return indices.contains(index) ? self[index] : nil
}
}
The problem is in this line let formatted_address = ide![0]
If an array is empty, you can't get it's first element with [0] because there is no element at all!
All you have to do is check if the array is not empty before unwrapping it:
if ide!.count > 0 {
//Your code
}
To avoid force-unwrapping ide, you may want to use optional binding like so:
if let id = request!["results"], let ide = id as? NSArray {
let formatted_address = ide[0]
let fors = formatted_address as! NSDictionary
//rest of your code
}
I am creating an app where I have annotation view showing that when you click it shows on the DetailsViewController that annotation data. However, I get "Name", and "Address" data but for phone Number I am getting set as nil. So, if you guys can see my code & help me solve it, I will be appreciated it.
Here is my code:
import UIKit
import MapKit
protocol UserLocationDelegate {
func userLocation(latitude :Double, longitude :Double)
}
class NearMeMapViewController: ARViewController, ARDataSource, MKMapViewDelegate, CLLocationManagerDelegate {
var nearMeIndexSelected = NearMeIndexTitle ()
var locationManager : CLLocationManager!
var nearMeARAnnotations = [ARAnnotation]()
var nearMeRequests = [NearMeRequest]()
var delegate : UserLocationDelegate!
var place: Place?
override func viewDidLoad() {
super.viewDidLoad()
self.title = nearMeIndexSelected.indexTitle
self.locationManager = CLLocationManager ()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = kCLHeadingFilterNone
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.dataSource = self
self.headingSmoothingFactor = 0.05
self.maxVisibleAnnotations = 30
getNearMeIndexSelectedLocation()
}
func getNearMeIndexSelectedLocation()
{
let nearMeRequest = MKLocalSearchRequest()
nearMeRequest.naturalLanguageQuery = nearMeIndexSelected.indexTitle
let nearMeregion = MKCoordinateRegionMakeWithDistance(self.locationManager.location!.coordinate, 250, 250)
nearMeRequest.region = nearMeregion
let nearMeSearch = MKLocalSearch(request: nearMeRequest)
nearMeSearch.start { (response : MKLocalSearchResponse?, error :Error?) in
for requestItem in (response?.mapItems)! {
let nearMeIndexRequest = NearMeRequest ()
nearMeIndexRequest.name = requestItem.name
nearMeIndexRequest.coordinate = requestItem.placemark.coordinate
nearMeIndexRequest.address = requestItem.placemark.addressDictionary?["FormattedAddressLines"] as! [String]
nearMeIndexRequest.street = requestItem.placemark.addressDictionary?["Street"] as! String!
nearMeIndexRequest.city = requestItem.placemark.addressDictionary?["City"] as! String
nearMeIndexRequest.state = requestItem.placemark.addressDictionary?["State"] as! String
nearMeIndexRequest.zip = requestItem.placemark.addressDictionary?["ZIP"] as! String
self.nearMeRequests.append(nearMeIndexRequest)
print(requestItem.placemark.name)
}
for nearMe in self.nearMeRequests {
let annotation = NearMeAnnotation(nearMeRequest: nearMe)
self.nearMeARAnnotations.append(annotation)
self.setAnnotations(self.nearMeARAnnotations)
}
}
}
func ar(_ arViewController: ARViewController, viewForAnnotation: ARAnnotation) -> ARAnnotationView {
let annotationView = NearMeARAnnotationView(annotation: viewForAnnotation)
// annotationView.delegate = self
annotationView.frame = CGRect(x: 0, y: 0, width: 150, height: 50)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapBlurButton(_:)))
annotationView.addGestureRecognizer(tapGesture)
return annotationView
}
func tapBlurButton(_ sender: UITapGestureRecognizer) {
if let annotationView = sender.view as? NearMeARAnnotationView {
if let detailsVc = storyboard?.instantiateViewController(withIdentifier: "DetailsViewController")
as? DetailsViewController {
detailsVc.annotation = annotationView.annotation
if let annotation = annotationView.annotation as? Place {
detailsVc.place = annotation
}
self.navigationController?.pushViewController(detailsVc, animated: true)
}
}
}
}
Just looking over your code quickly:
"\(nearMeAnnotation.nearMeRequest.phone)"
All the other ones have a forced unwrap, this one doesn't. Most probably the value is nil and since you ask for a string representation of a wrapped var that might really be nil sometimes.
I think you should use a default value everywhere instead of a forced unwrap, like:
"\(nearMeAnnotation.nearMeRequest.phone ?? "")"
but also:
"\(nearMeAnnotation.nearMeRequest.street ?? "") \(nearMeAnnotation.nearMeRequest.state ?? "") \(nearMeAnnotation.nearMeRequest.state ?? "") \(nearMeAnnotation.nearMeRequest.zip ?? "")"
With forced unwraps your application will crash if a certain value is not set. This could be handled more elegantly if they're really required, for example already in the constructor of your object. There's the root cause of the optionals you're seeing. In this case NearMeAnnotation.
There are some answer on this, but related to different problems and all in objective-c.
I save in a parse class "Position" positions of users with this:
var locationManager = CLLocationManager()
var lat = locationManager.location.coordinate.latitude
var lon = locationManager.location.coordinate.longitude
let myGeoPoint = PFGeoPoint(latitude: lat, longitude:lon)
let myParseId = PFUser.currentUser().objectId //PFUser.currentUser().objectId
println("****** this is my geoPoint: \(myGeoPoint)")
func sendPosition(userOfPosition: User) {
let takePosition = PFObject(className: "Position")
takePosition.setObject(myParseId, forKey: "who") //who
takePosition.setObject(myGeoPoint, forKey: "where")
takePosition.saveInBackgroundWithBlock(nil)
}
sendPosition(currentUser()!)
so this is my result:
then I want to show them on map, but how? don't understand how to retrive latitude and longitude from "where" column the code below doesn't work:
import UIKit
import MapKit
class MapViewController: UIViewController {
#IBOutlet weak var mapView: MKMapView!
var locationManager : CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var locationManager = CLLocationManager()
var lat = locationManager.location.coordinate.latitude
var lon = locationManager.location.coordinate.longitude
let location = CLLocationCoordinate2D(latitude: lat, longitude: lon)
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegionMake(location, span)
mapView.setRegion(region, animated: true)
let anotation = MKPointAnnotation()
anotation.setCoordinate(location)
anotation.title = "my title"
anotation.subtitle = " my subtitle"
mapView.addAnnotation(anotation)
println("****** Welcome in MapViewController")
//MARK: (471) Crossing Positions
//*******************************************************
let myGeoPoint = PFGeoPoint(latitude: lat, longitude:lon)
let myParseId = PFUser.currentUser().objectId //PFUser.currentUser().objectId
println("****** this is my geoPoint from map view controller: \(myGeoPoint)")
//
// var inspector = PFQuery(className:"GameScore")
// inspector.saveInBackgroundWithBlock {
// (success: Bool, error: NSError?) -> Void in
// if (success) {
// // The object has been saved.
// var the = inspector.objectId
// } else {
// // There was a problem, check error.description
// }
// }
//
//
//
func filterByProximity() {
PFQuery(className: "Position")
.whereKey("where", nearGeoPoint: myGeoPoint, withinKilometers: 500.0) //(474)
.findObjectsInBackgroundWithBlock ({
objects, error in
if let proximityArray = objects as? [PFObject] {
println("****** here the proximity matches: \(proximityArray)")
for near in proximityArray {
println("here they are \(near)")
if let position = near["where"] as! PFGeoPoint {
let theirLat = position.latituide
let theirLon = position.longitude
}
let theirLat = near["where"].latitude as Double
let theirlong = near["where"].longitude as Double
let location = CLLocationCoordinate2DMake(theirLat, theirlong)
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegionMake(location, span)
self.mapView.setRegion(region, animated: true)
let theirAnotation = MKPointAnnotation()
theirAnotation.setCoordinate(location)
self.mapView.addAnnotation(anotation)
}
}
})
}
filterByProximity()
// //update my position
//
// func exists() {
// PFQuery(className:"Position")
// .whereKey("who", containsString: myParseId)
// .findObjectsInBackgroundWithBlock({
// thisObject, error in
// if let result = thisObject as? [PFObject] {
// println("here the result: \(result)")
//
// let gotTheId = result[0].objectId
// println("ecco l'id singolo \(gotTheId)")
//
// //******** update function ********
// var query = PFQuery(className:"Position")
// query.getObjectInBackgroundWithId(gotTheId) {
// (usingObject: PFObject?, error: NSError?) -> Void in
// if error != nil {
// println(error)
// } else if let objectToupdate = usingObject {
// println("else occurred")
// objectToupdate["where"] = myGeoPoint
// println("position should be updated")
// objectToupdate.saveInBackgroundWithBlock(nil)
// println("position should be saved")
//
// }
// }
// //******** end update function ********
// }
// })
// }
//
// exists()
//*******************************************************
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Update after first answers
tried to check for optionals, but have this message:
after not down casting the double:
the 'where' is a PFGeoPoint, you can just call latitude and longitude on them
Try something like this - I'm not 100% sure in Swift syntax, yet
if(geoPoint)
{
if(geoPoint!.latitude)
{
let latitude = geoPoint!.latitude as double;
}
}
this worked. Was both a matter of optionals, and a matter of variables, I was using the wrong ones:
//MARK: (471) Crossing Positions
//*******************************************************
let myGeoPoint = PFGeoPoint(latitude: lat, longitude:lon)
let myParseId = PFUser.currentUser().objectId //PFUser.currentUser().objectId
var radius = 100.0
println("****** this is my geoPoint from map view controller: \(myGeoPoint)")
//MARK: *** let's look for other users ***
var nearArray : [CLLocationCoordinate2D] = []
func filterByProximity() {
PFQuery(className: "Position")
.whereKey("where", nearGeoPoint: myGeoPoint, withinKilometers: radius) //(474)
.findObjectsInBackgroundWithBlock ({
objects, error in
if let proximityArray = objects as? [PFObject] {
// println("****** here the proximity matches: \(proximityArray)")
for near in proximityArray {
// println("here they are \(near)")
let position = near["where"] as? PFGeoPoint
var theirLat = position?.latitude //this is an optional
var theirLong = position?.longitude //this is an optional
var theirLocation = CLLocationCoordinate2D(latitude: theirLat!, longitude: theirLong!)
nearArray.append(theirLocation)
if nearArray.isEmpty {
println("*** ERROR! anyone close by ***")
} else
{
for person in nearArray {
let span = MKCoordinateSpanMake(2.50, 2.50)
let region = MKCoordinateRegionMake(theirLocation, span)
self.mapView.setRegion(region, animated: true)
let theirAnotation = MKPointAnnotation()
theirAnotation.setCoordinate(theirLocation)
theirAnotation.title = near["who"] as String
self.mapView.addAnnotation(theirAnotation)
}
}
}
println("****** in a radius of \(radius) there are \(nearArray.count) bikers ******")
}
})
}
filterByProximity()