【问题标题】:Swift 4 Get multiples places from Google Places APISwift 4 从 Google Places API 获取多个地点
【发布时间】:2019-04-08 07:51:14
【问题描述】:

我无法从 Google Places API 获取多个地点。问题是...如果我只获取一种类似 Bars 的 pin 类型,没问题,没问题。但是,如果我试图获得 餐厅、酒吧、赌场...多种类型,那么它给了我唯一的第一名,在我们的例子中是餐厅。

我尝试通过以下链接向 Postman 提出相同的请求...但例如

  • 餐厅 1030 行 JSON
  • 政治83行
  • 尝试获取餐馆 + 政治 = 965 行 JSON。

我使用此代码来获取我想要的地方:

func fetchPlacesNearCoordinate(_ coordinate: CLLocationCoordinate2D, radius: Double, types:[String], completion: @escaping PlacesCompletion) -> Void {

    var urlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\(coordinate.latitude),\(coordinate.longitude)&radius=\(50000)&rankby=prominence&sensor=true&key=\(googleApiKey)"
    let typesString = types.count > 0 ? types.joined(separator: "|") : "food"
    urlString += "&types=\(typesString)"
    urlString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? urlString

    guard let url = URL(string: urlString) else { completion([]); return }

    if let task = placesTask, task.taskIdentifier > 0 && task.state == .running {
        task.cancel()
    }

    DispatchQueue.main.async {
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
    }

    placesTask = session.dataTask(with: url) { data, response, error in

        if data != nil{
            for el in data!{
                //print(el)
            }
        }
        var placesArray: [PlaceContent] = []
        defer {
            DispatchQueue.main.async {
                UIApplication.shared.isNetworkActivityIndicatorVisible = false
                completion(placesArray)
            }
        }

        guard let data = data else { return }

        do{
            let decode = try JSONDecoder().decode(GooglePlacesAnswer.self, from: data)
            placesArray = (decode.results?.map{ $0.toPlaceContent() }) ?? []
        } catch let value{
            print(value.localizedDescription)
        }
    }
    placesTask?.resume()
}

【问题讨论】:

    标签: swift api google-places gmsmapview gmsplace


    【解决方案1】:

    您无法获得官方文档中所述的多种类型的位置。您必须提出多个请求并组合结果。

    https://developers.google.com/maps/documentation/javascript/places

    type — 将结果限制在与指定类型匹配的位置。 只能指定一种类型(如果提供了一种以上的类型,则所有 第一个条目之后的类型被忽略)。请参阅list of supported types

    【讨论】:

    • 是否会正确获取所有机构并在之后对其进行过滤,或者提出很少的请求来获取我需要的所有类型?
    • 发出一些请求以获取您需要的所有类型
    猜你喜欢
    • 2017-11-04
    • 2017-07-31
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多