Create multiple markers using Google iOS SDK

前端 未结 1 756
独厮守ぢ
独厮守ぢ 2020-12-30 15:35

I am a newbie in Swift. I was ale to get 2 markers on Google Maps:

import UIKit
import GoogleMaps

class ViewController: UIViewController {

    // You don\'         


        
相关标签:
1条回答
  • 2020-12-30 15:58

    You should create a struct like this:

    struct State {
        let name: String
        let long: CLLocationDegrees
        let lat: CLLocationDegrees
    }
    

    Then create an array of this struct in your VC:

    let states = [
        State(name: "Alaska", long: -152.404419, lat: 61.370716),
        State(name: "Alabama", long: -86.791130, lat: 32.806671),
        // the other 51 states here...
    ]
    

    Now you can just loop through the array, adding markers in each iteration:

    for state in states {
        let state_marker = GMSMarker()
        state_marker.position = CLLocationCoordinate2D(latitude: state.lat, longitude: state.long)
        state_marker.title = state.name
        state_marker.snippet = "Hey, this is \(state.name)"
        state_marker.map = mapView
    }
    

    You might also want to add a dictionary that stores the names of the states as keys and the corresponding GMSMarker as value. This way, you can modify the markers later.

    var markerDict: [String: GMSMarker] = [:]
    
    override func loadView() {
    
        for state in states {
            let state_marker = GMSMarker()
            state_marker.position = CLLocationCoordinate2D(latitude: state.lat, longitude: state.long)
            state_marker.title = state.name
            state_marker.snippet = "Hey, this is \(state.name)"
            state_marker.map = mapView
            markerDict[state.name] = state_marker
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题