OStack程序员社区-中国程序员成长平台

标题: iOS Google map 以编程方式选择注释 [Swift] [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:49
标题: iOS Google map 以编程方式选择注释 [Swift]

我有一个方法可以将 标记 放置到我有自定义标注的 map 上。问题是用户需要单击此标记才能将其显示出来。是否可以从 Google Map 的 API 调用一个方法,该方法可以选择 注释以编程方式调出标注?

我知道对于 Apple map ,Objective C 中有 [mapView selectAnnotation:annotationName animated:YES];self.mapView.selectAnnotation(selectedAnnotation, animated: true) swift

我已阅读 How to select a map pin programmatically但这似乎对 Google map 没有任何帮助。

仅供引用 - 这是一个 Swift 项目



Best Answer-推荐答案


您需要使用 GMSMapView selectedMarker 属性,还需要将相机移动到新的 selectedMarker 位置

完整代码示例

import UIKit
import GoogleMaps

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

class TapViewController: UIViewController, GMSMapViewDelegate {
    let markers = [
        MarkerStruct(name: "Food Hut 1", lat: 52.649030, long: 1.174155),
        MarkerStruct(name: "Foot Hut 2", lat: 35.654154, long: 1.174185),
        MarkerStruct(name: "Foot Hut 3", lat: 22.654154, long: 1.174185),
        MarkerStruct(name: "Foot Hut 4", lat: 50.654154, long: 1.174185),
        ]

    var mapView : GMSMapView? = nil

    var mapMarkers : [GMSMarker] = []
    var timer : Timer? = nil

    override func viewDidLoad() {
        super.viewDidLoad()

        let camera = GMSCameraPosition.camera(withLatitude: 52.649030, longitude: 1.174155, zoom: 14)
        mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)

        mapView?.delegate = self
        self.view = mapView

        for marker in markers {
            let position = CLLocationCoordinate2D(latitude: marker.lat, longitude: marker.long)
            let locationmarker = GMSMarker(position: position)
            locationmarker.title = marker.name
            locationmarker.map = mapView
            mapMarkers.append(locationmarker)
        }

        timer = Timer.scheduledTimer(timeInterval: 15, target: self, selector:  #selector(self.selectRandomMarker), userInfo: nil, repeats: true)

    }

    //Selecting random marker
    func selectRandomMarker(){
        let randomIndex = arc4random_uniform(UInt32(self.mapMarkers.count))
        self.mapView?.selectedMarker = self.mapMarkers[Int(randomIndex)]
        self.mapView?.animate(toLocation: (self.mapView?.selectedMarker!.position)!)
    }

}

关于iOS Google map 以编程方式选择注释 [Swift],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49156832/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4