如何使用 swift 在谷歌地图中制作自定义 iconView?

Eri*_*ick 2 google-maps-sdk-ios swift

我需要做这样的事情 带有标记和标签的地图

iOS 版谷歌地图 sdk 中带有静态标签的标记

emr*_*pun 7

如果有很多标记,我不建议使用 iconView,因为它会使 UI 变得很慢,但这里是:

创建一个 UIView 文件作为“MarkerInfoView”,它将被创建为MarkerInfoView.xib

然后在那里设计你的 UI,为你的图标添加你的 imageView,然后添加其他必要的视图来完成你的 iconView。还在设计中包含标记作为 imageView。因为我不是 100% 确定,但我认为你不能在谷歌地图中同时使用 iconView 和 icon。

然后创建一个名为“MarkerInfoView.swift”的 swift 文件,转到MarkerInfoView.xib并选择其类为MarkerInfoView.

然后创建另一个 swift 文件,我们称之为PlaceMarker,在该文件中您将创建一个符合 GMSMarker 的类,然后您将初始化您的视图以将其设置为等于类iconView中的值PlaceMarker。让我们按如下方式进行:

class PlaceMarker: GMSMarker {
//Initialize with lat and long, then set position equal to the coordinate.
// 'position' comes from inheriting from GMSMarker, which is google marker.
init(latitude: Double, longitude: Double, distance: Double, placeName: String) {
    super.init()
    if let lat: CLLocationDegrees = latitude,
        let long: CLLocationDegrees = longitude {
        let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
        position = coordinate
    }

    let view = Bundle.main.loadNibNamed("MarkerInfoView", owner: nil, options: nil)?.first as! MarkerInfoView
    // you can set your view's properties here with data you are sending in initializer.
    // Remember if you need to pass more than just latitude and longitude, you need
    // to update initializer.
    // lets say you created 2 outlet as placeNameLabel, and distanceLabel, you can set
    // them like following:
    view.placeNameLabel.text = placeName
    view.distanceLabel.text = distance

    // Once your view is ready set iconView property coming from inheriting to
    // your view as following:

    iconView = view
    appearAnimation = .pop //not necessarily but looks nice.

}
}
Run Code Online (Sandbox Code Playgroud)

然后,当您拥有数据和谷歌地图视图时,ViewController您可以设置如下:

let latitude = 101.432432 //arbitrary, should come from your source
let longitude = 34.432124 
let distance = 4
let placeName = "My place".
let marker = PlaceMarker(latitude: latitude, longitude: longitude, distance: distance, placeName: placeName)
marker.map = self.mapView // your google maps set your marker's map to it.
Run Code Online (Sandbox Code Playgroud)