Как открыть Google Карты для показа маршрута с помощью Swift
Я читал в Интернете, но не мог найти законный ответ. Мне нужно открыть Карты Google, когда пользователь нажимает кнопку, чтобы показывать маршруты. Начало и назначение должны быть автоматически заполнены.
Как я могу достичь этого в Swift?
Если у кого-то есть решение, пожалуйста, предоставьте мне пример кода. Начало всегда будет текущим местоположением пользователя.
Ответы
Ответ 1
OK Я сам нашел ответ.
Если вы хотите отобразить направления из текущего местоположения пользователя, оставьте поле 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://");
}
}
для любых дальнейших запросов вы можете сослаться на эту ссылку Схема URL-адреса карты Google
Ответ 2
Ответ уже существует, но в более ранних версиях 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://");
}
Ответ 3
Для тех, у кого решение для принятого ответа не сработало, не забудьте добавить comgooglemaps
в LSApplicationQueriesSchemes
в info.plist.
![info.plist]()
Ответ 4
@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)
}
}
}
Ответ 5
Я хочу, чтобы пользователь мог открыть Google Карты через браузер (работает только тогда, когда у пользователя нет приложения Google Maps). Google предоставляет документацию по этому вопросу здесь. Начиная с iOS 9 вы должны установить схему. Это вы найдете здесь.
Для меня решение Google не работает. Может быть, вы умнее и найдете решение (пожалуйста, напишите!).
В любом случае я сделал простой веб-звонок:
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/[email protected]\(lat),\(lon)")!)
}
Это можно использовать как своего рода запасной вариант ответа от сумеш.
Ответ 6
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)
}
Ответ 7
Swift 4 Рабочий код
if let url = URL(string: "comgooglemaps://?saddr=&daddr=\(location.coordinate.latitude),\(location.coordinate.longitude)&directionsmode=driving") {
UIApplication.shared.open(url, options: [:])
}
этот код работает для меня. И я не вставил
* LSApplicationQueriesSchemes
Если вы используете эмулятор не можете увидеть результаты. Не забудьте поработать над проектом на телефоне.
Ответ 8
1) Метод: вы можете передать только адрес назначения. Текущий адрес будет автоматически загружен приложением карты Google.
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://");
}
}
Ответ 9
Вот обновление Swift 3
Во-первых, вам нужно два элемента для LSApplicationQueriesSchemes
в info.plist.
![enter image description here]()
Затем вы можете использовать эту функцию для загрузки адреса на картах Google.
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.")
}
}
Ответ 10
//Я надеюсь, что это сработает идеально.
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 согласно приложенному изображению.
введите описание изображения здесь
Ответ 11
Прежде всего, спасибо вам, ребята, за ваши ответы. Но когда я работал, я не нашел рабочего ответа для себя. В результате я создал рабочий код в двух случаях: когда у пользователя есть приложение Google Maps, а если нет. Вот моя версия кода. Xcode 10, Swift 4.2. Надеюсь, это поможет.
Шаг 1: найдите ваш info.plist и откройте как → Исходный код
![First you should find your info.plist and open it as Source Code.]()
Шаг 2. Добавьте эти строки между <dict>
и </dict>
![enter image description here]()
Шаг 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)
}
Ответ 12
В 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://");
}
}
Ответ 13
Ответ уже есть, но в более старых версиях Swift, и этот код может открыть Google Map в браузере, если на вашем iPhone не установлено приложение 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.")
}
}
Ответ 14
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)
}
}