【问题标题】:Place multiple markers on GMSMapView Swift在 GMSMapView Swift 上放置多个标记
【发布时间】:2017-05-03 18:27:00
【问题描述】:

我正在制作一个使用 google places api 来搜索附近用户位置的所有餐馆的应用程序。所以我可以成功检索餐厅坐标(lat,lng),然后我想在每个地方添加一个标记或一个圆圈,但我无法做到这一点。我可以将标记或圆圈添加到一个位置,但是当我尝试添加到多个位置时,它不会显示标记或圆圈。 这是我写的代码

func setUpMarkersForLibraries(locations: [CLLocationCoordinate2D]){
    print("Setting up Markers")
    var i = 0
    for l in locations{
        let circleCenter = l
        let circ = GMSCircle(position: circleCenter, radius: 30)

        circ.fillColor = UIColor(red: 0, green: 0.89, blue: 0, alpha: 0.8)
        circ.strokeColor = .black
        circ.strokeWidth = 5
        circ.title = "\(i)"
        //print("\(i)")
        i += 1
        circ.map = mapView
    }
}

我确定数组包含所有位置,我在循环中打印增量 i 的值,它会打印所有值。但是这些圆圈没有出现在地图上。我怎样才能做到这一点。请帮我解决这个问题。

这是我写的所有代码。

import UIKit
import GoogleMaps

class MapsViewController: UIViewController, CLLocationManagerDelegate 
{

var mapSet = false
var allLibraries = [CLLocationCoordinate2D]()
var loaded = false
var mapView: GMSMapView?
var locationManager: CLLocationManager = CLLocationManager()
var camera = GMSCameraPosition.camera(withLatitude: 0, longitude: 0, zoom: 12)

override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
    mapView = GMSMapView(frame: CGRect.zero)
    view = mapView
    loadNearByLibraries()
    //mapView?.animate(to: camera)
    //mapView.showsUserLocation = true
    //setUpMap()
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


private func setUpMap(location: CLLocation){

    camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude, longitude: location.coordinate.longitude, zoom: 15)
    let updateCamera = GMSCameraUpdate.setCamera(camera)
    self.mapView?.animate(with: updateCamera)
    let marker = GMSMarker()
    marker.position = camera.target
    marker.title = "My Place"
    marker.map = self.mapView

  }


func loadNearByLibraries(){
    let urlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&type=restaurant&keyword=cruise&key=AIzaSyBIDJ50ak-caS3M-6nSVbxdN_SmssAlTRI"
    let theUrl = URL(string: urlString)
    if let url = theUrl{
        print("Search Called")
        var urlRequest = URLRequest(url: url)
        urlRequest.httpMethod = "GET"
        print("URL : " + url.absoluteString)
        let task = URLSession.shared.dataTask(with: urlRequest, completionHandler: {
            (data, response, error) in

            if response != nil{
                if let res = response as? HTTPURLResponse{
                    if(res.statusCode == 408)
                    {
                        MessageBox.Show(message: "Error : Request TimeOut", title: "Error", view: self)
                    }

                }
            }

            if error != nil{
                print("Error \(error?.localizedDescription)")
                MessageBox.Show(message: (error?.localizedDescription)!, title: "An error occurred", view: self)

            }
            else{
                print("Printing Json")
                self.processJson(data: data!)

            }
        })
        task.resume()
    }
}

func processJson(data: Data){
    allLibraries.removeAll()
    do{

        let jsonData  = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

        let locations = jsonData
        let results = jsonData["results"] as! NSArray
        for i in results{
            let item = i as! NSDictionary
            let geom = item["geometry"] as! NSDictionary
            let loc = geom["location"] as! NSDictionary

            let lat = loc["lat"] as! NSNumber
            let lng = loc["lng"] as! NSNumber
            if let l: NSNumber = lat, let ln: NSNumber = lng{
                var latitude = CLLocationDegrees(l.floatValue)
                var longitude = CLLocationDegrees(ln.floatValue)
                var cord = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
                allLibraries.append(cord)
            }
            //print(loc)

        }


    }catch let error as Error{
        print("Error : \(error.localizedDescription)")
    }
    loaded = true
    //setUpMarkersForLibraries(locations: allLibraries)
    print("All Libraries : \(allLibraries.count)")
}


func setUpMarkersForLibraries(locations: [CLLocationCoordinate2D]){
    print("Setting up Markers")
    var i = 0
    for l in locations{
        let circleCenter = l
        let circ = GMSCircle(position: circleCenter, radius: 30)

        circ.fillColor = UIColor(red: 0, green: 0.89, blue: 0, alpha: 0.8)
        circ.strokeColor = .black
        circ.strokeWidth = 5
        circ.title = "\(i)"
        //print("\(i)")
        i += 1
        circ.map = mapView

    }
}


func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let lastLocation: CLLocation = locations[locations.count - 1]
    if( mapSet == false)
    {
        setUpMap(location: lastLocation)
        mapSet = true
    }
    if (loaded == true)
    {
        setUpMarkersForLibraries(locations: allLibraries)
        loaded = false
    }
    //print("Location Updated")
}


/*
// 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.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

请让我知道问题的原因以及我应该如何解决这个问题。谢谢。

【问题讨论】:

    标签: ios swift google-places-api google-maps-sdk-ios


    【解决方案1】:

    第 1 步: 创建一个模型“Restaurants”,其中创建两个变量纬度和经度。

    第 2 步: 像这样创建一个模型数组

    var datasource : [Restaurants] = Array()
    

    第 3 步: 当你点击网络服务点击时,像这样在模型类中添加纬度和经度。以我们在 NSArray 中的响应为例。

    let restaurantslist = result as NSArray
    for restaurantsListIteration in restaurantslist {
    self.datasource.append(Restaurants(value: restaurantsListIteration))
    }
    

    第 4 步: 在模型中映射后。现在添加在 mapView 中放置多个标记的代码。

     for  (index,restaurantsPin) in self.datasource.enumerated() {
                let latDouble = Double(restaurantsPin.latitude!)
                let longDouble = Double(restaurantsPin.longitude!)
                let marker = GMSMarker()
                marker.map = self.viewMap
                marker.iconView = UIImageView(image: #imageLiteral(resourceName: "pin"))
                marker.iconView?.tag = index
                marker.position = CLLocationCoordinate2DMake(latDouble!,longDouble!)
                self.view.addSubview(self.viewMap)
                self.viewMap.delegate = self
      }
    

    确保创建 MapView 的 outlet。

    【讨论】:

      猜你喜欢
      • 2016-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多