【问题标题】:iOS Google map programmatically select annotation [Swift]iOS Google 地图以编程方式选择注释 [Swift]
【发布时间】:2023-04-11 08:53:05
【问题描述】:

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

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

我已经阅读了How to select a map pin programmatically,但这似乎对谷歌地图没有任何帮助。

仅供参考 - 这是一个 Swift 项目

【问题讨论】:

  • 我认为您可以在self.mapView?.selectedMarkerproperty 中指定一个标记,例如self.mapView?.selectedMarker = yourDesiredMarker 我会测试它
  • 是的,我需要创建一个array: [GMSMarker]。初始化时将标记添加到数组中。然后在索引 0 处使用selectMarker。需要确保每次在创建标记之前清除数组和映射。 @ReinierMelian

标签: ios swift google-maps google-api


【解决方案1】:

您需要使用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)!)
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    相关资源
    最近更新 更多