¿Cómo puedo iniciar la aplicación Google Maps para iPhone desde mi propia aplicación nativa?

StackOverflow https://stackoverflow.com/questions/30058

  •  09-06-2019
  •  | 
  •  

Pregunta

El Documentación para desarrolladores de Apple (el enlace ya no está disponible) explica que si coloca un enlace en una página web y luego hace clic en él mientras usa Mobile Safari en el iPhone, se iniciará la aplicación Google Maps que se proporciona de serie con el iPhone.

¿Cómo puedo iniciar la misma aplicación Google Maps con una dirección específica desde mi propia aplicación nativa de iPhone (es decir,no una página web a través de Mobile Safari) de la misma manera que al tocar una dirección en Contactos se abre el mapa?

NOTA:ESTO SOLO FUNCIONA EN EL DISPOSITIVO MISMO.NO EN EL SIMULADOR.

¿Fue útil?

Solución

Para iOS 5.1.1 y versiones anteriores, utilice el openURL método de UIApplication.Realizará la reinterpretación mágica normal de la URL del iPhone.entonces

[someUIApplication openURL:[NSURL URLWithString:@"http://maps.google.com/maps?q=London"]]

debería invocar la aplicación de mapas de Google.

Desde iOS 6, invocarás la aplicación Maps de Apple.Para ello, configure un MKMapItem objeto con la ubicación que desea mostrar y luego enviarle el openInMapsWithLaunchOptions mensaje.Para comenzar en la ubicación actual, intente:

[[MKMapItem mapItemForCurrentLocation] openInMapsWithLaunchOptions:nil];

Deberá estar vinculado a MapKit para esto (y creo que le solicitará acceso a la ubicación).

Otros consejos

Exactamente.El código que necesitas para lograr esto es algo así:

UIApplication *app = [UIApplication sharedApplication];
[app openURL:[NSURL URLWithString: @"http://maps.google.com/maps?q=London"]];

desde según la documentación, UIApplication solo está disponible en el Delegado de aplicaciones a menos que llame asharedApplication.

Para abrir Google Maps en coordenadas específicas, pruebe este código:

NSString *latlong = @"-56.568545,1.256281";
NSString *url = [NSString stringWithFormat: @"http://maps.google.com/maps?ll=%@",
[latlong stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];

Puede reemplazar la cadena latlong con la ubicación actual de CoreLocation.

También puede especificar el nivel de zoom utilizando el indicador ("z").Los valores son 1-19.He aquí un ejemplo:

[[UIApplication shareApplication] openURL:[NSURL URLWithString:@"http://maps.google.com/maps?z=8"]];

Ahora también existe la aplicación Google Maps de la App Store, documentada en https://developers.google.com/maps/documentation/ios/urlscheme

Entonces primero verificarías que esté instalado:

[[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"comgooglemaps://"]];

Y luego puedes reemplazar condicionalmente http://maps.google.com/maps?q= con comgooglemaps://?q=.

Aquí está la referencia del esquema de URL de Apple para enlaces de mapas: https://developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html

Las reglas para crear un enlace de mapa válido son las siguientes:

  • El dominio debe ser google.com y el subdominio debe ser mapas o ditu.
  • La ruta debe ser /, /maps, /local o /m si la consulta contiene sitio como clave y local como valor.
  • La ruta no puede ser /maps/*.
  • Todos los parámetros deben ser compatibles.Consulte la Tabla 1 para obtener una lista de parámetros admitidos**.
  • Un parámetro no puede ser q=* si el valor es una URL (por lo que no se detecta KML).
  • Los parámetros no pueden incluir view=text o dirflg=r.

**Consulte el enlace de arriba para obtener la lista de parámetros admitidos.

Si está utilizando iOS 10, no olvide agregar esquemas de consulta en Info.plist.

<key>LSApplicationQueriesSchemes</key>
<array>
 <string>comgooglemaps</string>
</array>

Si estás usando Objective-C

if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"comgooglemaps:"]]) {
    NSString *urlString = [NSString stringWithFormat:@"comgooglemaps://?ll=%@,%@",destinationLatitude,destinationLongitude];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
    } else { 
    NSString *string = [NSString stringWithFormat:@"http://maps.google.com/maps?ll=%@,%@",destinationLatitude,destinationLongitude];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:string]];
    }

Si estás usando Swift 2.2

if UIApplication.sharedApplication().canOpenURL(NSURL(string: "comgooglemaps:")!) {
    var urlString = "comgooglemaps://?ll=\(destinationLatitude),\(destinationLongitude)"
    UIApplication.sharedApplication().openURL(NSURL(string: urlString)!)
}
else {
    var string = "http://maps.google.com/maps?ll=\(destinationLatitude),\(destinationLongitude)"
    UIApplication.sharedApplication().openURL(NSURL(string: string)!)
}

Si estás usando Swift 3.0

if UIApplication.shared.canOpenURL(URL(string: "comgooglemaps:")!) {
    var urlString = "comgooglemaps://?ll=\(destinationLatitude),\(destinationLongitude)"
    UIApplication.shared.openURL(URL(string: urlString)!)
}
else {
    var string = "http://maps.google.com/maps?ll=\(destinationLatitude),\(destinationLongitude)"
    UIApplication.shared.openURL(URL(string: string)!)
}

Para la pregunta del teléfono, ¿estás probando en el simulador?Esto sólo funciona en el propio dispositivo.

Además, openURL devuelve un bool, que puede utilizar para comprobar si el dispositivo en el que está ejecutando admite la funcionalidad.Por ejemplo, no puedes hacer llamadas desde un iPod Touch :-)

Simplemente llame a este método y agregue el esquema de URL de Google Maps en su archivo .plist igual que este Respuesta.

Swift-4: -

func openMapApp(latitude:String, longitude:String, address:String) {

    var myAddress:String = address

    //For Apple Maps
    let testURL2 = URL.init(string: "http://maps.apple.com/")

    //For Google Maps
    let testURL = URL.init(string: "comgooglemaps-x-callback://")

    //For Google Maps
    if UIApplication.shared.canOpenURL(testURL!) {
        var direction:String = ""
        myAddress = myAddress.replacingOccurrences(of: " ", with: "+")

        direction = String(format: "comgooglemaps-x-callback://?daddr=%@,%@&x-success=sourceapp://?resume=true&x-source=AirApp", latitude, longitude)

        let directionsURL = URL.init(string: direction)
        if #available(iOS 10, *) {
            UIApplication.shared.open(directionsURL!)
        } else {
            UIApplication.shared.openURL(directionsURL!)
        }
    }
    //For Apple Maps
    else if UIApplication.shared.canOpenURL(testURL2!) {
        var direction:String = ""
        myAddress = myAddress.replacingOccurrences(of: " ", with: "+")

        var CurrentLocationLatitude:String = ""
        var CurrentLocationLongitude:String = ""

        if let latitude = USERDEFAULT.value(forKey: "CurrentLocationLatitude") as? Double {
            CurrentLocationLatitude = "\(latitude)"
            //print(myLatitude)
        }

        if let longitude = USERDEFAULT.value(forKey: "CurrentLocationLongitude") as? Double {
            CurrentLocationLongitude = "\(longitude)"
            //print(myLongitude)
        }

        direction = String(format: "http://maps.apple.com/?saddr=%@,%@&daddr=%@,%@", CurrentLocationLatitude, CurrentLocationLongitude, latitude, longitude)

        let directionsURL = URL.init(string: direction)
        if #available(iOS 10, *) {
            UIApplication.shared.open(directionsURL!)
        } else {
            UIApplication.shared.openURL(directionsURL!)
        }

    }
    //For SAFARI Browser
    else {
        var direction:String = ""
        direction = String(format: "http://maps.google.com/maps?q=%@,%@", latitude, longitude)
        direction = direction.replacingOccurrences(of: " ", with: "+")

        let directionsURL = URL.init(string: direction)
        if #available(iOS 10, *) {
            UIApplication.shared.open(directionsURL!)
        } else {
            UIApplication.shared.openURL(directionsURL!)
        }
    }
}

Espero, esto es lo que estás buscando.Cualquier inquietud contáctame.:)

"g" cambia a "q"

[[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"http://maps.google.com/maps?q=London"]]

Si todavía tienes problemas, este video muestra cómo hacer que "Mis mapas" de Google aparezca en el iPhone; luego puedes tomar el enlace y enviárselo a cualquiera y funciona.

http://www.youtube.com/watch?v=Xo5tPjsFBX4

Para pasar al mapa de Google, utilice esta API y envíe la latitud y longitud del destino.

NSString* addr = nil;
     addr = [NSString stringWithFormat:@"http://maps.google.com/maps?daddr=%1.6f,%1.6f&saddr=Posizione attuale", destinationLat,destinationLong];

NSURL* url = [[NSURL alloc] initWithString:[addr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL:url];

Si necesita más flexibilidad que la que le brinda el formato de URL de Google o si desea insertar un mapa en su aplicación en lugar de iniciar la aplicación de mapas, encontrará un ejemplo en https://sourceforge.net/projects/quickconnect.

Si necesita más flexibilidad que la que le brinda el formato de URL de Google o si desea insertar un mapa en su aplicación en lugar de iniciar la aplicación de mapas Aquí hay un ejemplo.

Incluso le proporcionará el código fuente para realizar toda la integración.

iPhone4 iOS 6.0.1 (10A523)

Tanto para Safari como para Chrome.Ambas versiones más recientes hasta el momento (10 de junio de 2013).

El siguiente esquema de URL también funciona.Pero en el caso de Chrome solo funciona dentro de la página, no funciona desde la barra de direcciones.

mapas:q=Título dado@latitud,longitud

**Getting Directions between 2 locations**

        NSString *googleMapUrlString = [NSString stringWithFormat:@"http://maps.google.com/?saddr=%@,%@&daddr=%@,%@", @"30.7046", @"76.7179", @"30.4414", @"76.1617"];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:googleMapUrlString]];

Código de trabajo como en Swift 4:

Paso 1: agregue lo siguiente a info.plist

<key>LSApplicationQueriesSchemes</key>
<array>
<string>googlechromes</string>
<string>comgooglemaps</string>
</array>

Paso 2: utilice el siguiente código para mostrar Google Maps

    let destinationLatitude = "40.7128"
    let destinationLongitude = "74.0060"

    if UIApplication.shared.canOpenURL(URL(string: "comgooglemaps:")!) {
        if let url = URL(string: "comgooglemaps://?ll=\(destinationLatitude),\(destinationLongitude)"), !url.absoluteString.isEmpty {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }else{
        if let url = URL(string: "http://maps.google.com/maps?ll=\(destinationLatitude),\(destinationLongitude)"), !url.absoluteString.isEmpty {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top