duanlei20082008 2017-07-26 22:03
浏览 75

从JSON数据创建MapKit点(Swift)

Hi I have a file on a server json format with several map points:

 [{"ID":"34","CompanyName":"Sruper","Latitude":"33.8886954","Longitude":"35.4911273","Location":"USA","Category":"Automobile "},{"ID":"47","CompanyName":"TechMe","Latitude":"33.8869625","Longitude":"35.5131741","Location":"USA","Category":"Home "},{"ID":"48","CompanyName":"ElectroKey","Latitude":"33.8786214","Longitude":"35.4863271","Location":"USA","Category":"Health & Fitness "}]

I want to put these points as markers on my map in my ios app. I've looked at several pages and here but I have not found anything and what I have tried does not work. I am using swift 3 and Xcode.

I was able to retrieve the data as arrays but can not put them in the map view because they are array and not double how can I do this, With a loop? I get the error Could not cast value of type '__NSArrayI' (0x112f16dd8) to 'NSNumber'

I am using Swift and can't find the answer for swift but their is for objective c iOS JSON Array and MapKit

    let url = URL(string: "http://file.php")
    let data = try? Data(contentsOf: url!)

    let quotesData = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray

    let CompanyNameArray = quotesData.value(forKey: "CompanyName")
    let LocationLatitudeArray = quotesData.value(forKey: "Latitude")
    let LocationLongitudeArray = quotesData.value(forKey: "Longitude")
 struct Location {
        let title: String
        let latitude: Double
        let longitude: Double
    }

    let locations = [
        Location(title:CompanyNameArray as! String,    latitude: LocationLatitudeArray as! Double, longitude: LocationLongitudeArray as! Double),

    ]

    let annotations = locations.map { location -> MKAnnotation in
        let annotation = MKPointAnnotation()
        annotation.title = location.title
        annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
        return annotation
    }
    mapView.addAnnotations(annotations)

Any help,please?

  • 写回答

1条回答 默认 最新

  • douzhao4071 2017-07-26 22:20
    关注

    To access an array value, you must use array[index] like: CompanyNameArray[index]. You should iterate through the items in the array, and fill the array with locations.

    评论

报告相同问题?