Swift: Removing only one MKPolyline of several - swift

I have two polylines on the map:
var polylineRoute : MKGeodesicPolyline!
var polylineFlight : MKGeodesicPolyline!
I assign each of them a title and add them to the map like this (in different methods):
let polyline = MKGeodesicPolyline(coordinates: &routeCoordinates, count: routeCoordinates.count)
polyline.title = "route"
self.mapView.addOverlay(polyline)
self.polylineRoute = polyline
and
let polyline = MKGeodesicPolyline(coordinates: &routeCoordinates, count: routeCoordinates.count)
polyline.title = "flight"
self.mapView.addOverlay(polyline)
self.polylineFlight = polyline
Now, when a specific action is triggered, I would like to remove only the flight overlay and leave the route overlay intact.
This does not work at all:
func removeFlightPath()
{
self.mapView.removeOverlay(self.polylineFlight)
self.polylineFlight = nil
}
The following works but removes both polylines:
func removeFlightPath()
{
var overlays = mapView.overlays
mapView.removeOverlays(overlays)
}
Is there a working way to remove only one polyline? I searched the forum and there is only one response that is saying that it is possible using the title. However, it does not specify how it can be done.
Thanks a lot!
EDIT:
This solves the issue:
func removeFlightPath()
{
if self.polylineFlight != nil
{
// Overlays that must be removed from the map
var overlaysToRemove = [MKOverlay]()
// All overlays on the map
let overlays = self.mapView.overlays
for overlay in overlays
{
if overlay.title! == "flight"
{
overlaysToRemove.append(overlay)
}
}
self.mapView.removeOverlays(overlaysToRemove)
}
}

I think your source code is correct. Could be that the reference counting is messing it up. As long as the object is referred to, MKGeodesicPolyline will not be removed. In your code, you have used a local variable to create the polyline object. I have tried it without using a local variable and it is removing the polyline.
self.polylineFlight = MKGeodesicPolyline(coordinates: &routeCoordinates, count: routeCoordinates.count)
self.polylineFlight.title = "flight"

polylineFlight doesn't look right. It's built from routeCoordinates, the same as polylineRoute. So removing it would produce no change in the map.
Are you building from the right coordinates?
Can we see before/after screenshots? Or can we see a clarification of "does not work at all"?

Related

Getting a count on how many custom annotations are added to a mapView swift 4

I feel like this is something simple that I am just over looking. I have a map that the user pushes a button to add an annotation.
func addPinToPath() {
let catchPathPin = CatchAnnotation()
let catchLat = map.userLocation.coordinate.latitude
let catchLon = map.userLocation.coordinate.longitude
catchPathPin.coordinate = CLLocationCoordinate2D(latitude: catchLat, longitude: catchLon)
catchPathPin.title = "Fish On"
catchPathPin.subtitle = "Path"
catchPathPin.annoID = annoIDStart
catchPathPin.pinImageName = "catch"
let idToPass = catchPathPin.annoID
annoIDCatch = idToPass!
print(annoIDCatch)
map.addAnnotation(catchPathPin)
bitesInRoute = catchPathPin
}
at this point I would like to have a counter that shows in the display as to how many annotations are added.
annotations.count will give me a count of all annotations, but I only want the count for CatchPathPin
Theres two options. You could have a count variable that you increment every time
addPinToPath is called. The other option is to filter the current annotations and get the count from there.
count = map.annotations
.filter { $0 is CatchAnnotation }
.count

Allocating the results of Reverse Geocoding to a global variable

I am using Swift 4 and Xcode 9.3.1. I'm including screenshots of the code.
I am new to mobile development/ programming in general and have been thinking about how to phrase this. So this is the best I can explain it:
I am building an app that gets the user's location in order to send assistance through to them. The app gets the user's coordinates, and displays a TextView with their address information. So pretty straight forward mapKit/coreLocation functionality. So far, so good: Getting the coordinates with startUpdatingLocation() works fine, and I've used Reverse Geocoder to get the street name & locality. But they-- meaning the decoded street and locality strings-- only print out if I call them within the closure, not outside it. I've understood (correctly or incorrectly?) that variables that need to be available for multiple functions within a class should to be declared globally at the top. However I can't figure out how to extract the information from this closure in order to use it elsewhere.
I've been googling and reading through questions in stackOverflow and I feel like something really simple is missing but can't figure out what. Things I've tried unsuccessfully so far:
1_ Defining global variables as empty strings at the beginning of the class
and using the variable names inside the closure where the geocoding reverse method happens, in an attempt to store the resulting strings, but when I try to print the variables outside the closure, the global variable is still and empty string ("").
[global variables declared at the top][1]
2_Defining an empty, global array of strings and appending the information from inside the closure to the global array. Still got an empty array outside the closure. (so same as 1)
3_Create a function --func decodedString()-- to return the data as a String, so I can use it by declaring
*let streetLocation : String = decodedString()*
However when I declare that function like this :
var street = ""
var locality = ""
// Get the street address from the coordinates
func deocodedString() -> String {
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) { placemarks, error in
if let placemark = placemarks?.first {
self.street = placemark.name!
self.locality = placemark.locality!
let string = "\(self.street), \(self.locality)"
return string
}
}
}
I get an error of: Unexpected non-void return value in void function
unexpected no void return value in void function
Lastly, if I pass the information straight into a TextView within the closure by using the code below, my textView updates successfully-- but I can't format the strings, which I need to do in order to make them look like the design instructions I'm following (aka some bold text, some regular text, and some different sizes of text):
CLGeocoder().reverseGeocodeLocation(location) { placemarks, error in
if let placemark = placemarks?.first {
self.street = placemark.name!
self.locality = placemark.locality!
let string = "\(self.street), \(self.locality)"
self.addressTextView.text = string
}
}
So that's why I can't just pass it through with the textView.text = string approach.
I'd appreciate some help...I have been looking though StackOverFlow, youtube and other tutorial places but I can't figure out what I'm missing, or why my function declaration generates an error. I have already destroyed and reversed my code several times over last 24 hs without getting an independent string that I can apply formatting to before passing it into the textView and I'm at a loss as to how else to approach it.
When you call this function the reverseGeocodeLocation runs in the background thread. So if you want to return the address in this method you should use escaping closure.
func getaddress(_ position:CLLocationCoordinate2D,completion:#escaping (String)->()) {
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) { placemarks, error in
if let placemark = placemarks?.first {
let street = placemark.name!
let locality = placemark.locality!
let string = "\(street), \(locality)"
completion(string)
}
}
}
self.getaddress(position.target) { address in
print(address)
self.addressTextView.text = address
}
I had a problem with google geocoder to update the label on the map screen.
So I did this, first, create
swift file name: GoogleAPI just call it as you like.
class GoogleAPI {
static let sharedInstance = GoogleAPI()
private init() { }
var addressValue = ""
public func geocoding(lat: Double, long: Double) {
Alamofire.request("https://maps.googleapis.com/maps/api/geocode/json?latlng=\(lat),\(long)&key=YOUR_GOOGLE_KEY").responseJSON { (response) in
if response.result.isSuccess {
let dataJSON : JSON = JSON(response.result.value!)
self.geocoding(json: dataJSON)
} else {
print("Error \(response.result.error!)")
}
}
}
fileprivate func geocoding(json: JSON) {
let json = json["results"]
let address = json[1]["formatted_address"].stringValue
addressValue = address
print("pin address \(addressValue)")
}
}
This is an API call to Google to fetch all from a response and parse the only street.
After that go to your View Controller with a map where is the pin, map etc..
Set up a pin, marker to be draggable. [marker1.isDraggable = true]
Then add this function
mapView(_ mapView: GMSMapView, didEndDragging marker: GMSMarker)
and add call from above like this :
func mapView(_ mapView: GMSMapView, didEndDragging marker: GMSMarker) {
GoogleAPI.sharedInstance.geocoding(lat: marker.position.latitude, long: marker.position.longitude)
DispatchQueue.main.async {
self.txtSearch.text = GoogleAPI.sharedInstance.addressValue
}
}
txtSearch is my search text field.
yea I know, that can be done better, but no time. this is working.
Swift 4.2

ARKit limit display distance of a node

I would like to create a node in sceneView, that is displayed at normal position in the scene, until user get too close or too far from it. Then it should be displayed at the same direction from the user, but with restricted distance. So far best I found is SCNDistanceConstraint, which limits this distance, but the problem is, that this constraint after it moved the node, this node stays in this new place. So for example, I want to limit the node to be displayed not closer then one meter from camera. I'm getting closer to the node, and it's being pushed away, but then when I get camera back, this node should return to it's original position - for now it stays where it was pushed. Is there some easy way to get such behavior?
Im not entirely sure I have understood what you mean, but it seems you always want your SCNNode to be positioned 1m away from the camera, but keeping its other x, y values?
If this is the case then you can do something like this:
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
//1. Get The Current Node On Screen & The Camera Point Of View
guard let nodeToPosition = currentNode, let pointOfView = augmentedRealityView.pointOfView else { return }
//2. Set The Position Of The Node 1m Away From The Camera
nodeToPosition.simdPosition.z = pointOfView.presentation.worldPosition.z - 1
//3. Get The Current Distance Between The SCNNode & The Camera
let positionOfNode = SCNVector3ToGLKVector3(nodeToPosition.presentation.worldPosition)
let positionOfCamera = SCNVector3ToGLKVector3(pointOfView.presentation.worldPosition)
let distanceBetweenNodeAndCamera = GLKVector3Distance(positionOfNode, positionOfCamera)
print(distanceBetweenNodeAndCamera)
}
I have added in part three, so you could use the distance to do some additional calculations etc.
Hope this points you in the right direction...
The answer above is not exactly what I need - I want object to be displayed like it was just placed in normal position, so I can get closer and farer to/from it, but limit how close/far I can get from that object. When I'm beyond that limit, object should start move to be always within given distance range from camera. Anyway I think I have found some right direction in this. Instead of assigning position, I'm creating a constraint that constantly updates position of my node to be either in given position if it's in given range from user, or if not, adjusts this position to fit in that range:
private func setupConstraint() {
guard let mainNodeDisplayDistanceRange = mainNodeDisplayDistanceRange else {
constraints = nil
position = requestedPosition
return
}
let constraint = SCNTransformConstraint.positionConstraint(inWorldSpace: true) { (node, currentPosition) -> SCNVector3 in
var cameraPositionHorizontally = (self.augmentedRealityView as! AugmentedRealityViewARKit).currentCameraPosition
cameraPositionHorizontally.y = self.requestedPosition.y
let cameraToObjectVector = self.requestedPosition - cameraPositionHorizontally
let horizontalDistanceFromCamera = Double((cameraToObjectVector).distanceHorizontal)
guard mainNodeDisplayDistanceRange ~= horizontalDistanceFromCamera else {
let normalizedDistance = horizontalDistanceFromCamera.keepInRange(mainNodeDisplayDistanceRange)
let normalizedPosition = cameraPositionHorizontally + cameraToObjectVector.normalizeHorizontally(toDistance: normalizedDistance)
return normalizedPosition
}
return self.requestedPosition
}
constraints = [constraint]
}
internal var requestedPosition: SCNVector3 = .zero {
didSet {
setupConstraint()
}
}
This starts to work fine, but I still need to find a way to animate this.

Swift mapView load more pins

I have a method that showing me multiple Annotations on the map. Its About 10 000 annotation so i have to show only annotation that are visible on the map in current time. When I move with map i execute method that return me objects with coordinates that will be visible. But my method will delete all of them and start to adding them to map one by one. My goal is when I present Annotations and i move with map i want to keep the ones that are visible and the others remove. I am using this and FBAnnotationClusteringSwift framework.
this is my method for adding pins.
private var arrOfPinsOnMap:[FBAnnotation] = []
private var clusteringManager = FBClusteringManager()
func addMapPoints(){
self.arrOfPinsOnMap.removeAll()
self.clusteringManager = FBClusteringManager() //everytime recreate instance otherwise there will be duplicates.
for i in 0..<sortedObjectsByDistance_ids.count {
var id_pobor = String()
let pin = FBAnnotation()
guard let tempUniqueE21 = get_sortedObjectsByDistance(i) else {
continue
}
let temp = tempUniqueE21
pin.coordinate = CLLocationCoordinate2D(latitude: tempUniqueE21.lat, longitude: tempUniqueE21.lng)
pin.title = temp.provoz
pin.subtitle = temp.ulice
self.clusteringManager.addAnnotations([pin])
self.arrOfPinsOnMap.append(pin)
}
}
I am calling this method overtime when user move with map. The problem is not with FB framework but with stored Annotation values.

Create an array of MKPointAnnotation objects

Currently working with Map Views and adding pins to the map. I know how to add a single point to the map using addAnotation() method. Now, I am trying to add multiple points to the MapView in the easiest way. I've fetched the data (latitude, longitude and name from an online XML file) and stored it in an array and now I want to add all those coordinates+name as pins in the map. For doing so I've declared an array of MKPointAnnotation objects like so:
var pinsArray: [MKPointAnnotation] = []
And then for dumping the collected data to I've done the following:
for i in 0...(myFeed.count-1) {
pinsArray[i].title = myFeed.objectAtIndex(i).objectForKey("NOMBRE")!.stringValue
pinsArray[i].coordinate = CLLocationCoordinate2D(latitude: myFeed[i].objectForKey("LATITUD")!.doubleValue, longitude: myFeed[i].objectForKey("LONGITUD")!.doubleValue)
pinsArray[i].subtitle = ""
mapView.addAnnotation(pinsArray[i])
}
But when I run the app I get an error saying that the array index is out of range (fatal error: Array index out of range). I guess this is a problem on the declaration of the pinsArray, I do not really know how to solve this one.
Try this:
var pinsArray: [MKPointAnnotation] = []
for i in 0...(myFeed.count-1)
{
let pointAnnotation = MKPointAnnotation() // First create an annotation.
pointAnnotation.title = myFeed.objectAtIndex(i).objectForKey("NOMBRE")!.stringValue
pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: myFeed[i].objectForKey("LATITUD")!.doubleValue, longitude: myFeed[i].objectForKey("LONGITUD")!.doubleValue)
pointAnnotation.subtitle = ""
pinsArray.append(pointAnnotation) // Now append this newly created annotation to array.
}
mapView.addAnnotations(pinsArray) // Add all the annotations to map view at once.