Google Maps API 是一组允许开发者在应用中嵌入 Google 地图服务的编程接口。在 iOS 应用中集成 Google Maps 可以实现地图显示、位置标记、路线规划、地点搜索等功能。
首先需要获取 Google Maps API 密钥:
使用 CocoaPods 添加依赖:
pod 'GoogleMaps'
pod 'GooglePlaces' # 如果需要地点搜索功能
然后运行 pod install
在 AppDelegate.swift
中配置:
import GoogleMaps
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
GMSServices.provideAPIKey("YOUR_API_KEY")
return true
}
import UIKit
import GoogleMaps
class MapViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 设置地图初始位置和缩放级别
let camera = GMSCameraPosition.camera(withLatitude: 37.7749, longitude: -122.4194, zoom: 12.0)
let mapView = GMSMapView.map(withFrame: view.bounds, camera: camera)
view.addSubview(mapView)
// 添加标记
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194)
marker.title = "San Francisco"
marker.snippet = "California"
marker.map = mapView
}
}
let mapView = GMSMapView.map(withFrame: view.bounds, camera: camera)
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
let path = GMSMutablePath()
path.add(CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194))
path.add(CLLocationCoordinate2D(latitude: 34.0522, longitude: -118.2437))
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 5.0
polyline.map = mapView
let placesClient = GMSPlacesClient.shared()
placesClient.findPlaceLikelihoodsFromCurrentLocation(withPlaceFields: [.name, .coordinate], callback: { (placeLikelihoods, error) in
guard error == nil else {
print("Error: \(error!.localizedDescription)")
return
}
for likelihood in placeLikelihoods! {
let place = likelihood.place
print("Name: \(place.name ?? "Unknown")")
print("Coordinate: \(place.coordinate)")
}
})
没有搜到相关的文章