2016-09-22 2 views
0

나는 매우 새롭고 Google Maps SDK로 어려움을 겪고 있습니다. Google지도 SDK를 사용하여 실제로 경로를 생성 할 수 있습니까? 마치 "Generate Route"라고 쓰여진 버튼을 클릭 한 다음 한번 클릭하면 실제 Google지도 앱을 사용하는 것처럼 실제로 탐색 할 수있는 경로가 생성됩니다. 감사.GoogleMaps SDK를 사용하여 경로를 생성 하시겠습니까?

답변

1

예 :

func getDiectionFromGoogle(startCoordinate: CLLocationCoordinate2D, toLocation: CLLocationCoordinate2D) { 
    var urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(startCoordinate.latitude),\(startCoordinate.longitude)&destination=\(toLocation.latitude),\(toLocation.longitude)&key=\("your key!!")" 
    urlString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! 
    let session = URLSession.shared 
    let placesTask = session.dataTask(with: URL(string: urlString)!, completionHandler: {data, response, error in 
     if error != nil { 
     } 
     if let jsonResult = (try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)) as? NSDictionary { 

      // *******UPDATE********** 
      print(jsonResult) // this returns a dictionary 

      if let routes = jsonResult["routes"] as? NSArray { 
       // example to get data from dictionary 
      } 

     }) 
     placesTask.resume() 
    } 

당신이 jsonResult의 내용물을 참조하십시오. 방향 등을위한 경로를 생성하는 데 필요한 모든 좌표를 찾을 수 있습니다!

또한 json 요청에 더 많은 매개 변수를 사용할 수 있습니다. 여기 좀 봐. 10월 15일

https://developers.google.com/maps/documentation/directions/intro

// 업데이트는 당신이 인코딩 된 경로에 문제가 발생한 것 같아요. 다음은 경로를 디코딩하는 방법입니다. 나는 가장 간단한 방법을 사용하지 않을 것이라고 확신하지만, 그냥 작동하기 때문에 그냥 무시합니다. 하하

// you can see a key called polyline in somewhere in the dictionary 
// polylineCoordinates are all the coordinates for your routes 
// path can be used for polyline 
if let polyline = (paths[i] as AnyObject).value(forKey: "polyline") as? NSDictionary { 
    if let points = polyline.value(forKey: "points") as? String { 
     let gmsPath = GMSPath(fromEncodedPath: points) 
     for index in 0 ..< gmsPath!.count() { 
      let coordinate = gmsPath!.coordinate(at: index) 
      self.polylineCoordinates.append(coordinate) 
      self.path.add(coordinate) 
     } 
    } 
} 

다음은 폴리 라인 사용 방법에 대한 Google 문서입니다. 이 코드에 대해서는 어떤 코드도 제공하지 않겠습니다. 나는 당신이 그것을 풀 수 있다고 확신합니다. 옳게함으로써 배우는가? 하지만 당신이 뭔가를 붙이면, 당신은 나에게 돌아올 수 있습니다. 도와 드리겠습니다. https://developers.google.com/maps/documentation/ios-sdk/shapes

Google지도와 같은 탐색 기능을 Google이 제공하는지 여부는 확실하지 않습니다. 나 자신에 의해 내 애플 리케이션 탐색을 빌드합니다. 가능한 경우 도와 드리겠습니다. 10월 20일

// 갱신 당신은 거의있다. 경로 [i]는 여기 LOL에서옵니다. 정말 못생긴 코드.

enter image description here

if let jsonResult = (try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)) as? NSDictionary { 
    if let routes = jsonResult["routes"] as? NSArray { 
     if let legs = routes.value(forKey: "legs") as? NSArray { 
      if let steps = legs.value(forKey: "steps") as? NSArray { 
       if steps.count != 0 { 
        if let firstStep = steps.object(at: 0) as? NSArray { 
         if firstStep.count != 0 { 
          if let paths = firstStep.object(at: 0) as? NSArray { 
           if paths.count > 0 { 
            for i in 0 ..< paths.count { 

내 그래프를 참조하기로 [0] intersection1 좌표 시작이다 경로 1는 intersection2 할 intersection1이고 path [2] 최종 좌표 intersection2이다.

사실 내 self.path는 쓸모가 없습니다. jsonResult에서 경로를 디코딩하면됩니다. self.polylineCoordinates를 사용하는 이유는 내 그래프에서 빨간색 삼각형과 같은 모든 좌표를 가져 와서 내 탐색을 만들려고하기 때문입니다. jsonResult에서 startAt (내가 잘못 기억하지 못했다면)라는 키와 endAt라는 키를 볼 수 있습니다.이 좌표는 그래프에서 검은 색 삼각형으로 나타납니다. 모든 좌표를 가져와야하는 이유는 교차점에서 다른 교차점까지의 경로가 직선이 아니기 때 문에 교차점 1에서 교차점 2와 같은 곡선이 될 수 있기 때문입니다.

+0

거룩한 쓰레기 이것은 멋져 보입니다! 시간을내어 회신하기 전에 기다려 주셔서 감사 드리며 유감스럽게 생각합니다. 그러나 나는 이것에 대해 아주 새롭기 때문에 이것을 어떻게 표시 할 수 있는지, 또는 json이 어떻게/무엇인지를 알 수는 없다. 너 더 설명 할 수 있니? 감사! – skyleguy

+0

또한 안드로이드가 아니라 iOS 앱에서이 작업을 수행하고 있음을 분명히하고 싶습니다! – skyleguy

+1

이것은 Swift이므로 ios도 마찬가지입니다. jsonResult는 주로 { "name": { "John": "male", "Mary": "female", "Bob": "male}"과 같은 사전을 반환합니다. –