2017-11-03 3 views
3

내가 장소 마커를 추가하기 위해 구글 맵이 클래스mapKit를 시작하고 두 점 (스위프트) 사이의 탐색을 시작

import UIKit 
import CoreLocation 
import GoogleMaps 
import GooglePlaces 
import SwiftyJSON 
import Alamofire 
import MapKit 

class FinalClass: UIViewController { 

    @IBOutlet weak var containerView: UIView! 
    @IBOutlet weak var bottomInfoView: UIView! 
    @IBOutlet weak var descriptionLabel: UILabel! 
    @IBOutlet weak var distanceLabel: UILabel! 



    var userLocation:CLLocationCoordinate2D? 
    var places:[QPlace] = [] 
    var index:Int = -1 

    var locationStart = CLLocation() 
    var locationEnd = CLLocation() 

    var mapView:GMSMapView! 
    var marker:GMSMarker? 






    override func loadView() { 
     super.loadView() 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 



     guard index >= 0, places.count > 0 else { 
      return 


     } 

     let place = places[index] 
     let lat = place.location?.latitude ?? 1.310844 
     let lng = place.location?.longitude ?? 103.866048 

     // Google map view 
     let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lng, zoom: 12.5) 
     mapView = GMSMapView.map(withFrame: self.view.bounds, camera: camera) 
     mapView.autoresizingMask = [.flexibleHeight, .flexibleWidth, .flexibleTopMargin, .flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin] 
     self.containerView.addSubview(mapView) 

     // Add gesture 
     addSwipeGesture() 

     didSelect(place: place) 
     if userLocation != nil { 
      addMarkerAtCurrentLocation(userLocation!) 

     } 
    } 

    func addSwipeGesture() { 
     let directions: [UISwipeGestureRecognizerDirection] = [.right, .left] 
     for direction in directions { 
      let gesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(sender:))) 
      gesture.direction = direction 
      self.bottomInfoView.addGestureRecognizer(gesture) 
     } 
    } 

    func addMarkerAtCurrentLocation(_ userLocation: CLLocationCoordinate2D) { 
     let marker = GMSMarker() 
     marker.position = userLocation 
     marker.title = "Your location" 
     marker.map = mapView 
    } 

    func didSelect(place:QPlace) { 

     guard let coordinates = place.location else { 
      return 
     } 

     // clear current marker 
     marker?.map = nil 

     // add marker 
     marker = GMSMarker() 
     marker?.position = coordinates 
     marker?.title = place.name 
     marker?.map = mapView 
     mapView.selectedMarker = marker 
     moveToMarker(marker!) 

     // update bottom info panel view 
     let desc = place.getDescription() 
     descriptionLabel.text = desc.characters.count > 0 ? desc : "-" 
     distanceLabel.text = "-" 

     // update distance 
     if userLocation != nil { 
      let dist = distance(from: userLocation!, to: coordinates) 
      distanceLabel.text = String.init(format: "Distance %.2f meters", dist) 
      self.drawPath(startLocation: userLocation!, endLocation: coordinates) 
     } 

     title = place.name 
    } 

    func moveToMarker(_ marker: GMSMarker) { 
     let camera = GMSCameraPosition.camera(withLatitude: marker.position.latitude, 
               longitude: marker.position.longitude, 
               zoom: 12.5) 
     self.mapView.animate(to: camera) 
    } 

    // distance between two coordinates 
    func distance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance { 
     let from = CLLocation(latitude: from.latitude, longitude: from.longitude) 
     let to = CLLocation(latitude: to.latitude, longitude: to.longitude) 

     return from.distance(from: to) 

    } 

    func handleSwipe(sender: UISwipeGestureRecognizer) { 

     guard index >= 0, places.count > 0 else { 
      return 
     } 

     if sender.direction == .left { 
      if index < places.count - 2 { 
       index += 1 
       didSelect(place: places[index]) 
      } 
     } else if sender.direction == .right { 
      if index > 1 { 
       index -= 1 
       didSelect(place: places[index]) 
      } 
     } 
    } 




    func drawPath(startLocation: CLLocationCoordinate2D, endLocation: CLLocationCoordinate2D) { 

     let from = CLLocation(latitude: startLocation.latitude, longitude: startLocation.longitude) 
     let to = CLLocation(latitude: endLocation.latitude, longitude: endLocation.longitude) 

     let origin = "\(from.coordinate.latitude),\(from.coordinate.longitude)" 
     let destination = "\(to.coordinate.latitude),\(to.coordinate.longitude)" 


     let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving" 

     Alamofire.request(url).responseJSON { response in 

      print(response.request as Any) // original URL request 
      print(response.response as Any) // HTTP URL response 
      print(response.data as Any)  // server data 
      print(response.result as Any) // result of response serialization 

      let json = JSON(data: response.data!) 
      let routes = json["routes"].arrayValue 

      // print route using Polyline 
      for route in routes 
      { 
       let routeOverviewPolyline = route["overview_polyline"].dictionary 
       let points = routeOverviewPolyline?["points"]?.stringValue 
       let path = GMSPath.init(fromEncodedPath: points!) 
       let polyline = GMSPolyline.init(path: path) 
       polyline.strokeWidth = 4 
       polyline.strokeColor = UIColor.black 
       polyline.map = self.mapView 
      } 

     } 

    } 


    @IBAction func navigationStart(_ sender: Any) { 





    } 

을 사용하고,지도에 방향을 그릴 수있는 버튼 기능에 두 개의 좌표를 추가 그리고 두 지점 사이의 거리를 보여주고, 이제는 startLocation: userLocation!endLocation: coordinates 사이의 탐색기를 시작하고 싶습니다. 그러나 일부 연구를 통해 동일한보기에서 탐색기를 시작할 수 없다는 것을 알았습니다.지도 응용 프로그램을 열어야하기 때문에 MapKit 및 버튼 추가

@IBAction func navigationStart(_ sender: Any) { 


} 

그래서지도 애플리케이션에서 열리는 버튼을 눌러 userLocation에서 coordinates 방향으로 열려면 어떻게해야하나요? 나는 이미 비슷한 질문을 한 것이지만, 내 문제와는 조금 다르다. 왜냐하면 나는 이미 다른 형식을 사용하고 있기 때문이다.

답변

0

귀하의 질문은 약간 혼란 스럽지만지도 앱을 열고 사용자의 현재 위치에서지도의 다른 지점으로 방향을 표시하려면 사용자의 위치 (그냥 목적지 :

)를 전달할 필요가 없습니다.

스위프트 4 :

let coordinate = CLLocationCoordinate2DMake(51.5007, -0.1246) 
let placeMark = MKPlacemark(coordinate: coordinate) 
let mapItem = MKMapItem(placemark: placeMark) 
mapItem.name = "Big Ben" 
mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]) 

목적 C :

CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(51.5007, -0.1246); 
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate: coordinate]; 
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark]; 
[mapItem setName:@"Big Ben"]; 
[mapItem openInMapsWithLaunchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving}]; 
+0

예 내 유일한 문제는 당신이 내 코드를 보면이 didSelect을 FUNC에 의해, 나의 목적지가 표시되는 점이다 (PL 에코 : QPlace) { 가드하자 { 반환 } 그래서 상수 "좌표"목적지, 나는 단추의 func에이 상수를 추가하는 방법을 모르겠어요 –

+0

저장하지 왜 그때 그것에 대한 참조? 또는 버튼을 눌렀을 때 장소를 얻으시겠습니까? – Leon

+0

이전 VC에서 장소를 얻습니다. 어떻게 참조를 저장할 수 있습니까? –