簡體   English   中英

如何在Google Places自動完成iOS中顯示距離

[英]how to show distance in google place autocomplete iOS

我正在嘗試實現自動完成框。 在該應用中,我想在表格視圖的左側顯示一個帶有標簽的距離。 我認為他們使用的是Places Autocomplete API,但我不知道它在表格視圖的左側顯示距離。

這是我想要的照片。

extension ViewController: GMSAutocompleteResultsViewControllerDelegate {
    func resultsController(_ resultsController: GMSAutocompleteResultsViewController,
                       didAutocompleteWith place: GMSPlace) {
        searchController?.isActive = false
        // Do something with the selected place.
        print("Place name: \(place.name)")
        print("Place address: \(place.formattedAddress)")
        print("Place attributions: \(place.attributions)")

        self.googleMapsView.clear()

        let position: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: place.coordinate.latitude, longitude: place.coordinate.longitude)
        let marker:GMSMarker = GMSMarker(position: position)

        markerPosition = CLLocation(latitude: marker.position.latitude, longitude: marker.position.longitude)

        marker.title = place.name
        marker.appearAnimation = kGMSMarkerAnimationPop
        marker.icon = GMSMarker.markerImage(with: .red)
        marker.map = self.googleMapsView

        self.googleMapsView.camera = GMSCameraPosition.camera(withLatitude: (place.coordinate.latitude), longitude: (place.coordinate.longitude), zoom: 17.0, bearing: 0, viewingAngle: 0)

        searchController?.searchBar.text = place.name

        self.dismiss(animated: true, completion: nil) // dismiss after select place
    }

    func resultsController(_ resultsController: GMSAutocompleteResultsViewController,
                       didFailAutocompleteWithError error: Error){
        // TODO: handle the error.
        print("Error: ", error.localizedDescription)
    }
}

您可以使用CLLocation對象上的函數計算給定GMSPlace到您當前設備位置之間的距離:

func distance(from location: CLLocation) -> CLLocationDistance

在您的具體示例中:

if let currentPosition = self.googleMapsView.myLocation {
     //returns the distance between two CLLocation objects in meters
     let distance = markerPosition.distance(from: currentPosition)
}

現在,您可以將distance轉換並格式化為所需的distance

或者,您可以使用CLLocationManager獲取當前設備的位置。

謝謝你的答案。 現在,我可以計算距離,但是無法在Tableview單元格的左側顯示距離。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM