欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[IOS]整合google map并获取当前位置

程序员文章站 2022-07-14 11:49:21
...

1.下载Google map的sdk,详情参考:

Get Started

2.准备好SDK后,展示map这些问题都不大,稍微难点的是定位当前位置

可以参考google的git tutorial:

https://github.com/googlemaps/maps-sdk-for-ios-samples/tree/master/tutorials

 

同时可以参考:

iOS之集成GoogleMap(定位、搜索)需要注意的事:http://www.cocoachina.com/cms/wap.php?action=article&id=21868
3.我的示例代码:
import UIKit
import GoogleMaps
import GooglePlaces

let screenH = UIScreen.main.bounds.size.height
let screenW = UIScreen.main.bounds.size.width

class BookController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    //MARK:UI widget
    @IBOutlet weak var googleMapView: UIView!
    @IBOutlet weak var merchantTable: UITableView!
    @IBOutlet weak var searchBarView: UIView!
    
    //MARK:Others
    var merchantList: Array<MerchantBookDetail> = []
    
    //MARK: Google map
    var placesClient: GMSPlacesClient!
    var locationManager = CLLocationManager()
    var currentLocation: CLLocation?
    var mapView: GMSMapView?
    var zoomLevel: Float = 16.0
    
    // An array to hold the list of likely places.
    var likelyPlaces: [GMSPlace] = []
    
    // The currently selected place.
    var selectedPlace: GMSPlace?
    
    // A default location to use when location permission is not granted.
    let defaultLocation = CLLocation(latitude: -33.869405, longitude: 151.199)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        initData()
        initView()
        
    }

    func initData()  {
        
        merchantList = initMerchant()
        
        placesClient = GMSPlacesClient.shared()
        // Initialize the location manager.
        locationManager = CLLocationManager()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.distanceFilter = 50
        locationManager.startUpdatingLocation()
        locationManager.delegate = self
        
    }
    
    func initView()  {
        loadGoogleMap()
        
        //table
        merchantTable.delegate = self
        merchantTable.dataSource = self
        merchantTable.separatorStyle = UITableViewCellSeparatorStyle.none
        
        
    }
    
    func initMerchant() -> Array<MerchantBookDetail> {
        let merchant_one = MerchantBookDetail(merchant: "般咸道35号地下\n电话:2297 3377")
        let merchant_two = MerchantBookDetail(merchant: "尖沙咀金马伦道12号\n恒信商业大厦l字全层\n电话:3422 8855")
        
        let merchantList : [MerchantBookDetail] = [merchant_one,merchant_two];
        
        return merchantList
    }
    
    // Update the map once the user has made their selection.
    @IBAction func unwindToMain(segue: UIStoryboardSegue) {
        // Clear the map.
        mapView?.clear()
        
        // Add a marker to the map.
        if selectedPlace != nil {
            let marker = GMSMarker(position: (self.selectedPlace?.coordinate)!)
            marker.title = selectedPlace?.name
            marker.snippet = selectedPlace?.formattedAddress
            marker.map = mapView
        }
        
        listLikelyPlaces()
    }
    
    // Populate the array with the list of likely places.
    func listLikelyPlaces() {
        // Clean up from previous sessions.
        likelyPlaces.removeAll()
        
        placesClient.currentPlace(callback: { (placeLikelihoods, error) -> Void in
            if let error = error {
                // TODO: Handle the error.
                print("Current Place error: \(error.localizedDescription)")
                return
            }
            
            // Get likely places and add to the list.
            if let likelihoodList = placeLikelihoods {
                for likelihood in likelihoodList.likelihoods {
                    let place = likelihood.place
                    self.likelyPlaces.append(place)
                }
            }
        })
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func selectBtnAction(_ sender: Any) {
        
        let bookSelectVC:BookSelectController = UIStoryboard.init(name: "Book", bundle: nil).instantiateViewController(withIdentifier: "book-select") as! BookSelectController
        
        self.navigationController?.pushViewController(bookSelectVC, animated: true)
        
    }
    
     func loadGoogleMap() {
        // Create a GMSCameraPosition that tells the map to display the
        let camera = GMSCameraPosition.camera(withLatitude: defaultLocation.coordinate.latitude,
                                              longitude: defaultLocation.coordinate.longitude,
                                              zoom: zoomLevel)
        let rect = CGRect(x: 0, y: 0, width: googleMapView.frame.width, height: googleMapView.frame.height)
        mapView = GMSMapView.map(withFrame: rect, camera: camera)
        mapView?.settings.myLocationButton = true
        mapView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        mapView?.isMyLocationEnabled = true
        mapView?.settings.compassButton = true
        googleMapView.backgroundColor = UIColor.clear
        // Add the map to the view, hide it until we've got a location update.
        googleMapView.addSubview(mapView!)
//        mapView?.isHidden = true
        listLikelyPlaces()
        
        googleMapView.addSubview(searchBarView)
        
        
    }

    func safeAreaInsetmap(view: UIView) -> UIEdgeInsets {
        if #available(iOS 11, *) {
            return view.safeAreaInsets
        }
        return UIEdgeInsets.zero
    }
    
    //MARK:table view API
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return merchantList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let row = indexPath.row
        let cellId = "book_map_cell"
        let cell: BookMapTableCellTableViewCell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! BookMapTableCellTableViewCell
        
        let merchant = merchantList[row]
        
        cell.merchantDetail.text = merchant.merchantDetail
        cell.merchantImage.image = UIImage.init(named: "merchantImage_\(row+1)")
        
        return cell
    }
}


// Delegates to handle events for the location manager.
extension  BookController: CLLocationManagerDelegate {
    
    // Handle incoming location events.
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location: CLLocation = locations.last!
        print("Location: \(location)")
        
        let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude,
                                              longitude: location.coordinate.longitude,
                                              zoom: zoomLevel)
        let position2D = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let marker = GMSMarker(position: position2D)
        marker.map = self.mapView
        
        if (mapView?.isHidden)! {
            mapView?.isHidden = false
            mapView?.camera = camera
        } else {
            mapView?.animate(to: camera)
        }
        
        listLikelyPlaces()
    }
    
    // Handle authorization for the location manager.
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .restricted:
            print("Location access was restricted.")
        case .denied:
            print("User denied access to location.")
            // Display the map using the default location.
            mapView?.isHidden = false
        case .notDetermined:
            print("Location status not determined.")
        case .authorizedAlways: fallthrough
        case .authorizedWhenInUse:
            print("Location status is OK.")
        }
    }
    
    // Handle location manager errors.
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        locationManager.stopUpdatingLocation()
        print("Error: \(error)")
    }
}
 


[IOS]整合google map并获取当前位置
            
    
    博客分类: IOS google map定位 
 

  • [IOS]整合google map并获取当前位置
            
    
    博客分类: IOS google map定位 
  • 大小: 657.8 KB
相关标签: google map 定位

上一篇: java 版本更迭

下一篇: MIME