我为哥本哈根骑自行车的人开发了一个应用程序,但遇到了一些问题。 当 Google map 在手机上不可用时,该应用需要打开 Apple map 。
代码是这样的
// OUTLETS!
@IBOutlet weak var googleMapsView: GMSMapView!
// VARIABLES!
var locationManager = CLLocationManager()
var M1: GMSMarker!
var M2: GMSMarker!
//Marker funtioncs
var markerFunctions: [GMSMarker: (() -> Void)]!
override func viewDidLoad() {
super.viewDidLoad()
// GET LOCATION WHILE USING APP
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
initGoogleMaps()
}
// START GOOGLE MAPS!
func initGoogleMaps() {
// MARKERS
M1 = GMSMarker()
M1.position = CLLocationCoordinate2D(latitude: 55.65208178045790, longitude: 12.527047696518300)
M1.title = "Sjælør St."
M1.snippet = "Press for navigation"
M1.map = self.googleMapsView
M2 = GMSMarker()
M2.position = CLLocationCoordinate2D(latitude: 55.67530850095370, longitude: 12.583165039072400)
M2.title = "Børsen (Slotsholmsgade)"
M2.snippet = "Press for navigation"
M2.map = self.googleMapsView
// Marker functions
markerFunctions = [
M1: { UIApplication.shared.open(NSURL(string: "comgooglemaps-x-callback://" +
"?daddr=55.65208178045790,12.527047696518300&directionsmode=bicycling&zoom=17")! as URL)},
M2: { UIApplication.shared.open(NSURL(string: "comgooglemaps-x-callback://" +
"?daddr=55.67530850095370,12.583165039072400&directionsmode=bicycling&zoom=17")! as URL)},
当点击信息窗口时,谷歌地图的导航需要出现(它有效)。但是,如果 Google map 应用程序不可用,我该如何重新编写“标记功能”以使其改为打开 Apple map ?
最佳答案
为此,您需要检查是否安装了 Google map 。这可以很容易地完成:
func openMaps(latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
let googleMapsInstalled = UIApplication.shared.canOpenURL(URL(string: "comgooglemaps://")!)
if googleMapsInstalled {
UIApplication.shared.open(URL(string: "comgooglemaps-x-callback://" +
"?daddr=\(latitude),\(longitude)&directionsmode=bicycling&zoom=17")!)
} else {
let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.openInMaps(launchOptions: nil)
}
}
出于隐私原因,默认情况下 iOS 不允许检查 URL 是否可以打开。您需要在您的应用中将 comgooglemaps://
列入白名单检查。为此,将其添加到您的应用 Info.plist
:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>comgooglemaps</string>
</array>
如果您已正确完成此操作,openMaps(latitude:, logitude:)
将打开 Google map (如果已安装),否则将打开 Apple map 。只需更改闭包(“标记函数”)即可调用新方法。
当然,您还需要import MapKit
才能正常工作。
关于ios - Swift:未安装谷歌地图时应用程序需要打开苹果 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42279122/