2016-07-28 29 views
5

Tôi đang sử dụng bản đồ Google SDK của iOS (Swift).Làm thế nào để "Hiển thị vị trí hiện tại của tôi trên bản đồ google, khi tôi mở ViewController?" trong Swift?

Có ai biết cách "Hiển thị vị trí hiện tại của tôi trên bản đồ google, khi tôi mở ViewController" không?

Thực ra nó giống như ứng dụng Google Maps. Khi bạn mở Google Maps, điểm màu xanh lam sẽ hiển thị vị trí hiện tại của bạn. Bạn không cần nhấn "myLocationButton" trong lần đầu tiên.

Vì vậy, đây là mã:

import UIKit 
import CoreLocation 
import GoogleMaps 

class GoogleMapsViewer: UIViewController { 

    @IBOutlet weak var mapView: GMSMapView! 

    let locationManager = CLLocationManager() 
    let didFindMyLocation = false 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let camera = GMSCameraPosition.cameraWithLatitude(23.931735,longitude: 121.082711, zoom: 7) 
     let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera) 

     mapView.myLocationEnabled = true 
     self.view = mapView 

     // GOOGLE MAPS SDK: BORDER 
     let mapInsets = UIEdgeInsets(top: 80.0, left: 0.0, bottom: 45.0, right: 0.0) 
     mapView.padding = mapInsets 

     locationManager.distanceFilter = 100 
     locationManager.delegate = self 
     locationManager.requestWhenInUseAuthorization() 

     // GOOGLE MAPS SDK: COMPASS 
     mapView.settings.compassButton = true 

     // GOOGLE MAPS SDK: USER'S LOCATION 
     mapView.myLocationEnabled = true 
     mapView.settings.myLocationButton = true 
    } 
} 


// MARK: - CLLocationManagerDelegate 
extension GoogleMapsViewer: CLLocationManagerDelegate { 

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { 
     if status == .AuthorizedWhenInUse { 
      locationManager.startUpdatingLocation() 
      mapView.myLocationEnabled = true 
      mapView.settings.myLocationButton = true 
     } 
    } 
     func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
     if let location = locations.first { 
      mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 20, bearing: 0, viewingAngle: 0) 
      locationManager.stopUpdatingLocation() 
     } 
    } 
} 

Bất cứ ai giúp đỡ? Cảm ơn bạn rất nhiều!

+0

này là đủ cho SHW vị trí hiện tại // GOOGLE MAPS SDK: COM PASS mapView.settings.compassButton = true // GOOGLE MAPS SDK: ĐỊA ĐIỂM CỦA NGƯỜI DÙNG mapView.myLocationEnabled = true mapView.settings.myLocationButton = true –

+0

Có, đủ để hiển thị vị trí hiện tại. Nhưng tôi có thể đặt camera ở vị trí hiện tại của mình không? –

Trả lời

13

Đối Swift giải pháp 3.x, hãy kiểm tra này Answer

Đầu tiên tất cả các bạn đã nhập key trong file Info.plist NSLocationWhenInUseUsageDescription

enter image description here

Sau thêm phím này chỉ cần tạo một biến số CLLocationManager và làm như sau

@IBOutlet weak var mapView: GMSMapView! 
var locationManager = CLLocationManager() 

class YourControllerClass: UIViewController,CLLocationManagerDelegate { 

    //Your map initiation code 
    let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera) 
    self.view = mapView 
    self.mapView?.myLocationEnabled = true 

    //Location Manager code to fetch current location 
    self.locationManager.delegate = self 
    self.locationManager.startUpdatingLocation() 
} 


//Location Manager delegates 
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 

    let location = locations.last 

    let camera = GMSCameraPosition.cameraWithLatitude((location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!, zoom: 17.0) 

    self.mapView?.animateToCameraPosition(camera) 

    //Finally stop updating location otherwise it will come again and again in this delegate 
    self.locationManager.stopUpdatingLocation() 

} 

Khi bạn chạy mã, bạn sẽ nhận được cửa sổ bật lên cho phép và không cho phép vị trí. Chỉ cần nhấp vào Cho phép và bạn sẽ thấy vị trí hiện tại của mình.

Đảm bảo thực hiện điều này trên thiết bị thay vì giả lập. Nếu bạn đang sử dụng trình mô phỏng, bạn phải chọn một số vị trí tùy chỉnh và chỉ bạn mới có thể thấy dấu chấm màu xanh lam.

enter image description here

5

Sử dụng mã này,

Bạn bỏ lỡ addObserver phương pháp và một số nội dung,

viewDidLoad:

mapView.settings.compassButton = YES; 

mapView.settings.myLocationButton = YES; 

mapView.addObserver(self, forKeyPath: "myLocation", options: .New, context: nil) 

dispatch_async(dispatch_get_main_queue(), ^{ 
    mapView.myLocationEnabled = YES; 
    }); 

Observer Phương pháp:

override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { 

    if change[NSKeyValueChangeOldKey] == nil { 

     let location = change[NSKeyValueChangeNewKey] as CLLocation 
     gmsMap.camera = GMSCameraPosition.cameraWithTarget(location.coordinate, zoom: 16) 
    } 
} 

hy vọng hữu ích

3
  • đầu tiên thêm dòng sau vào thông tin của bạn.plist

    1. NSLocationWhenInUseUsageDescription
    2. LSApplicationQueriesSchemes (kiểu mảng và thêm hai mục vào mảng này mục 0: googlechromes, mục 1: comgooglemaps
  • thứ hai đi đến https://developers.google.com/maps/documentation/ios-sdk/start và làm theo các bước cho đến khi bước 5

  • điều cuối cùng cần làm sau khi bạn thiết lập mọi thứ là truy cập ViewController và dán f ollowing

    import UIKit 
    import GoogleMaps 
    
    class ViewController: UIViewController,CLLocationManagerDelegate { 
    
        //Outlets 
        @IBOutlet var MapView: GMSMapView! 
    
        //Variables 
        var locationManager = CLLocationManager() 
    
        override func viewDidLoad() { 
         super.viewDidLoad() 
    
         initializeTheLocationManager() 
         self.MapView.isMyLocationEnabled = true 
        } 
    
        func initializeTheLocationManager() { 
         locationManager.delegate = self 
         locationManager.requestWhenInUseAuthorization() 
         locationManager.startUpdatingLocation() 
        } 
    
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    
         var location = locationManager.location?.coordinate 
    
         cameraMoveToLocation(toLocation: location) 
    
        } 
    
        func cameraMoveToLocation(toLocation: CLLocationCoordinate2D?) { 
         if toLocation != nil { 
          MapView.camera = GMSCameraPosition.camera(withTarget: toLocation!, zoom: 15) 
         } 
        } 
    
    } 
    

(đừng quên thêm một cái nhìn trong kịch bản và kết nối nó với các MapViw)

bây giờ bạn có thể xây dựng và chạy để xem vị trí hiện tại của bạn trên bản đồ google chỉ giống như khi bạn mở Google Map App

thưởng thức mã hóa :)

0
import UIKit 
import GoogleMaps 
import GooglePlaces 
import CoreLocation 

class ViewController: UIViewController,CLLocationManagerDelegate,GMSMapViewDelegate { 

    @IBOutlet weak var currentlocationlbl: UILabel! 

    var mapView:GMSMapView! 

    var locationManager:CLLocationManager! = CLLocationManager.init() 
    var geoCoder:GMSGeocoder! 
    var marker:GMSMarker! 

    var initialcameraposition:GMSCameraPosition! 
    override func viewDidLoad() { 

     super.viewDidLoad() 

     // Do any additional setup after loading the view, typically from a nib. 

     self.mapView = GMSMapView() 
     self.geoCoder = GMSGeocoder() 
     self.marker = GMSMarker() 
     self.initialcameraposition = GMSCameraPosition() 

     // Create gms map view-------------> 
     mapView.frame = CGRect(x: 0, y: 150, width: 414, height: 667) 
     mapView.delegate = self 
     mapView.isMyLocationEnabled = true 
     mapView.isBuildingsEnabled = false 

     mapView.isTrafficEnabled = false 
     self.view.addSubview(mapView) 
     // create cureent location label----------> 

     self.currentlocationlbl.lineBreakMode = NSLineBreakMode.byWordWrapping 
     self.currentlocationlbl.numberOfLines = 3 
     self.currentlocationlbl.text = "Fetching address.........!!!!!" 

     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation 
     if locationManager.responds(to: #selector(CLLocationManager.requestAlwaysAuthorization)) 
     { 
      self.locationManager.requestAlwaysAuthorization() 
     } 
     self.locationManager.startUpdatingLocation() 

     if #available(iOS 9, *) 
     { 
      self.locationManager.allowsBackgroundLocationUpdates = true 
     } 
     else 
     { 
      //fallback earlier version 
     } 

     self.locationManager.startUpdatingLocation() 
     self.marker.title = "Current Location" 
     self.marker.map = self.mapView 

     // Gps button add mapview 

     let gpbtn:UIButton! = UIButton.init() 
     gpbtn.frame = CGRect(x: 374, y: 500, width: 40, height: 40) 
     gpbtn.addTarget(self, action: #selector(gpsAction), for: .touchUpInside) 
     gpbtn.setImage(UIImage(named:"gps.jpg"), for: .normal) 
     self.mapView.addSubview(gpbtn) 
    } 

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 
    { 
     var location123 = CLLocation() 
     location123 = locations[0] 
     let coordinate:CLLocationCoordinate2D! = CLLocationCoordinate2DMake(location123.coordinate.latitude, location123.coordinate.longitude) 
     let camera = GMSCameraPosition.camera(withTarget: coordinate, zoom: 16.0) 

     self.mapView.camera = camera 
     self.initialcameraposition = camera 
     self.marker.position = coordinate 
     self.locationManager.stopUpdatingLocation()  
    } 

    func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) 
    { 
     self.currentAddres(position.target) 
    } 

    func currentAddres(_ coordinate:CLLocationCoordinate2D) -> Void 
    { 
     geoCoder.reverseGeocodeCoordinate(coordinate) { (response, error) in 

      if error == nil 
      { 
       if response != nil 
       { 
        let address:GMSAddress! = response!.firstResult() 

        if address != nil 
        { 
         let addressArray:NSArray! = address.lines! as NSArray 

         if addressArray.count > 1 
         { 
          var convertAddress:AnyObject! = addressArray.object(at: 0) as AnyObject! 
          let space = "," 
          let convertAddress1:AnyObject! = addressArray.object(at: 1) as AnyObject! 
          let country:AnyObject! = address.country as AnyObject! 

          convertAddress = (((convertAddress.appending(space) + (convertAddress1 as! String)) + space) + (country as! String)) as AnyObject 

          self.currentlocationlbl.text = "\(convertAddress!)".appending(".") 
         } 
         else 
         { 
          self.currentlocationlbl.text = "Fetching current location failure!!!!" 
         } 
        } 
       } 
      } 
     } 
    } 
Các vấn đề liên quan