Google 지도 앱 열기(플러트와 함께 사용 가능한 경우)
구글 지도 앱이 iOS에 설치되어 있는지 여부를 감지하고, 설치되어 있으면 실행하고, 설치되어 있지 않으면 애플 지도를 실행합니다. 지금까지 제가 가지고 있는 것은 이렇습니다만, Google 지도가 설치된 휴대폰에서는 이를 인식하지 못하고 제대로 실행되지 않습니다.
아이디어 있어요?
import 'package:url_launcher/url_launcher.dart';
_launchMaps() async {
String googleUrl =
'comgooglemaps://?center=${trip.origLocationObj.lat},${trip.origLocationObj.lon}';
String appleUrl =
'https://maps.apple.com/?sll=${trip.origLocationObj.lat},${trip.origLocationObj.lon}';
if (await canLaunch("comgooglemaps://")) {
print('launching com googleUrl');
await launch(googleUrl);
} else if (await canLaunch(appleUrl)) {
print('launching apple url');
await launch(appleUrl);
} else {
throw 'Could not launch url';
}
}
여기서 URL 체계를 가져왔습니다:
나는 내 문제를 발견했다: 이것은 목록 파일에 있어야 한다. 위의 질문의 코드는 괜찮습니다. (질문에서 언급된 SO 답변은 "comgoogle maps" 문자열만 언급했습니다.)
<key>LSApplicationQueriesSchemes</key>
<array>
<string>googlechromes</string>
<string>comgooglemaps</string>
</array>
문서:
패키지를 설치하고 아래 코드를 사용할 수 있습니다:
import 'package:url_launcher/url_launcher.dart';
class MapUtils {
MapUtils._();
static Future<void> openMap(double latitude, double longitude) async {
String googleUrl = 'https://www.google.com/maps/search/?api=1&query=$latitude,$longitude';
if (await canLaunch(googleUrl)) {
await launch(googleUrl);
} else {
throw 'Could not open the map.';
}
}
}
이제 앱에서 구글 지도를 열 수 있습니다. 다음 방법을 호출하십시오:
MapUtils.openMap(-3.823216,-38.481700);
URL 실행기 사용
yaml 파일: url_dll: ^5.0.2
그런 다음 이 방법을 사용하여 제공된 lat 및 long 중심의 구글 맵을 열 수 있습니다
more info to maps intent from docs [here][2]
launchMap({String lat = "47.6", String long = "-122.3"}) async{
var mapSchema = 'geo:$lat,$long';
if (await canLaunch(mapSchema)) {
await launch(mapSchema);
} else {
throw 'Could not launch $mapSchema';
}
}
만약 당신이 실제 주소를 가지고 있지 않다면, 당신은 단순히 구글 지도에 주소를 전달할 수 있다.
void launchMap(String address) async {
String query = Uri.encodeComponent(address);
String googleUrl = "https://www.google.com/maps/search/?api=1&query=$query";
if (await canLaunch(googleUrl)) {
await launch(googleUrl);
}
}
물론, 주소에 더 많은 정보가 있을수록 검색은 더 정확해질 것이다. 실제 구글 지도 페이지나 앱에서 무언가를 찾는 것과 정확히 같다.
참고로 주소를 URL에 추가하기 전에 주소를 URL 인코딩해야 공백과 같은 특수 문자를 지원할 수 있습니다. iOS에만 필요하지만, 우리는 모든 환경을 위해 개발하고 싶습니다.
방향을 사용하여 탐색하려면 소스 및 대상 좌표와 중지로 추가할 다른 좌표를 사용하여 URL을 생성하면 됩니다.
단계:
플러그인 설치
아래와 같이 코드를 작성한다.
_launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
const url ='https://www.google.com/maps/dir/?api=1&origin=43.7967876,-79.5331616&destination=43.5184049,-79.8473993&waypoints=43.1941283,-79.59179|43.7991083,-79.5339667|43.8387033,-79.3453417|43.836424,-79.3024487&travelmode=driving&dir_action=navigate';
_launchURL(url);
import 'package:url_launcher/url_launcher.dart';
static void launchMapsUrl(
sourceLatitude,
sourceLongitude,
destinationLatitude,
destinationLongitude) async {
String mapOptions = [
'saddr=$sourceLatitude,$sourceLongitude',
'daddr=$destinationLatitude,$destinationLongitude',
'dir_action=navigate'
].join('&');
final url = 'https://www.google.com/maps?$mapOptions';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
} }
여기서 이 기능을 직접 사용하여 필요한 매개 변수를 전달하고 이 패키지를 가져올 수도 있습니다
이런 식으로 해
전체 코드는 아래와 같습니다
static void navigateTo(double lat, double lng) async {
var uri = Uri.parse("google.navigation:q=$lat,$lng&mode=d");
if (await canLaunch(uri.toString())) {
await launch(uri.toString());
} else {
throw 'Could not launch ${uri.toString()}';
}
}
펍스펙으로
dependencies:
flutter:
sdk: flutter
...
url_launcher: ^5.7.8
사용할 위치 가져오기
import 'package:url_launcher/url_launcher.dart';
최종적으로 네가 불러라
onPressed: () {
navigateTo(location.lat, location.lng);
},
static Future<void> openMap(BuildContext context, double lat, double lng) async {
String url = '';
String urlAppleMaps = '';
if (Platform.isAndroid) {
url = 'https://www.google.com/maps/search/?api=1&query=$lat,$lng';
if (await canLaunchUrl(Uri.parse(url))) {
await launchUrl(Uri.parse(url));
} else {
throw 'Could not launch $url';
}
} else {
urlAppleMaps = 'https://maps.apple.com/?q=$lat,$lng';
url = 'comgooglemaps://?saddr=&daddr=$lat,$lng&directionsmode=driving';
if (await canLaunchUrl(Uri.parse(url))) {
await launchUrl(Uri.parse(url));
} else if (await canLaunchUrl(Uri.parse(urlAppleMaps))) {
await launchUrl(Uri.parse(urlAppleMaps));
} else {
throw 'Could not launch $url';
}
}
}
플러그인 사용:
intent: ^1.4.0
다음 코드를 사용해 보십시오:
static void navigateTo(double lat, double lng) async {
var uri = Uri.parse("google.navigation:q=$lat,$lng&mode=c");
android_intent.Intent()
..setAction(android_action.Action.ACTION_VIEW)
..setData(uri)
..setPackage("com.google.android.apps.maps")
..startActivity().catchError((e) => print(e));
}
참고:
Roc Boronat의 후속으로 플랫폼별 지도 애플리케이션을 실행하는 데 다음 코드를 사용할 수 있습니다.
Future<void> launchMapUrl(String address) async {
String encodedAddress = Uri.encodeComponent(address);
String googleMapUrl = "https://www.google.com/maps/search/?api=1&query=$encodedAddress";
String appleMapUrl = "http://maps.apple.com/?q=$encodedAddress";
if (Platform.isAndroid) {
try {
if (await canLaunch(googleMapUrl)) {
await launch(googleMapUrl);
}
} catch (error) {
throw("Cannot launch Google map");
}
}
if (Platform.isIOS) {
try {
if (await canLaunch(appleMapUrl)) {
await launch(appleMapUrl);
}
} catch (error) {
throw("Cannot launch Apple map");
}
}
Apple Maps URL의 쿼리 매개 변수에 대한 자세한 내용은 여기를 참조하십시오.
편집(2022년 8월 7일): 이 코드는 플러그인 버전 6.0.20까지 작동합니다. 6.0.20 및 6.0.20 이상의 플러그인 버전을 사용하여 및 메서드를 사용하여 Google 지도를 실행하려고 할 때 오류가 발생하여 이 버전 이후에 작동하지 않았습니다. 사용되지 않는 메서드( 및 )에서만 작동합니다. 이 코드 스니펫을 시도하고 싶은 사람이 있다면 미리 알려주세요.
tldr: 라이브러리에 오류가 있고 canLaunch는 URL을 실행할 수 있더라도 때때로 false를 반환합니다.
나는 내 앱의 다른 링크와 같은 방식으로 구글 지도 링크()를 열려고 했지만, 어떤 이유로든 런치는 항상 거짓으로 반환되었다. 그래서 저는 제 앱이 다운되지 않도록 Try catch block을 실행합니다. 그리고 그것은 작동합니다.
try {
launch(url);
} catch (error, stack) {
// log error
}
lat &lon 대신 'url_syslog 6.1.0' + 물리적 주소를 사용합니다,
void _pushMap(String address) async {
String query = Uri.encodeComponent(address);
String googleUrl = "google.navigation:q=$query";
Uri googleUri = Uri.parse(googleUrl);
if (await canLaunchUrl(googleUri)) {
await launchUrl(googleUri);
}
}
이렇게 하면 구글 지도를 포함한 관련 앱을 열겠다는 암시적 의도가 전송됩니다. iOS 기기에서 테스트하지 않았습니다.
package url_dll을 설치하고 아래 코드를 사용할 수 있습니다: 이것은 다음과 같은 최신 코드입니다
url_filename: 6.1.6
canLaunch(); launch(); 이러한 메서드는 이제 더 이상 사용되지 않습니다.
class GoogleMapUtils {
GoogleMapUtils._();
static Future<void> openMapApp(double latitude, double longitude) async {
Uri googleUrl = Uri.parse('https://www.google.com/maps/search/?api=1&query=$latitude,$longitude');
if (await canLaunchUrl(googleUrl)) {
await launchUrl(googleUrl);
} else {
throw 'Unable open the map.';
}
}
}
패키지 설치
아래 기능을 사용합니다
void launchMap() async { Uri googleUrl = Uri.parse('https://www.google.com/maps/search/?api=1&query=Googleplex'); if (await canLaunchUrl(googleUrl)) { await launchUrl(googleUrl, mode:LaunchMode.externalApplication); } }
기본적으로 네비게이션이 열린 상태에서 사용합니다.
샘플 코드 - 앱이 설치된 경우 앱에서 열립니다. 그렇지 않으면 브라우저에서 열립니다
///launch map
Future<void> openMap(double latitude, double longitude) async {
String mapUrl = '';
if (Platform.isIOS) {
mapUrl =
'https://maps.apple.com/?daddr=$latitude,$longitude';
} else {
mapUrl =
'https://www.google.com/maps/dir/?api=1&destination=$latitude,$longitude&travelmode=driving';
}
if (await canLaunchUrl(Uri.parse(mapUrl))) {
await launchUrl(Uri.parse(mapUrl),mode: LaunchMode.externalApplication);
} else {
throw 'Could not open the map.';
}
}
만약 당신이 애플 기기에서 구글 지도를 열고 싶다면, 이 코드를 info.plist에 추가하세요
<key>LSApplicationQueriesSchemes</key>
<array>
<string>googlechromes</string>
<string>comgooglemaps</string>
</array>
<key>LSApplicationQueriesSchemes</key>
기타 쿼리의 경우
URL 매개 변수 예제
https://www.google.com/maps/dir/?api=1
&origin=$latitude,$longitude
&destination=$latitude,$longitude
&travelmode=driving
&dir_action=navigate
q= query
saddr = starting point for directions
daddr = destination point for directions
dirflg = The transport type
다음은 최신 LaunchUrl 패키지에서 작동합니다. mode: LaunchMode.externalApplication이 중요합니다. 그렇지 않으면 앱의 내부 브라우저에서 열리지만 원하지 않습니다.
openMap(double lat, double lng) async {
String googleUrl =
'https://www.google.com/maps/search/?api=1&query=$lat,$lng';
if (await canLaunchUrlString(googleUrl)) {
await launchUrlString(googleUrl, mode: LaunchMode.externalApplication);
} else {
throw 'Unable open the map.';
}
}
Include the package: url_launcher: ^6.1.10
use the latest version: https://pub.dev/packages/url_launcher
If you want to open the map in an external app if available on your device, add a launch url property namely LaunchMode. LaunchMode has a few options you can choose from according to your app's needs. LaunchMode options are,
- LaunchMode.platformDefault - This is the default mode and leaves the decision of launch the URL to the platform.
- LaunchMode.inAppWebView - Loads the URL in an in-app webview.
- LaunchMode.externalApplication - Passes the URL to the OS to be handled by another application.
- LaunchMode.externalNonBrowserApplication - Passes the URL to the OS to be handled by another non-browser application
Add url_launcher to your pubspec.yaml file
url_launcher: LATEST_VERSION
Use the given below function,
Future<void> openMap(double latitude, double longitude, {LaunchMode linkLaunchMode = LaunchMode.externalApplication}) async { String googleUrl = 'https://www.google.com/maps/search/?api=1&query=$latitude,$longitude'; if (await canLaunchUrl(Uri.parse(googleUrl))) { await launchUrl(Uri.parse(googleUrl), mode: linkLaunchMode); } else { throw 'Could not open the map.'; } }
- You can see in the above function, the function has default launch mode as an external application so whenever the user clicks on the link it will open in the external google map app.
- You can also customize this function base on your feature requirement.
'개발하자' 카테고리의 다른 글
어떻게 yaml에 의해 비밀 파일을 쿠버네티스 비밀로 설정합니까? (0) | 2023.03.08 |
---|---|
플러터에서 텍스트를 수직 및 수평으로 중앙에 배치하려면 어떻게 해야 합니까? (0) | 2023.03.08 |
pip를 사용하여 설치한 후 "jupyter: 명령을 찾을 수 없습니다 (0) | 2023.03.07 |
테라폼 콘솔에서 로컬 변수 가져오기 (0) | 2023.03.06 |
FastAPI 서버가 "422 unprocessable entity"를 반환함 - value_error.missing (0) | 2023.03.06 |