【发布时间】:2015-11-09 11:11:09
【问题描述】:
我在互联网上阅读,但找不到合法的答案。当用户单击按钮以显示路线时,我需要打开 Google 地图。起点和终点必须自动填写。
如何在 Swift 中实现这一点?
如果有人有解决方案,请提供示例代码。起点始终是用户的当前位置。
【问题讨论】:
标签: ios swift google-maps
我在互联网上阅读,但找不到合法的答案。当用户单击按钮以显示路线时,我需要打开 Google 地图。起点和终点必须自动填写。
如何在 Swift 中实现这一点?
如果有人有解决方案,请提供示例代码。起点始终是用户的当前位置。
【问题讨论】:
标签: ios swift google-maps
好的,我自己找到了答案。
如果您想显示从用户当前位置出发的路线,请将字段 saddr 留空,并在字段 daddr 中输入目的地坐标。
我就是这样做的
if (UIApplication.sharedApplication().canOpenURL(NSURL(string:"comgooglemaps://")!)) {
UIApplication.sharedApplication().openURL(NSURL(string:
"comgooglemaps://?saddr=&daddr=\(place.latitude),\(place.longitude)&directionsmode=driving")!)
} else {
NSLog("Can't use comgooglemaps://");
}
}
如有任何进一步的疑问,您可以参考此链接Google Map URL Scheme
【讨论】:
Swift 5 - 代码
func openGoogleMap() {
guard let lat = booking?.booking?.pickup_lat, let latDouble = Double(lat) else {Toast.show(message: StringMessages.CurrentLocNotRight);return }
guard let long = booking?.booking?.pickup_long, let longDouble = Double(long) else {Toast.show(message: StringMessages.CurrentLocNotRight);return }
if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!)) { //if phone has an app
if let url = URL(string: "comgooglemaps-x-callback://?saddr=&daddr=\(latDouble),\(longDouble)&directionsmode=driving") {
UIApplication.shared.open(url, options: [:])
}}
else {
//Open in browser
if let urlDestination = URL.init(string: "https://www.google.co.in/maps/dir/?saddr=&daddr=\(latDouble),\(longDouble)&directionsmode=driving") {
UIApplication.shared.open(urlDestination)
}
}
}
别忘了在 info.plist 中写下这个
<key>LSApplicationQueriesSchemes</key>
<array>
<string>comgooglemaps</string>
<string>comgooglemaps-x-callback</string>
</array>
【讨论】:
答案已经存在,但在旧版本的 Swift 中
在 Swift 3 中
//Working in Swift new versions.
if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!))
{
UIApplication.shared.openURL(NSURL(string:
"comgooglemaps://?saddr=&daddr=\(Float(latitude!)),\(Float(longitude!))&directionsmode=driving")! as URL)
} else
{
NSLog("Can't use com.google.maps://");
}
【讨论】:
@IBAction func NavigationTrackerPressedPressed(_ sender: UIButton){
if let UrlNavigation = URL.init(string: "comgooglemaps://") {
if UIApplication.shared.canOpenURL(UrlNavigation){
if self.destinationLocation?.longitude != nil && self.destinationLocation?.latitude != nil {
let lat = (self.destinationLocation?.latitude)!
let longi = (self.destinationLocation?.longitude)!
if let urlDestination = URL.init(string: "comgooglemaps://?saddr=&daddr=\(lat),\(longi)&directionsmode=driving") {
UIApplication.shared.openURL(urlDestination)
}
}
}
else {
NSLog("Can't use comgooglemaps://");
self.openTrackerInBrowser()
}
}
else
{
NSLog("Can't use comgooglemaps://");
self.openTrackerInBrowser()
}
}
func openTrackerInBrowser(){
if self.destinationLocation?.longitude != nil && self.destinationLocation?.latitude != nil {
let lat = (self.destinationLocation?.latitude)!
let longi = (self.destinationLocation?.longitude)!
if let urlDestination = URL.init(string: "https://www.google.co.in/maps/dir/?saddr=&daddr=\(lat),\(longi)&directionsmode=driving") {
UIApplication.shared.openURL(urlDestination)
}
}
}
【讨论】:
这里是 Swift 3 更新
首先,您需要在 info.plist 中将两个项目添加到LSApplicationQueriesSchemes。
然后你就可以使用这个功能在谷歌地图上加载地址了。
let primaryContactFullAddress = "No 28/A, Kadalana, Moratuwa, Sri Lanka"
@IBAction func showLocaionOnMaps(_ sender: Any) {
let testURL: NSURL = NSURL(string: "comgooglemaps-x-callback://")!
if UIApplication.shared.canOpenURL(testURL as URL) {
if let address = primaryContactFullAddress.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
let directionsRequest: String = "comgooglemaps-x-callback://" + "?daddr=\(address)" + "&x-success=sourceapp://?resume=true&x-source=AirApp"
let directionsURL: NSURL = NSURL(string: directionsRequest)!
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(directionsURL as URL)) {
application.open(directionsURL as URL, options: [:], completionHandler: nil)
}
}
} else {
NSLog("Can't use comgooglemaps-x-callback:// on this device.")
}
}
【讨论】:
Swift 4 工作代码
if let url = URL(string: "comgooglemaps://?saddr=&daddr=\(location.coordinate.latitude),\(location.coordinate.longitude)&directionsmode=driving") {
UIApplication.shared.open(url, options: [:])
}
此代码对我有用。而且我没有插入
* LSApplicationQueriesSchemes
如果你使用模拟器是看不到结果的。不要忘记在电话上处理您的项目。
【讨论】:
1) 方法:你可以传递唯一的目的地地址当前地址将被谷歌地图应用程序自动获取。
let strLat : String = "23.035007"
let strLong : String = "72.529324"
override func viewDidLoad() {
super.viewDidLoad()
if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!)) {
UIApplication.shared.openURL(URL(string:"comgooglemaps://?saddr=&daddr=\(strLat),\(strLong)&directionsmode=driving")!)
}
else {
print("Can't use comgooglemaps://");
}
}
2) 您可以同时传递起始地址和目标地址
let strLat : String = "23.035007"
let strLong : String = "72.529324"
let strLat1 : String = "23.033331"
let strLong2 : String = "72.524510"
override func viewDidLoad() {
super.viewDidLoad()
if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!)) {
UIApplication.shared.openURL(URL(string:"comgooglemaps://?saddr=\(strLat),\(strLong)&daddr=\(strLat1),\(strLong2)&directionsmode=driving&zoom=14&views=traffic")!)
}
else {
print("Can't use comgooglemaps://");
}
}
【讨论】:
我希望用户可以通过浏览器打开谷歌地图(仅当用户没有谷歌地图应用时才有效) Google 提供了该here 的文档。 从 iOS 9 开始,您必须设置一个方案。这个你会找到here。
对我来说,谷歌解决方案不起作用。也许您更聪明并找到了解决方案(请发布!)。
反正我打了一个简单的网络电话:
let lat = 37.7
let lon = -122.4
if (UIApplication.sharedApplication().canOpenURL(NSURL(string:"https://maps.google.com")!))
{
UIApplication.sharedApplication().openURL(NSURL(string:
"https://maps.google.com/?q=@\(lat),\(lon)")!)
}
这可以用作 sumeshs 答案的一种后备。
【讨论】:
let lat = self.upcomingListArr[indexPath.item].latitude!
let long = self.upcomingListArr[indexPath.item].longitude!
if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {
UIApplication.shared.openURL(NSURL(string:
"comgooglemaps://?saddr=&daddr=\(String(describing: lat)),\(String(describing: long))")! as URL)
} else {
UIApplication.shared.openURL(NSURL(string:
"https://www.google.co.in/maps/dir/?saddr=&daddr=\(String(describing: lat)),\(String(describing: long))")! as URL)
}
【讨论】:
您可以为 URL 创建小型构建器,这会将您重定向到 GoogleMaps
/*
add to InfoPlist:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>comgooglemaps</string>
<string>comgooglemaps-x-callback</string>
</array>
*/
final public class GoogleMapsURIConstructor {
public enum NavigationType: String {
case driving
case transit
case walking
}
public class func prepareURIFor(latitude lat: Double,
longitude long: Double,
fromLatitude fromLat: Double? = nil,
fromLongitude fromLong: Double? = nil,
navigation navigateBy: NavigationType) -> URL? {
if let googleMapsRedirect = URL(string: "comgooglemaps://"),
UIApplication.shared.canOpenURL(googleMapsRedirect) {
if let fromLat = fromLat,
let fromLong = fromLong {
let urlDestination = URL(string: "comgooglemaps-x-callback://?saddr=\(fromLat),\(fromLong)?saddr=&daddr=\(lat),\(long)&directionsmode=\(navigateBy.rawValue)")
return urlDestination
} else {
let urlDestination = URL(string: "comgooglemaps-x-callback://?daddr=\(lat),\(long)&directionsmode=\(navigateBy.rawValue)")
return urlDestination
}
} else {
if let fromLat = fromLat,
let fromLong = fromLong {
let urlDestination = URL(string: "https://www.google.co.in/maps/dir/?saddr=\(fromLat),\(fromLong)&daddr=\(lat),\(long)&directionsmode=\(navigateBy.rawValue)")
return urlDestination
} else {
let urlDestination = URL(string: "https://www.google.co.in/maps/dir/?saddr=&daddr=\(lat),\(long)&directionsmode=\(navigateBy.rawValue)")
return urlDestination
}
}
}
}
用法:
let uri = GoogleMapsURIConstructor.prepareURIFor(latitude: lat,
longitude: long,
fromLatitude: userLatitude,
fromLongitude: userLongitude,
navigation: .driving)
UIApplication.shared.open(uri, options: [: ], completionHandler: nil)
结果:
【讨论】:
首先,谢谢你们的回答。但是当我工作时,我没有找到适合我的工作答案。结果我用两种情况编写了工作代码:当用户有谷歌地图应用程序时,如果没有。 这是我的代码版本。 Xcode 10,斯威夫特 4.2。希望它会有所帮助。
第 1 步:找到您的 info.plist 并打开为 -> 源代码
第 2 步:在<dict> 和</dict> 之间添加这些行
第 3 步:在您的操作中添加此代码。不要忘记设置您的纬度和经度。
let latitude = 44.987781
let longitude = 88.987781
let appDomen: String = "comgooglemaps://"
let browserDomen: String = "https://www.google.co.in/maps/dir/"
let directionBody: String = "?saddr=&daddr=\(latitude),\(longitude)&directionsmode=driving"
// Make route with google maps application
if let appUrl = URL(string: appDomen), UIApplication.shared.canOpenURL(appUrl) {
guard let appFullPathUrl = URL(string: appDomen + directionBody) else { return }
UIApplication.shared.openURL(appFullPathUrl)
// If user don't have an application make route in browser
} else if let browserUrl = URL(string: browserDomen), UIApplication.shared.canOpenURL(browserUrl) {
guard let browserFullPathUrl = URL(string: browserDomen + directionBody) else { return }
UIApplication.shared.openURL(browserFullPathUrl)
}
【讨论】:
如果没有安装谷歌地图应用,用苹果地图版本打开。
import Foundation
import CoreLocation
import UIKit
import MapKit
struct GoogleMapApp {
func openWithDirection(cordinate: CLLocationCoordinate2D, locationName: String) {
let hasGoogleMapApp = UIApplication.shared.canOpenURL(URL(string: "comgooglemaps://")!)
if hasGoogleMapApp {
let urlString = "comgooglemaps-x-callback://?saddr=&daddr=\(cordinate.latitude),\(cordinate.longitude)&directionsmode=driving"
if let url = URL(string: urlString) {
UIApplication.shared.open(url, options: [:])
}
} else {
// If google map not installed, open with Apple Map App
let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: cordinate, addressDictionary: nil))
mapItem.name = locationName
mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])
}
}
}
【讨论】:
// 我希望它能完美运行。
let googleURL = NSURL(string: "comgooglemaps://?q=")
if(UIApplication.shared.canOpenURL(googleURL! as URL)) {
UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=\(DEVICE_LAT),\(DEVICE_LONG)&daddr=\(addressLat),\(addressLng)&directionsmode=driving")!, options: [:], completionHandler: nil)
}
//同样根据附图从info.plist设置权限。
【讨论】:
我们可以用这个方法打开谷歌地图。如果没有安装谷歌地图,它将重定向到浏览器。
func redirectToGoogleMap(coordinates : String) {
if let url = URL(string: "comgooglemaps://?saddr=&daddr=\(coordinates)&directionsmode=driving"),
UIApplication.shared.canOpenURL(url) {
print("comgoogle maps worked")
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler:nil)
} else {
UIApplication.shared.openURL(url)
}
} else{
if let url = URL(string: "https://www.google.co.in/maps/dir/?saddr=&daddr=\(coordinates)&directionsmode=driving"),
UIApplication.shared.canOpenURL(url) {
print("google com maps worked")
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler:nil)
} else {
UIApplication.shared.openURL(url)
}
}else{
kSweetAlert.showAlert(CommonMethods.setLangText("oops"), subTitle: "Oops! Could not open google maps", style: AlertStyle.error)
}
}
}`
【讨论】:
SWIFT 5.1(为我工作)
// Destination Address (Lat/Long)
let place = business?.businessAddresse
// Google URL
let stringURL = "comgooglemaps://"
// Checking Nil
if !(place?.latitude == nil) || !(place?.longitude == nil) {
if UIApplication.shared.canOpenURL(URL(string: stringURL)!) {
// If have Google Map App Installed
if let url = URL(string: "comgooglemaps://?saddr=&daddr=\(place?.latitude ?? 0.0),\(place?.longitude ?? 0.0)&directionsmode=driving") {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
} else {
// If have no Google Map App (Run Browser Instead)
if let destinationURL = URL(string: "https://www.google.co.in/maps/dir/?saddr=&daddr=\(place?.latitude ?? 0.0),\(place?.longitude ?? 0.0)&directionsmode=driving") {
UIApplication.shared.open(destinationURL, options: [:], completionHandler: nil)
}
}
} else {
// Show Alert When No Location Found
self.delegate?.noDirectionError(title: "Error", message: "There's no direction available for this restaurant")
}
注意:此代码仅适用于 iOS 11 或更高版本,希望对你们也有帮助,加油。
【讨论】:
在 Swift 4 中:
if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {
UIApplication.shared.open((NSURL(string:
"comgooglemaps://?saddr=&daddr=\(trashDictionarySorted[indexPath.section][0])&directionsmode=driving")! as URL), options: [:], completionHandler: nil)
} else {
NSLog("Can't use comgooglemaps://");
}
}
【讨论】:
答案已经存在,但在旧版本的 Swift 中,如果您的 iPhone 没有安装 Google Map Application,此代码可以在浏览器中打开 Google Map。
在 Swift 4 中
import MapKit
func openGoogleDirectionMap(_ destinationLat: String, _ destinationLng: String) {
let LocationManager = CLLocationManager()
if let myLat = LocationManager.location?.coordinate.latitude, let myLng = LocationManager.location?.coordinate.longitude {
if let tempURL = URL(string: "comgooglemaps://?saddr=&daddr=\(destinationLat),\(destinationLng)&directionsmode=driving") {
UIApplication.shared.open(tempURL, options: [:], completionHandler: { (isSuccess) in
if !isSuccess {
if UIApplication.shared.canOpenURL(URL(string: "https://www.google.co.th/maps/dir///")!) {
UIApplication.shared.open(URL(string: "https://www.google.co.th/maps/dir/\(myLat),\(myLng)/\(destinationLat),\(destinationLng)/")!, options: [:], completionHandler: nil)
} else {
print("Can't open URL.")
}
}
})
} else {
print("Can't open GoogleMap Application.")
}
} else {
print("Prease allow permission.")
}
}
【讨论】:
func openTrackerInBrowser(lat: String, long: String, dlat: String, dlong: String){
if let urlDestination = URL.init(string: "https://www.google.co.in/maps/dir/?saddr=\(lat),\(long)&daddr=\(dlat),\(dlong)&directionsmode=driving") {
UIApplication.shared.open(urlDestination, options: [:], completionHandler: nil)
}
}
【讨论】:
这是在苹果和谷歌地图之间选择导航应用程序的简单解决方案(如果已安装,否则系统将导航到默认的苹果地图)。
在您的项目中添加这个 OpenMaps 类。
class OpenMaps {
// Presenting Action Sheet with Map Options Like Google And Apple Maps.
/// - Parameter coordinate: coordinate of destination
static func presentActionSheetwithMapOption(coordinate: CLLocationCoordinate2D) {
let latitude = coordinate.latitude
let longitude = coordinate.longitude
// Google MAP URL
let googleURL = "comgooglemaps://?daddr=\(latitude),\(longitude)&directionsmode=driving"
let googleItem = ("Google Maps", URL(string:googleURL)!)
// Apple MAP URL
let appleURL = "maps://?daddr=\(latitude),\(longitude)"
var installedNavigationApps = [("Apple Maps", URL(string:appleURL)!)]
if UIApplication.shared.canOpenURL(googleItem.1) {
installedNavigationApps.append(googleItem)
}
if installedNavigationApps.count == 1 {
if let app = installedNavigationApps.first {
self.openMap(app: app)
}
return
}
// If there are google map install in the device then System will ask choose map application between apple and google map.
let alert = UIAlertController(title: nil,
message: "Choose application",
preferredStyle: .actionSheet)
for app in installedNavigationApps {
let button = UIAlertAction(title: app.0,
style: .default, handler: { _ in
self.openMap(app: app)
})
alert.addAction(button)
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancel)
guard let vc = AlertViewManager.shared.getTopViewController() else {
debugPrint("Unable To open the action sheet for maps. Function: \(#function), Line: \(#line)")
return
}
vc.present(alert, animated: true)
}
// Open Selected Map
/// - Parameter app: Selected Map Application Details
private static func openMap(app: (String, URL)) {
guard UIApplication.shared.canOpenURL(app.1) else {
debugPrint("Unable to open the map.")
return
}
UIApplication.shared.open(app.1, options: [:], completionHandler: nil)
}
}
用法:
let coordinate = CLLocationCoordinate2D(latitude: 30.7333,
longitude: 76.7794)
OpenMaps.presentActionSheetwithMapOption(coordinate: coordinate)
【讨论】: