首页 > 解决方案 > 如何使用谷歌地方 API 从邮政编码中获取建议的地址?

问题描述

使用 Google Places API 时,如何根据用户输入的英国邮政编码获取预测地址列表?我设置GMSAutocompleteFilter为输入.address。我究竟做错了什么?附上截图。完整的邮政编码是 ig11 7ps

import UIKit
import GooglePlaces

class TestViewController: UIViewController {

var textField: UITextField?
var resultText: UITextView?
var fetcher: GMSAutocompleteFetcher?


  override func viewDidLoad() {
     super.viewDidLoad()

    view.backgroundColor = .white
    edgesForExtendedLayout = []

    // Set bounds in United Kingdom to
    // - Easternmost point – Lowestoft Ness, Suffolk at 52°29′N 1°46′E
    // - Westernmost point – Corrachadh Mòr, Highland at 56°42′N 6°13′W

    let neBoundsCorner = CLLocationCoordinate2D(latitude: 52.48333333,
                                                longitude: 1.76666667)
    let swBoundsCorner = CLLocationCoordinate2D(latitude: 52.70000000,
                                                longitude: 6.21666667)
    let bounds = GMSCoordinateBounds(coordinate: neBoundsCorner,
                                     coordinate: swBoundsCorner)


    // Set up the autocomplete filter.
    let filter = GMSAutocompleteFilter()
    filter.type = .address

    // Create the fetcher.
    fetcher = GMSAutocompleteFetcher(bounds: bounds, filter: filter)
    fetcher?.delegate = self

    textField = UITextField(frame: CGRect(x: 5.0, y: 10.0,
                                          width: view.bounds.size.width - 5.0,
                                          height: 44.0))
    textField?.autoresizingMask = .flexibleWidth
    textField?.addTarget(self, action: #selector(textFieldDidChange(textField:)),
                         for: .editingChanged)

    resultText = UITextView(frame: CGRect(x: 0, y: 45.0,
                                          width: view.bounds.size.width,
                                          height: view.bounds.size.height - 45.0))
    resultText?.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
    resultText?.text = "No Results"
    resultText?.isEditable = false

    view.addSubview(textField!)
    view.addSubview(resultText!)
 }//end viewDidLoad


  func textFieldDidChange(textField: UITextField) {
     fetcher?.sourceTextHasChanged(textField.text!)
  }

}//end of class

extension TestViewController: GMSAutocompleteFetcherDelegate {

  func didAutocomplete(with predictions: [GMSAutocompletePrediction]) {
     let resultsStr = NSMutableString()
      for prediction in predictions {
 resultsStr.appendFormat("%@\n", prediction.attributedPrimaryText.string)

     }

       resultText?.text = resultsStr as String
}

   func didFailAutocompleteWithError(_ error: Error) {
      resultText?.text = error.localizedDescription
   }   
}

在此处输入图像描述

标签: swiftgoogle-places-api

解决方案


推荐阅读