현재 위치를 시작 주소로 사용하여 길 찾기에 대한 iPhone지도를 호출하는 방법
나는 아이폰이 호출하여 응용 프로그램을 매핑 시작할 수 알고 openURL
매개 변수를 사용하여 URL을 매핑하는 구글에 saddr
와 daddr
위치 문자열이나 위도 / 경도 (아래 예 참조).
그러나 지도 앱의 위치 처리 코드를 사용할 수 있도록 시작 주소를 "현재 위치" 지도 북마크 로 만들 수 있는지 궁금합니다 . 내 Google 검색은 무익했습니다.
예를 들면 :
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat: @"http://maps.google.com/maps?saddr=%@&daddr=%@", myLatLong, latlong]]];
대신 현재 위치 북마크를 호출하는 것을 제외하고는 myLatLong
.
iOS 6 이전
현재 위치를 가져 오려면 Core Location을 사용해야하지만 위도 / 경도 쌍을 사용하면지도에서 해당 위치에서 거리 주소 또는 위치로 경로를 지정할 수 있습니다. 이렇게 :
CLLocationCoordinate2D currentLocation = [self getCurrentLocation];
// this uses an address for the destination. can use lat/long, too with %f,%f format
NSString* address = @"123 Main St., New York, NY, 10001";
NSString* url = [NSString stringWithFormat: @"http://maps.google.com/maps?saddr=%f,%f&daddr=%@",
currentLocation.latitude, currentLocation.longitude,
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
마지막으로 CoreLocation을 사용하여 현재 위치를 명시 적으로 찾는 것을 피하고 @"http://maps.google.com/maps?saddr=Current+Location&daddr=%@"
대신 URL 을 사용 하려면 Current + Location 문자열 을 지역화하는 방법 에 대해 아래 주석에서 제공 한이 링크 를 참조하십시오 . 그러나 문서화되지 않은 다른 기능을 활용하고 있으며 Jason McCreary가 아래에서 지적했듯이 향후 릴리스에서는 안정적으로 작동하지 않을 수 있습니다.
iOS 6 업데이트
원래 지도 는 Google 지도를 사용했지만 지금은 Apple과 Google에 별도의지도 앱이 있습니다.
1) Google지도 앱을 사용하여 경로를 지정 하려면 comgooglemaps URL 스키마를 사용 하십시오 .
NSString* url = [NSString stringWithFormat: @"comgooglemaps://?daddr=%@&directionsmode=driving",
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
BOOL opened = [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
2) Apple Maps를 사용하려면 MKMapItem
iOS 6 용 새 클래스를 사용할 수 있습니다. 여기에서 Apple API 문서를 참조하십시오.
기본적으로 목적지 좌표 ( latlong
)로 라우팅하는 경우 다음과 같은 것을 사용합니다 .
MKPlacemark* place = [[MKPlacemark alloc] initWithCoordinate: latlong addressDictionary: nil];
MKMapItem* destination = [[MKMapItem alloc] initWithPlacemark: place];
destination.name = @"Name Here!";
NSArray* items = [[NSArray alloc] initWithObjects: destination, nil];
NSDictionary* options = [[NSDictionary alloc] initWithObjectsAndKeys:
MKLaunchOptionsDirectionsModeDriving,
MKLaunchOptionsDirectionsModeKey, nil];
[MKMapItem openMapsWithItems: items launchOptions: options];
동일한 코드에서 iOS 6+ 및 iOS 6 이전 버전을 모두 지원하려면 Apple이 MKMapItem
API 문서 페이지 에있는 다음 코드와 같은 코드를 사용하는 것이 좋습니다 .
Class itemClass = [MKMapItem class];
if (itemClass && [itemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)]) {
// iOS 6 MKMapItem available
} else {
// use pre iOS 6 technique
}
이는 Xcode Base SDK가 iOS 6 (또는 최신 iOS ) 이라고 가정합니다 .
NSString* addr = [NSString stringWithFormat:@"http://maps.google.com/maps?daddr=Current Location&saddr=%@",startAddr];
NSURL* url = [[NSURL alloc] initWithString:[addr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL:url];
[url release];
이것은 작동하지만 iPhone / iPod 언어가 영어로 설정된 경우에만 작동합니다. 다른 언어를 지원하려면지도 북마크 이름과 일치하도록 현지화 된 문자열을 사용해야합니다.
이것은 iPhone에서 작동합니다.
http://maps.google.com/maps?saddr=Current Location & daddr = 123 Main St, Ottawa, ON
다음과 같이 전 처리기 #define을 사용할 수 있습니다.
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
iOS 버전을 이해하십시오. 그런 다음이 코드를 사용하여 iOS 6도 지원할 수 있습니다.
NSString* addr = nil;
if (SYSTEM_VERSION_LESS_THAN(@"6.0")) {
addr = [NSString stringWithFormat:@"http://maps.google.com/maps?daddr=%1.6f,%1.6f&saddr=Posizione attuale", view.annotation.coordinate.latitude,view.annotation.coordinate.longitude];
} else {
addr = [NSString stringWithFormat:@"http://maps.apple.com/maps?daddr=%1.6f,%1.6f&saddr=Posizione attuale", view.annotation.coordinate.latitude,view.annotation.coordinate.longitude];
}
NSURL* url = [[NSURL alloc] initWithString:[addr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL:url];
샌드 박싱으로 인해지도 애플리케이션의 북마크에 액세스 할 수 없습니다.
대신 Core Location을 사용하여 현재 위치를 직접 확인하십시오. 그런 다음 작성한 URL에서 해당 위치 (위도 및 경도)를 사용하여지도를 엽니 다.
특정 매핑 요청으로 Apple, Google 및 기타 iOS 매핑 앱을 시작하기 위해 만든 미니 라이브러리 인 CMMapLauncher를 확인하는 것이 좋습니다 . CMMapLauncher를 사용하면 질문에 대한 지침을 얻는 코드는 다음과 같습니다.
[CMMapLauncher launchMapApp:CMMapAppAppleMaps
forDirectionsFrom:[CMMapPoint mapPointWithName:@"Origin"
coordinate:myLatLong]
to:[CMMapPoint mapPointWithName:@"Destination"
coordinate:latlong]];
보시다시피 iOS 6과 다른 사람들 사이에 필요한 버전 확인을 캡슐화합니다.
iOS6이 나왔으니 안녕하세요!
애플은 (제 관점에서) 나쁜 방식으로 놀라운 일을했습니다.
Apple의지도가 실행되고 iOS 6을 실행하는 장치의 maps.google.com/?q=
경우 iDevice가 기본 계획 앱을 열도록하려면 사용하지 않아야 합니다. 이제 maps.apple.com/?q=
.
개발자가 많은 작업을 할 필요가 없도록 친숙한 maps.apple.com 서버는 모든 비 Apple 기기를 maps.google.com으로 리디렉션하므로 변경 사항이 투명합니다.
이런 식으로 개발자는 모든 Google 쿼리 문자열을 사과 문자열로 전환하기 만하면됩니다. 이것은 내가 많이 싫어하는 것입니다.
저는 오늘 그 기능을 구현해야했기 때문에 그렇게했습니다. 하지만 모바일 웹 사이트에있는 모든 URL을 Apple의지도 서버를 대상으로 다시 작성해서는 안된다고 생각했기 때문에 iDevices 서버 측을 감지하고 해당 URL 만 제공 할 것이라고 생각했습니다. 나는 나눌 것이라고 생각했다.
저는 PHP를 사용하고 있으므로 오픈 소스 Mobile Detect 라이브러리를 사용했습니다. http://code.google.com/p/php-mobile-detect/
isiPad
의사 메서드를 부울 게터로 사용하면 완료됩니다. Google을 사과로 변환하지 않습니다 ;-)
$server=$detect->isiPad()?"apple":"google";
$href="http://maps.{$server}.com/?q=..."
건배!
이제 모바일 장치의 URL에서만 html로이 작업을 수행 할 수 있습니다. 여기에 예가 있습니다. 멋진 점은 이것을 qr 코드로 바꾸면 누군가가 어디에 있든 휴대 전화에서 스캔하여 길을 찾을 수 있다는 것입니다.
실제 솔루션은 여기에서 찾을 수 있습니다. Z5 개념 iOS 개발 코드 스 니펫
약간의 인코딩이 필요합니다.
- (IBAction)directions1_click:(id)sender
{
NSString* address = @"118 Your Address., City, State, ZIPCODE";
NSString* currentLocation = @"Current Location";
NSString* url = [NSStringstringWithFormat: @"http://maps.google.com/maps?saddr=%@&daddr=%@",[currentLocation stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
UIApplication *app = [UIApplicationsharedApplication];
[app openURL: [NSURL URLWithString: url]];
}
iOS6의 경우 Apple 문서는 동등한 maps.apple.com URL 스키마 사용을 권장합니다.
그래서 사용
http://maps.apple.com/maps?saddr=%f,%f&daddr=%f,%f
대신에
http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f
이전 버전과 호환되도록 코드는
NSString* versionNum = [[UIDevice currentDevice] systemVersion];
NSString *nativeMapScheme = @"maps.apple.com";
if ([versionNum compare:@"6.0" options:NSNumericSearch] == NSOrderedAscending)
nativeMapScheme = @"maps.google.com";
}
NSString* url = [NSString stringWithFormat: @"http://%@/maps?saddr=%f,%f&daddr=%f,%f", nativeMapScheme
startCoordinate.latitude, startCoordinate.longitude,
endCoordinate.latitude, endCoordinate.longitude];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
there is a whole load of other supported parameters for the Apple Maps URL scheme : Apple URL Scheme Reference
you can use these iOS version detection macros if you have conditional code in other parts of your code. iOS version macros
If you don't want to ask for location permissions and don't have the lat and lng, use the following.
NSString *destinationAddress = @"Amsterdam";
Class itemClass = [MKMapItem class];
if (itemClass && [itemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)]) {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:destinationAddress completionHandler:^(NSArray *placemarks, NSError *error) {
if([placemarks count] > 0) {
MKPlacemark *placeMark = [[MKPlacemark alloc] initWithPlacemark:[placemarks objectAtIndex:0]];
MKMapItem *mapItem = [[MKMapItem alloc]initWithPlacemark:placeMark];
MKMapItem *mapItem2 = [MKMapItem mapItemForCurrentLocation];
NSArray *mapItems = @[mapItem, mapItem2];
NSDictionary *options = @{
MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
MKLaunchOptionsMapTypeKey:
[NSNumber numberWithInteger:MKMapTypeStandard],
MKLaunchOptionsShowsTrafficKey:@YES
};
[MKMapItem openMapsWithItems:mapItems launchOptions:options];
} else {
//error nothing found
}
}];
return;
} else {
NSString *sourceAddress = [LocalizedCurrentLocation currentLocationStringForCurrentLanguage];
NSString *urlToOpen = [NSString stringWithFormat:@"http://maps.google.com/maps?saddr=%@&daddr=%@",
[sourceAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[destinationAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlToOpen]];
}
For ios5, the Current Location needs to be in the correct language. I use the LocalizedCurrentLocation from this post http://www.martip.net/blog/localized-current-location-string-for-iphone-apps
For ios6, I use the CLGeocoder to get the placemark and then open the map with it and the current location.
Remember to add CoreLocation.framework and MapKit.framework
For iOS6 Maps App, you can just use the same URL posted above http://maps.google.com/maps?saddr=%f,%f&daddr=%@
but instead of the Google maps URL, you use the url with maps://
resulting in the following URL: maps://saddr=%f,%f&daddr=%@.
Using 'Current Location' doesn't seem to work, so I stayed with the coordinates.
Antother good thing: It's backwards compatible: On iOS5, it launches the Google Maps app.
With the current version of Google Maps, simply omit the sadr
parameter:
saddr
: … If the value is left blank, then the user’s current location will be used.
https://developers.google.com/maps/documentation/ios/urlscheme
My suggestion would be using OpenInGoogleMaps-iOS as this is an up to date choice (by November 2015), it supports cocoa pods installation and you are ready to go in a few clicks.
Install using: pod "OpenInGoogleMaps"
Require in header file using: #import "OpenInGoogleMapsController.h"
Sample code below:
/*In case the user does NOT have google maps, then apple maps shall open*/
[OpenInGoogleMapsController sharedInstance].fallbackStrategy = kGoogleMapsFallbackAppleMaps;
/*Set the coordinates*/
GoogleMapDefinition *definition = [[GoogleMapDefinition alloc] init];
CLLocationCoordinate2D metsovoMuseumCoords; //coordinates struct
metsovoMuseumCoords.latitude = 39.770598;
metsovoMuseumCoords.longitude = 21.183215;
definition.zoomLevel = 20;
definition.center = metsovoMuseumCoords; //this will be the center of the map
/*and here we open the map*/
[[OpenInGoogleMapsController sharedInstance] openMap:definition];
I answered this on a different thread. (Current Location doesn't work with Apple Maps IOS 6). You need to get the coordinates of the current location first, then use it to create the map url.
If you don't provide source location, it will take current location as source. Try below code-
let urlString = "http://maps.apple.com/maps?daddr=(destinationLocation.latitude),(destinationLocation.longitude)&dirflg=d" }
UIApplication.shared.openURL(URL(string: urlString)!)
'Nice programing' 카테고리의 다른 글
스트림에서 TextReader를 받으시겠습니까? (0) | 2020.10.25 |
---|---|
styles.xml에서 프로그래밍 방식으로 스타일 속성을 검색하는 방법 (0) | 2020.10.25 |
입력 스트림을 출력 스트림에 연결 (0) | 2020.10.25 |
Eclipse의 초보자, "동적 웹 프로젝트"가 없습니다. Linux Ubuntu에 있습니다. (0) | 2020.10.25 |
Html.EditorFor 기본값 설정 (0) | 2020.10.25 |