Карта распространения с использованием Google Map в Swift 5 - PullRequest
0 голосов
/ 20 января 2020

Прежде всего создайте ключ API на портале Google Console, а затем создайте файл info.plist, который будет включен в каталог проекта. После этого в AppDelegate метод didfinishLoad напишите код.

Импорт googleMap и googlePlace и

GMSServices.provideAPIKey(“Your_API_Key”)
GMSPlacesClient.provideAPIKey("Your_API_Key") 

Переход к просмотру класса контроллера В перетаскивании xib перетащите uiview и переименуйте его с помощью GMSMapView

И дать выход для представления и объявить переменную

@IBOutlet weak var vwMap: GMSMapView!
let marker = GMSMarker()

let locationManager : CLLocationManager = CLLocationManager()
let geocoder : CLGeocoder = CLGeocoder()
var placemark : CLPlacemark = CLPlacemark()

Затем

Метод ViewDidLoad, где мы создаем карту и просматриваем карту здесь

override func viewDidLoad() {
    super.viewDidLoad()


    let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
    vwMap.camera = camera
    self.showMarker(position: vwMap.camera.target)
    vwMap.delegate = self

    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.startUpdatingLocation()

    vwMap.settings.myLocationButton = true
    vwMap.settings.compassButton = true
    vwMap.settings.indoorPicker = true
    vwMap.settings.scrollGestures = true
    vwMap.settings.zoomGestures = true
    vwMap.isMyLocationEnabled = true

    vwMap.padding = UIEdgeInsets(top: 0, left: 0, bottom: 50, right: 50)

}

Это метод, созданный для текущей точки привязки местоположения

func showMarker(position: CLLocationCoordinate2D)  {

    marker.position = position
    marker.title = ""
    marker.snippet = "XXX"
    marker.map = vwMap
    marker.isDraggable = true

    drow_circle()
}

Этот метод создан для получения информации о местоположении

func geocode(latitude: CLLocationDegrees, longitude: CLLocationDegrees) -> String {
    let location = CLLocation(latitude: latitude, longitude: longitude)
    let geocoder = CLGeocoder()

    var str = ""

    geocoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in

        // Place details
        var placeMark: CLPlacemark!
        placeMark = placemarks?[0]

        if let locationName = placeMark.name
        {
            str = str + (locationName as String)
        }

        // Street address
        if let street = placeMark.subLocality {
            str = str + (street as String)
        }

        // City
        if let city = placeMark.locality {
            str = str + (city as String)
        }

        // Zip code
        if let zip = placeMark.postalCode {
            str = str + (zip as String)
        }

        // Country
        if let country = placeMark.country {
            str = str + (country as String)
        }

        self.lblAddress.text = str

    })
    return str
}

} ​​

Расширение, созданное для делегатов MapView

extension MapViewController : GMSMapViewDelegate,CLLocationManagerDelegate {
    func mapView(_mapview : GMSMapView, didTapInfoWindowOf marker: GMSMarker){
        print("click on marker")
    }

    func mapView(_ mapView: GMSMapView, didLongPressInfoWindowOf marker: GMSMarker) {
        print("long press")
    }

    func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
        let view = UIView(frame: CGRect.init(x: 0, y: 0, width: 200, height: 100))
        view.backgroundColor = .white
        view.layer.cornerRadius = 6

        let titleLbl = UILabel(frame: CGRect.init(x: 8, y: 8, width: view.frame.size.width-16, height: 15))
        titleLbl.text = "Hi Google\(marker.title)"
        view.addSubview(titleLbl)

        return view
    }

    func mapView(_ mapView: GMSMapView, didBeginDragging marker: GMSMarker) {
        print("draging")
    }

    func mapView(_ mapView: GMSMapView, didEndDragging marker: GMSMarker) {
        print("end Draging")
        drow_circle()
    }

    func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
        marker.position = coordinate
        self.geocode(latitude: coordinate.latitude, longitude: coordinate.longitude)
    }

    func drow_circle()  {
        let circlePos = marker.position
        let circle = GMSCircle(position: circlePos, radius: 100000)
        circle.map = vwMap
    }


    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error.localizedDescription)
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }

        let location = CLLocation(latitude: locValue.latitude, longitude: locValue.longitude)

    //         self.geocode(latitude: locValue.latitude, longitude: locValue.longitude)


    }

}`enter code here`
...