【发布时间】:2017-04-27 19:24:45
【问题描述】:
我正在尝试使用谷歌地图 SDK 添加多个标记。我获取数据但未插入多个标记,欢迎任何帮助
我尝试以下代码:
import UIKit
import GoogleMaps
import GooglePlaces
class ViewController: UIViewController,GMSMapViewDelegate {
override func viewDidAppear(_ animated: Bool) {
let getPlaces: String = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&type=restaurant&key=AIzaSyCNKHyGGXXfsRq6bsiG6EmtQiy7ApN2TFg"
let frame = GMSCameraPosition.camera(withLatitude: 33.8670522, longitude: 151.1957362, zoom: 12.0)
let mapview = GMSMapView.map(withFrame: self.view.bounds, camera: frame)
let session = URLSession.shared.dataTask(with: URL(string: getPlaces)!) { (data, response, error) in
do{
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
// print(jsonResult)
let returnedPlaces: NSArray? = jsonResult["results"] as? NSArray
if returnedPlaces != nil {
for index in 0..<returnedPlaces!.count {
if let returnedPlace = returnedPlaces?[index] as? NSDictionary {
var placeName = ""
var latitude = 0.0
var longitude = 0.0
if let name = returnedPlace["name"] as? NSString {
placeName = name as String
}
if let geometry = returnedPlace["geometry"] as? NSDictionary{
if let location = geometry["location"] as? NSDictionary {
if let lat = location["lat"] as? Double {
latitude = lat
}
if let lng = location["lng"] as? Double {
longitude = lng
}
}
}
DispatchQueue.main.async{
// let marker = index
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(latitude, longitude)
marker.title = placeName
// self.view = mapview
marker.map = mapview
print("HI see this \(placeName)")
}
}
}
self.view = mapview
}
}catch
{
print("Error")
}
}
session.resume()
}
我得到如下异常:
2017-04-27 12:08:26.207 Inte-GoogleMaps[759:15071] 在从主线程访问引擎后,此应用程序正在从后台线程修改自动布局引擎。这可能会导致引擎损坏和奇怪的崩溃。
由于未捕获的异常“GMSThreadException”而终止应用程序,原因:“必须从主线程调用 API 方法”
【问题讨论】: