使用Google iOS SDK创建多个标记

时间:2016-09-24 13:24:40

标签: ios swift google-maps

我是斯威夫特的新手。我想在Google地图上获得2个标记:

import UIKit
import GoogleMaps

class ViewController: UIViewController {

    // You don't need to modify the default init(nibName:bundle:) method.

    override func loadView() {
        let camera = GMSCameraPosition.cameraWithLatitude(37.0902, longitude: -95.7129, zoom: 3.0)
        let mapView = GMSMapView.mapWithFrame(CGRect.zero, camera: camera)
        mapView.myLocationEnabled = true
        view = mapView

        let state_marker = GMSMarker()
        state_marker.position = CLLocationCoordinate2D(latitude: 61.370716, longitude: -152.404419)
        state_marker.title = "Alaska"
        state_marker.snippet = "Hey, this is Alaska"
        state_marker.map = mapView

        let state_marker1 = GMSMarker()
        state_marker1.position = CLLocationCoordinate2D(latitude: 32.806671, longitude: -86.791130)
        state_marker1.title = "Alabama"
        state_marker1.snippet = "Hey, this is Alabama"
        state_marker1.map = mapView

    }
}

我需要为不同的纬度和经度添加51个标记,以用于具有不同标题和摘要的每个州。

我可以将这个块复制51次,但有没有办法优化这段代码?

1 个答案:

答案 0 :(得分:16)

您应该创建一个这样的结构:

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

然后在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...
]

现在你可以循环遍历数组,在每次迭代中添加标记:

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
}

您可能还想添加一个字典,该字典将状态名称存储为键,并将相应的GMSMarker存储为值。这样,您可以稍后修改标记。

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
    }

}