首页 > 解决方案 > 如何使用swift在谷歌地图中制作自定义iconView?

问题描述

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

用于 iOS 的 google maps sdk 中带有静态标签的标记

标签: swiftgoogle-maps-sdk-ios

解决方案


If there is gonna be a lot of markers, I do not recommend using iconView because it makes UI so laggy, but here it goes:

Create a UIView file as "MarkerInfoView", which will be created as MarkerInfoView.xib

Then design your UI in there, add your imageView for your icon, then add other necessary views to complete your iconView. Also include marker in the design as an imageView. Because Im not 100% sure but I think you cant use both iconView and icon in google maps.

Then create a swift file called "MarkerInfoView.swift", go to MarkerInfoView.xib and select it's class as MarkerInfoView.

Then create another swift file, lets call it PlaceMarker, inside that file you will create a class which will conform to GMSMarker, then you will initialize your view to set it equal to iconView in PlaceMarker class. Lets do it as following:

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.

}
}

Then when you have your data and your googlemaps view in a ViewController you can set like:

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.

推荐阅读