我对使用 Xcode 和 SwiftUI 进行编程相当陌生,并且无法将 Google map 集成到 SwiftUI 项目中。
我将所有正确的 API key 添加到我的 AppDelegate.swift 文件中,并创建了一个名为 GoogMapView 的 View ,我试图用它来显示 Google map 的实例。这是我在文件 GoogMapView 中的代码:
import SwiftUI
import MapKit
import UIKit
import GoogleMaps
import GooglePlaces
struct GoogMapView : UIViewRepresentable {
func makeUIView(context: Context) -> GMSMapView {
GMSMapView(frame: .zero)
}
func updateUIView(_ view: GMSMapView, context: Context) {
let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
view = mapView
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = mapView
}
我在“view = mapView”处不断收到错误,但我尝试的一切都失败了。知道如何设置它以便我可以在主视图中调用它吗?
最佳答案
我也是一个新的 iOS 开发者。我正在研究同样的事情,偶然发现了你的问题。由于我是 iOS 新手,我不能声称它遵循所有正确的约定,但此代码可以在基本级别使用 SwiftUI 在模拟器上显示 map 。解决方案基于您的代码和 Matteo 的观察。
import SwiftUI
import UIKit
import GoogleMaps
struct ContentView: UIViewRepresentable {
let marker : GMSMarker = GMSMarker()
/// Creates a `UIView` instance to be presented.
func makeUIView(context: Self.Context) -> GMSMapView {
// Create a GMSCameraPosition that tells the map to display the
// coordinate -33.86,151.20 at zoom level 6.
let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
return mapView
}
/// Updates the presented `UIView` (and coordinator) to the latest
/// configuration.
func updateUIView(_ mapView: GMSMapView, context: Self.Context) {
// Creates a marker in the center of the map.
marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = mapView
}
}
关于xcode - 谷歌地图集成到 SwiftUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58194015/