programing

iOS 6에서 지도 앱을 프로그래밍 방식으로 엽니다.

mbctv 2023. 4. 11. 22:28
반응형

iOS 6에서 지도 앱을 프로그래밍 방식으로 엽니다.

iOS 6 이전에는 다음과 같은 URL을 열면 (Google) 지도 앱이 열립니다.

NSURL *url = [NSURL URLWithString:@"http://maps.google.com/?q=New+York"];
[[UIApplication sharedApplication] openURL:url];

새로운 Apple Maps 구현에서는 모바일 Safari에서 Google Maps를 열기만 하면 됩니다.iOS 6에서도 같은 동작을 할 수 있는 방법은 무엇입니까? 지도 앱을 프로그래밍 방식으로 열고 특정 위치/주소/검색 등을 가리키도록 하려면 어떻게 해야 합니까?

Apple의 공식 방법은 다음과 같습니다.

// Check for iOS 6
Class mapItemClass = [MKMapItem class];
if (mapItemClass && [mapItemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)]) 
{
    // Create an MKMapItem to pass to the Maps app
    CLLocationCoordinate2D coordinate = 
                CLLocationCoordinate2DMake(16.775, -3.009);
    MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:coordinate 
                                            addressDictionary:nil];
    MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
    [mapItem setName:@"My Place"];
    // Pass the map item to the Maps app
    [mapItem openInMapsWithLaunchOptions:nil];
}

운전 또는 도보 안내를 받고 싶은 경우 다음 사항을 포함할 수 있습니다.mapItemForCurrentLocation와 함께MKMapItem에 정렬하여+openMapsWithItems:launchOptions:기동 옵션을 적절히 설정합니다.

// Check for iOS 6
Class mapItemClass = [MKMapItem class];
if (mapItemClass && [mapItemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)]) 
{
    // Create an MKMapItem to pass to the Maps app
    CLLocationCoordinate2D coordinate = 
                CLLocationCoordinate2DMake(16.775, -3.009);
    MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:coordinate 
                                            addressDictionary:nil];
    MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
    [mapItem setName:@"My Place"];

    // Set the directions mode to "Walking"
    // Can use MKLaunchOptionsDirectionsModeDriving instead
    NSDictionary *launchOptions = @{MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeWalking};
    // Get the "Current User Location" MKMapItem
    MKMapItem *currentLocationMapItem = [MKMapItem mapItemForCurrentLocation];
    // Pass the current location and destination map items to the Maps app
    // Set the direction mode in the launchOptions dictionary
    [MKMapItem openMapsWithItems:@[currentLocationMapItem, mapItem] 
                    launchOptions:launchOptions];
}

원본 iOS 5 및 하위 코드를 보존할 수 있습니다.else그 후의 진술if에 기재되어 있는 항목의 순서를 반대로 했을 경우,openMapsWithItems:좌표에서 현재 위치까지의 방향을 알 수 있습니다.이 툴을 사용하면, 2개의 로케이션의 어느쪽이든, 어느쪽이든,MKMapItem현재 위치 지도 항목 대신.그런 건 안 먹어봤어.

마지막으로, (문자열로서) 지시하는 주소가 있는 경우 지오코더를 사용하여MKPlacemark, 경유로CLPlacemark.

// Check for iOS 6
Class mapItemClass = [MKMapItem class];
if (mapItemClass && [mapItemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)])
{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder geocodeAddressString:@"Piccadilly Circus, London, UK" 
        completionHandler:^(NSArray *placemarks, NSError *error) {

        // Convert the CLPlacemark to an MKPlacemark
        // Note: There's no error checking for a failed geocode
        CLPlacemark *geocodedPlacemark = [placemarks objectAtIndex:0];
        MKPlacemark *placemark = [[MKPlacemark alloc]
                                  initWithCoordinate:geocodedPlacemark.location.coordinate
                                  addressDictionary:geocodedPlacemark.addressDictionary];

        // Create a map item for the geocoded address to pass to Maps app
        MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
        [mapItem setName:geocodedPlacemark.name];

        // Set the directions mode to "Driving"
        // Can use MKLaunchOptionsDirectionsModeWalking instead
        NSDictionary *launchOptions = @{MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving};

        // Get the "Current User Location" MKMapItem
        MKMapItem *currentLocationMapItem = [MKMapItem mapItemForCurrentLocation];

        // Pass the current location and destination map items to the Maps app
        // Set the direction mode in the launchOptions dictionary
        [MKMapItem openMapsWithItems:@[currentLocationMapItem, mapItem] launchOptions:launchOptions];

    }];
}

내 질문에 대한 답을 찾았다.Apple은 지도 URL 형식을 여기에 기록합니다.기본적으로는 대체가 가능한 것 같습니다.maps.google.com와 함께maps.apple.com.

업데이트: iOS 6의 Mobile Safari에서도 동일한 내용이 적용된다는 것이 판명되었습니다.http://maps.apple.com/?q=...동일한 방법으로 해당 검색으로 지도 앱을 엽니다.http://maps.google.com/?q=...이전 버전에서는 그랬습니다.이것은 동작하며, 위의 링크 페이지에 기재되어 있습니다.

업데이트: URL 형식에 대한 질문에 대한 답변입니다.그러나 여기 nevan king의 답변(아래 참조)은 실제 지도 API의 훌륭한 요약입니다.

가장 좋은 방법은 새로운 iOS 6 메서드를 호출하는 것입니다.MKMapItem openInMapsWithLaunchOptions:launchOptions

예:

CLLocationCoordinate2D endingCoord = CLLocationCoordinate2DMake(40.446947, -102.047607);
MKPlacemark *endLocation = [[MKPlacemark alloc] initWithCoordinate:endingCoord addressDictionary:nil];
MKMapItem *endingItem = [[MKMapItem alloc] initWithPlacemark:endLocation];

NSMutableDictionary *launchOptions = [[NSMutableDictionary alloc] init];
[launchOptions setObject:MKLaunchOptionsDirectionsModeDriving forKey:MKLaunchOptionsDirectionsModeKey];

[endingItem openInMapsWithLaunchOptions:launchOptions];

그러면 현재 위치에서 주행하기 위한 내비게이션이 시작됩니다.

maps.apple.com url "filename"을 찾으셨군요.오래된 디바이스는 자동으로 maps.google.com으로 리다이렉트되므로 이 옵션을 선택하는 것이 좋습니다.그러나 iOS 6에서는 MKMapItem이라는 새로운 클래스를 이용할 수 있습니다.

관심 있는 두 가지 방법은 다음과 같습니다.

  1. - Open In Maps With Launch Options : - MKMapItem 인스턴스에서 호출하여 Maps.app에서 엽니다.
  2. +openMapsWithItems:launchOptions: - MKMapItem 클래스에서 호출하여 MKMapItem 인스턴스 배열을 엽니다.

다음은 스위프트에서 완료된 nevan king의 솔루션을 사용한 클래스입니다.

class func openMapWithCoordinates(theLon:String, theLat:String){

            var coordinate = CLLocationCoordinate2DMake(CLLocationDegrees(theLon), CLLocationDegrees(theLat))

            var placemark:MKPlacemark = MKPlacemark(coordinate: coordinate, addressDictionary:nil)

            var mapItem:MKMapItem = MKMapItem(placemark: placemark)

            mapItem.name = "Target location"

            let launchOptions:NSDictionary = NSDictionary(object: MKLaunchOptionsDirectionsModeDriving, forKey: MKLaunchOptionsDirectionsModeKey)

            var currentLocationMapItem:MKMapItem = MKMapItem.mapItemForCurrentLocation()

            MKMapItem.openMapsWithItems([currentLocationMapItem, mapItem], launchOptions: launchOptions)
}

http://maps.apple.com?q=... 링크 설정을 사용하면 오래된 기기에서 먼저 Safari 브라우저를 열 수 있다는 점이 불쾌했습니다.

따라서 iOS 5 기기에서 maps.apple.com을 참조하여 앱을 여는 절차는 다음과 같습니다.

  1. 앱에서 무언가를 클릭하면 maps.apple.com URL을 참조합니다.
  2. safari가 링크를 엽니다.
  3. maps.apple.com 서버가 maps.google.com URL로 리다이렉트 됩니다.
  4. maps.google.com url이 해석되어 Google Maps 앱이 열립니다.

(매우 명확하고 혼란스러운) 스텝2와 스텝3은 사용자에게는 귀찮다고 생각합니다.따라서 OS 버전을 확인하고 디바이스에서 maps.google.com 또는 maps.apple.com 중 하나를 실행합니다(response용).IOS 5 또는 IOS 6 OS 버전).

이 문제에 대한 조사를 통해 다음과 같은 결론을 얻었습니다.

  1. maps.google.com을 사용하면 모든 ios에 대해 safari에서 맵이 열립니다.
  2. maps.apple.com을 사용하면 ios 6의 맵어플리케이션에서 맵이 열리고 ios 5에서도 동작하며 ios 5에서는 safari에서 정상적으로 맵이 열립니다.

구글 는, 「Google」( 「Google」)를 할 수 .comgooglemaps:// ★★★★★★★★★★★★★★★★★」comgooglemaps-x-callback://URL 스킴은 여기에 기재되어 있습니다.

url을 시작하기 전에 url에서 특수문자를 삭제하고 공백을 +로 바꿉니다.이렇게 하면 두통을 덜 수 있습니다.

    NSString *mapURLStr = [NSString stringWithFormat: @"http://maps.apple.com/?q=%@",@"Limmattalstrasse 170, 8049 Zürich"];

    mapURLStr = [mapURLStr stringByReplacingOccurrencesOfString:@" " withString:@"+"];
    NSURL *url = [NSURL URLWithString:[mapURLStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
    if ([[UIApplication sharedApplication] canOpenURL:url]){
            [[UIApplication sharedApplication] openURL:url];
        }
NSString *address = [NSString stringWithFormat:@"%@ %@ %@ %@"
                             ,[dataDictionary objectForKey:@"practice_address"]
                             ,[dataDictionary objectForKey:@"practice_city"]
                             ,[dataDictionary objectForKey:@"practice_state"]
                             ,[dataDictionary objectForKey:@"practice_zipcode"]];


        NSString *mapAddress = [@"http://maps.apple.com/?q=" stringByAppendingString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

        NSLog(@"Map Address %@",mapAddress);

        [objSpineCustomProtocol setUserDefaults:mapAddress :@"webSiteToLoad"];

        [self performSegueWithIdentifier: @"provider_to_web_loader_segue" sender: self];

//VKJ

지도를 사용하는 것이 아니라 UiButton 액션을 사용하는 것만으로, 이것은 나에게 있어서 큰 도움이 되었습니다.

// Button triggers the map to be presented.

@IBAction func toMapButton(sender: AnyObject) {

//Empty container for the value

var addressToLinkTo = ""

//Fill the container with an address

self.addressToLinkTo = "http://maps.apple.com/?q=111 Some place drive, Oak Ridge TN 37830"

self.addressToLinkTo = self.addressToLinkTo.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!

let url = NSURL(string: self.addressToLinkTo)
UIApplication.sharedApplication().openURL(url!)

                }

이 코드 중 일부를 분산시킬 수 있습니다.예를 들어 변수를 클래스 수준 변수로 넣고 다른 함수로 채운 다음 버튼을 누르면 변수에 있는 것을 가져와 URL에서 사용할 수 있도록 스크럽할 수 있습니다.

@PJemyMalouf의 답변을 바탕으로 Swift 4로 업데이트:

private func navigateUsingAppleMaps(to coords:CLLocation, locationName: String? = nil) {
    let placemark = MKPlacemark(coordinate: coords.coordinate, addressDictionary:nil)
    let mapItem = MKMapItem(placemark: placemark)
    mapItem.name = locationName
    let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
    let currentLocationMapItem = MKMapItem.forCurrentLocation()

    MKMapItem.openMaps(with: [currentLocationMapItem, mapItem], launchOptions: launchOptions)
}

언급URL : https://stackoverflow.com/questions/12504294/programmatically-open-maps-app-in-ios-6

반응형