gpt4 book ai didi

ios - 使用 Google iOS SDK 创建多个标记

转载 作者:搜寻专家 更新时间:2023-10-30 22:22:17 25 4
gpt4 key购买 nike

我是 Swift 的新手。我很高兴在 Google map 上得到 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 个不同纬度和经度的标记。

我可能只复制这个 block 51 次,但是有没有办法优化这段代码?

最佳答案

你应该像这样创建一个结构:

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
}

}

关于ios - 使用 Google iOS SDK 创建多个标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39676823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com