在GMSMapView Swift上放置多个标记

时间:2017-05-03 18:27:00

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

我正在制作一个使用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
    }
}

我确定数组包含所有位置,并且我在循环中打印increment 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.
}
*/

}

请告诉我问题的原因以及如何解决此问题。感谢。

1 个答案:

答案 0 :(得分:2)

第1步: 创建一个模型"餐厅"其中创建两个变量纬度和经度。

第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的插座。