问题
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 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:
Step 1: Create a model "Restaurants" in which create two variables latitude and longitude.
Step 2: Create an array of model like this
var datasource : [Restaurants] = Array()
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))
}
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
}
Make sure that you create an outlet of MapView.
来源:https://stackoverflow.com/questions/43767500/place-multiple-markers-on-gmsmapview-swift