Swift mapView load more pins - swift

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.

Related

Swift - MapView duplicate annotations

I'm querying data from FireStore and displaying the elements on a MapView, using a cursor I am able to paginate data.
This is my custom Annotation class:
final class PostAnnotation: NSObject, MKAnnotation {
var title: String?
var coordinate: CLLocationCoordinate2D
var username: String
var post: PostModel
var subtitle: String?
init(address: PostPlaceMark) {
self.title = address.title
self.coordinate = address.coordinate
self.username = address.username
self.post = address.post
self.subtitle = address.subTitle
}
}
I hit a button to load more data, for testing purposes my data pool is quite small around 7-10 elements. However, whenever I fetch/refresh data, I always get a duplicate of the previous group of annotations.
For instance, when my MapView first loads I have batch of annotations, hit my refresh button I have batch of annotations 1 and batch of annotations 2 but also have a duplicate of batch of annotations 1. Hit refresh again I have batch of annotations one x 3, batch of annotations two x 2 and just one instance of all data belonging to batch of annotations three.
I have managed to figure out where the issue lies but I have two extremes here:
One I keep getting duplicate annotations
Two the previous batch is
removed
The reason I am doing this is to combat the fact there may/can be a number of annotations surrounding a particular view. I have limited to where the issue and potential solution may lie.
private static func annotationsByDistributingAnnotationsContestingACoordinate(annotations: [PostAnnotation], constructNewAnnotationWithClosure ctor: annotationRelocator) -> [PostAnnotation] {
var newAnnotations = [PostAnnotation]()
let contestedCoordinates = annotations.map{ $0.coordinate }
let newCoordinates = coordinatesByDistributingCoordinates(coordinates: contestedCoordinates)
newAnnotations.removeAll()
for (i, annotation) in annotations.enumerated() {
let newCoordinate = newCoordinates[i]
let newPost = annotation.post
let newAnnotation = ctor(annotation, newCoordinate, newPost)
print(newAnnotation.post.location)
newAnnotations.forEach { (naac) in
annotations.forEach { (element) in
if newAnnotations.contains(where: {$0.post.postID == naac.post.postID}) {
let index = newAnnotations.firstIndex{$0.post.postID == naac.post.postID}
// newAnnotations.remove(at: index!)
print("removed")
// newAnnotations.removeAll(where: {$0.post.postID == naac.post.postID})
}
}
}
newAnnotations.append(newAnnotation)
}
let withoutDuplicates = Array(Set(newAnnotations))
return withoutDuplicates
}
I can detect if the element is already in the array, however, removing it, even the firstIndex causes me to lose the annotation completely.
This is how I add/update my annotations, in case you was wondering:
private func updateAnnotations(from mapView: MKMapView) {
let annotations = self.address.map(PostAnnotation.init)
let newAnnotations = ContestedAnnotationTool.annotationsByDistributingAnnotations(annotations: annotations) {
(oldAnn: MKAnnotation, newCoordinate:CLLocationCoordinate2D, post: PostModel) -> (PostAnnotation) in
PostAnnotation(address: PostPlaceMark.init(post: post, coordinate: newCoordinate, title: "\(post.manufacturer) \(post.model)", username: post.username, subTitle: "£\(post.price)"))
}
mapView.removeAnnotations(mapView.annotations)
mapView.addAnnotations(newAnnotations)
}

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

Swift: Removing only one MKPolyline of several

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"?

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.