Google Maps integration into SwiftUI
我刚刚开始使用Xcode和SwiftUI编程,但是在将Google Maps集成到SwiftUI项目时遇到了麻烦。
我在AppDelegate.swift文件中添加了所有正确的API密钥,并创建了一个名为GoogMapView的视图,我试图使用该视图来显示Google地图的实例。 这是我在文件GoogMapView中的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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在模拟器上显示地图。 解决方案基于您的代码和Matteo的观察。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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 } } |