在GMSMapView Swift上放置多个标记 [英] Place multiple markers on GMSMapView Swift

查看:88
本文介绍了在GMSMapView Swift上放置多个标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个使用Google Places API搜索用户位置附近的所有餐馆的应用程序.这样我就可以成功检索餐厅的坐标(纬度,经度),然后向每个位置添加一个标记或一个圆圈,但是我无法做到这一点.我可以将标记或圆圈添加到一个位置,但是当我尝试添加到多个位置时,它不会显示标记或圆圈. 这是我写的代码

i was making an application that uses google places api to search for all the restaurants nearby user's location. So i can successfully retrieve the restaurants coordinates(lat, lng) and then i want to add a marker or a circle to each place but i am unable to do that. I can add a marker or circle to one location but when i try to add to multiple locations it does not show markers or circles. Here is the code i wrote

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的值,并且它打印了所有值.但是圈子没有出现在地图上.我怎样才能做到这一点.请帮助我解决这个问题.

I am sure the array contains all the locations and i print the value of increment i in the loop and it prints all values. But the circles don't show up on the map. How can i do that. Please help me with this problem.

这是我编写的所有代码.

Here is all the code i have written.

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.
}
*/

}

请务必让我知道问题的原因以及如何解决此问题.谢谢.

Please do let me know the cause of the problem and how should i remove this problem. Thanks.

推荐答案

步骤1: 创建一个模型"Restaurants",在其中创建两个变量纬度和经度.

Step 1: Create a model "Restaurants" in which create two variables latitude and longitude.

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

Step 2: Create an array of model like this

var datasource : [Restaurants] = Array()

第3步: 当您访问Web时,服务就会到达,像这样在模型类中添加纬度和经度.第一个例子是我们在NSArray中的响应.

Step 3: When you hit web the service hits, add the latitude and longitude in model class like this. fir example our response in NSArray.

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

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

Step 4: After mapping in model. Now add the code which place multiple marker in 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的出口.

Make sure that you create an outlet of MapView.

这篇关于在GMSMapView Swift上放置多个标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆