2017-02-18 70 views
0

我想實現一個自動完成框。在那個應用程序中,我想用tableview中左邊的標籤顯示距離。我認爲他們正在使用地方自動完成API,但我不知道它顯示在tableview左側的距離。如何在谷歌地方顯示距離自動完成iOS

This picture is what I want.

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) 
    } 
} 

回答

0

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

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) 
} 

現在你可以c反轉和格式化你的distance到你想要的。

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

+0

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

-1

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

相關問題