rscode101 February 2016

CLLocationCoordinate2D into one array

I have a dynamic amount of locations being plotted onto a mapkit. I am curious on how I can get my current latitudes and longitudes into a single array, as they are currently being printed as separate objects which is not plotting not the map like it should. I know the problem but not sure how to fix it. Here is my current code to produce the coordinates -

  do {
        let place = try myContext.executeFetchRequest(fetchRequest) as! [Places]

        for coords in place{
            let latarray = Double(coords.latitude!)
            let lonarray = Double(coords.longitude!)
            let arraytitles = coords.title!

            let destination:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latarray, lonarray)

        print(destination)

    } catch let error as NSError {
        // failure
        print("Fetch failed: \(error.localizedDescription)")
    }

And here is the print in the console - Output

What I need the print to look like to work correctly - Desired output

I hope you understand what I mean. I am very grateful of any help! Thank you for reading.

Answers


dzk February 2016

You could create an array of CLLocationCoordinate2Ds:

var coordinateArray: [CLLocationCoordinate2D] = []

if latarray.count == lonarray.count {
    for var i = 0; i < latarray.count; i++ {
        let destination = CLLocationCoordinate2DMake(latarray[i], lonarray[i])
        coordinateArray.append(destination)
    }
}

EDIT:

In your code, neither latarray nor lonarray is an array. If you want to create an array of CLLocationCoordinate2Ds, you should add a variable to store your locations and your for loop should look like this:

var locations: [CLLocationCoordinate2D] = []

for coords in place{
    let lat = Double(coords.latitude!)
    let lon = Double(coords.longitude!)
    let title = coords.title!

    let destination = CLLocationCoordinate2DMake(lat, lon)
    print(destination) // This prints each location separately

    if !locations.contains(destination) {
        locations.append(destination)
    }
}

print(locations) // This prints all locations as an array

// Now you can use your locations anywhere in the scope where you defined the array.
func getLocationFromArray() {
    // Loop through the locations array:
    for location in locations {
        print(location) // Prints each location separately again
    }
}

Post Status

Asked in February 2016
Viewed 3,554 times
Voted 14
Answered 1 times

Search




Leave an answer