показывать несколько маркеров в Google Maps API для iOS - PullRequest
0 голосов
/ 03 февраля 2020

Я новичок в области быстрой разработки и внедрения Google Maps SDK для iOS для нашего приложения рецептов. Он имеет функцию показа супермаркетов рядом с текущим местоположением, например this .

Мое приложение необходимо для отображения нескольких маркеров, которые указывают, где супермаркеты находятся рядом с текущим местоположением на карте моего приложения, но я не Не знаю, как подать заявку, чтобы найти супермаркеты рядом с текущим местоположением.

, и я следую этому уроку. https://www.raywenderlich.com/197-google-maps-ios-sdk-tutorial-getting-started

Есть некоторые проблемы. 1. Изначально можно ли таким образом включить то, что я хочу? Я сомневаюсь, что способ этого урока может сделать это, потому что я полагаю, что этот урок должен быть старым. 2. показать ошибку Использование необъявленного типа 'GooglePlace

import UIKit
import GoogleMaps

class PlaceMarker: GMSMarker {
    // 1
    let place: GooglePlace

    // 2
    init(place: GooglePlace) {
      self.place = place
      super.init()

      position = place.coordinate
      groundAnchor = CGPoint(x: 0.5, y: 1)
      appearAnimation = .pop
    }
}
Использование неразрешенного идентификатора 'GoogleDataProvider'

import UIKit
import CoreLocation
import GoogleMaps

class MapViewController: UIViewController {
    var mapView: GMSMapView!

    private let locationManager = CLLocationManager()

    private let dataProvider = GoogleDataProvider()
    private let searchRadius: Double = 1000


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        //        locationManager.delegate = self as? CLLocationManagerDelegate
        //        locationManager.requestWhenInUseAuthorization()
        //        mapView.delegate = self as? GMSMapViewDelegate
        //
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self as! CLLocationManagerDelegate
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
        }
        let camera = GMSCameraPosition.camera(withLatitude: locationManager.location!.coordinate.latitude, longitude: locationManager.location!.coordinate.longitude, zoom: 15);
        mapView = GMSMapView.map(withFrame: self.view.bounds, camera: camera)
        mapView.delegate = self as! GMSMapViewDelegate
        self.view.addSubview(mapView)
        mapView.settings.myLocationButton = true
        mapView.isMyLocationEnabled = true

        mapView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            mapView.topAnchor.constraint(equalTo: view.topAnchor),
            mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
        ])


        if CLLocationManager.locationServicesEnabled() {
            switch (CLLocationManager.authorizationStatus()) {
            case .notDetermined, .restricted, .denied:
                print("No access")
            case .authorizedAlways, .authorizedWhenInUse:
                print("Access")
            }
        } else {
            print("Location services are not enabled")
        }
    }

    func showCurrentLocation() {
        mapView.settings.myLocationButton = true
        let locationObj = locationManager.location as! CLLocation
        let coord = locationObj.coordinate
        let lattitude = coord.latitude
        let longitude = coord.longitude
        print(" lat in  updating \(lattitude) ")
        print(" long in  updating \(longitude)")

        let center = CLLocationCoordinate2D(latitude: locationObj.coordinate.latitude, longitude: locationObj.coordinate.longitude)
        let marker = GMSMarker()
        marker.position = center
        marker.title = "current location"
        marker.map = mapView
        //let camera: GMSCameraPosition = GMSCameraPosition.camera(withLatitude: lattitude, longitude: longitude, zoom: Float(5))
        //self.mapView.animate(to: camera)
        //        mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    }




    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */

}


extension MapViewController: GMSMapViewDelegate {

}

extension MapViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        guard status == .authorizedWhenInUse else {
            return
        }

        locationManager.startUpdatingLocation()
        mapView.isMyLocationEnabled = true
        mapView.settings.myLocationButton = true
        self.showCurrentLocation()

    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.first else {
            return
        }
        mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
        locationManager.stopUpdatingLocation()
        self.showCurrentLocation()
    }
}

Swift 5 Xcode 11.3

Я ценю и приветствую любую помощь. Большое спасибо.

добавление

Я задал тот же вопрос на другом веб-сайте и получил ответ "Вы можете сделать эту часть ниже функции. Если вы передаете местоположение и заголовок в качестве параметра этой функции и повторяю, вы можете развернуть маркеры "

let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = mapView

, но я не совсем уверен, как узнать местоположение супермаркетов. Нужно ли использовать json или Google Place API или более? Чтобы реализовать свою идею, я полагаю, нужно получить широту и долготу. Я сейчас в замешательстве ....

...