itsource

Android를 통해 Google Maps Directions 실행

mycopycode 2022. 9. 19. 23:42
반응형

Android를 통해 Google Maps Directions 실행

내 앱은 A에서 B로 Google 지도를 표시해야 하는데, 나는 Google 지도를 내 앱에 넣고 싶지 않고, 대신 Intent를 사용하여 실행하고 싶다.이게 가능합니까?만약 그렇다면, 어떻게?

다음과 같은 것을 사용할 수 있습니다.

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
    Uri.parse("http://maps.google.com/maps?saddr=20.344,34.34&daddr=20.5666,45.345"));
startActivity(intent);

하려면 를 합니다.saddr파라미터와 값.

위도와 경도 대신 실제 주소를 사용할 수 있습니다.그러나 브라우저 또는 Google 지도에서 열 수 있는 대화 상자가 나타납니다.

이렇게 하면 Google 지도가 탐색 모드에서 직접 부팅됩니다.

Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
    Uri.parse("google.navigation:q=an+address+city"));

갱신하다

2017년 5월 Google은 범용 크로스 플랫폼 Google Maps URL을 위한 새로운 API를 출시했다.

https://developers.google.com/maps/documentation/urls/guide

새로운 API에서도 Intents를 사용할 수 있습니다.

사용자가 "길찾기"를 요청했기 때문에 약간 주제를 벗어났지만 Android 문서에서 설명된 Geo URI 스킴을 사용할 수도 있습니다.

http://developer.android.com/guide/appendix/g-app-intents.html

"Geo:latitude, landitude"를 사용하는 문제는 Google 지도에서 핀이나 레이블이 없이 사용자의 지점만 가운데에 위치한다는 것입니다.

특히 정확한 장소를 가리켜야 하거나 길을 물어봐야 하는 경우에는 매우 혼란스럽습니다.

쿼리 파라미터 "syslog:lat,lon?q=name"을 사용하여 지오포인트에 라벨을 붙이면 검색에 쿼리를 사용하여 lat/lon 파라미터를 해제합니다.

지도를 lat/lon 중앙에 배치하고 커스텀 라벨이 붙어 있는 핀을 표시하는 방법을 찾았습니다.이 핀은 표시하기에 매우 편리하고 길 안내나 기타 조작을 요구할 때 편리합니다.

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
Uri.parse("geo:0,0?q=37.423156,-122.084917 (" + name + ")"));
startActivity(intent);

메모(@The Nail 기준):Maps v.7에서는 동작하지 않습니다(작성 시의 최신 버전).좌표를 무시하고 괄호 사이에 지정된 이름을 가진 객체를 검색합니다.위치가 포함된 Google 지도 7.0.0에 대한 의도도 참조하십시오.

현재의 답변은 훌륭하지만, 어느 것도 내가 찾던 것을 하지 않고, 맵 앱만 열고, 소스 위치 및 수신처의 이름을 추가하고, Geo URI 스킴을 사용하는 것은 나에게 전혀 효과가 없고, 맵 웹 링크에는 라벨이 없기 때문에, 이 솔루션을 생각해 냈습니다.그것은 본질적으로 합병입니다.다른 솔루션이나 코멘트가 있으면, 이 질문을 보는 사람에게 도움이 될 것입니다.

String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?saddr=%f,%f(%s)&daddr=%f,%f (%s)", sourceLatitude, sourceLongitude, "Home Sweet Home", destinationLatitude, destinationLongitude, "Where the party is at");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);

현재 위치를 출발점으로 사용하려면(유감스럽게도 현재 위치에 레이블을 붙일 방법을 찾지 못했습니다) 다음을 사용하십시오.

String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?daddr=%f,%f (%s)", destinationLatitude, destinationLongitude, "Where the party is at");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);

완전성을 위해 사용자가 지도 앱을 설치하지 않은 경우 ActivityNotFoundException을 잡는 것이 좋습니다.그러면 지도 앱 제한 없이 작업을 다시 시작할 수 있습니다.인터넷 브라우저는 이 url sc를 시작하는 데 유효한 어플리케이션이기 때문에 Toast에 접속할 수 없습니다.헤임도.

        String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?daddr=%f,%f (%s)", 12f, 2f, "Where the party is at");
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
        intent.setPackage("com.google.android.apps.maps");
        try
        {
            startActivity(intent);
        }
        catch(ActivityNotFoundException ex)
        {
            try
            {
                Intent unrestrictedIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                startActivity(unrestrictedIntent);
            }
            catch(ActivityNotFoundException innerEx)
            {
                Toast.makeText(this, "Please install a maps application", Toast.LENGTH_LONG).show();
            }
        }

추신. 제 예에서 사용된 위도나 경도는 제 위치를 대표하지 않습니다. 실제 위치와 유사하다는 것은 순전히 우연의 일치입니다. 일명 저는 아프리카 출신이 아닙니다.p

편집:

길 안내에 대해서는 이제 Google.Navigation에서 내비게이션이 지원됩니다.

Uri navigationIntentUri = Uri.parse("google.navigation:q=" + 12f +"," + 2f);//creating intent with latlng
Intent mapIntent = new Intent(Intent.ACTION_VIEW, navigationIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);

최신 크로스 플랫폼 구글 지도 URL 사용 : 구글 지도 앱이 없어도 브라우저에서 열립니다.

예: https://www.google.com/maps/dir/?api=1&destination=81.2344,67.0000&destination=80.252059,13.0604

Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
    .authority("www.google.com")
    .appendPath("maps")
    .appendPath("dir")
    .appendPath("")
    .appendQueryParameter("api", "1")
    .appendQueryParameter("destination", 80.00023 + "," + 13.0783);
String url = builder.build().toString();
Log.d("Directions", url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

다양한 모드에서 Intent를 사용하여 Google 지도를 엽니다.

Google 지도 앱은 intent를 사용하여 열 수 있습니다.

val gmmIntentUri = Uri.parse("google.navigation:q="+destintationLatitude+","+destintationLongitude + "&mode=b")
val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
mapIntent.setPackage("com.google.android.apps.maps")
startActivity(mapIntent)

여기서 "mode=b"는 자전거용입니다.

다음을 사용하여 운전, 걷기 및 자전거 모드를 설정할 수 있습니다.

  • 운전용 d
  • w 산책용
  • 자전거용 b

Google 지도에서 의도에 대한 자세한 내용을 확인할 수 있습니다.

참고: 자전거/자동차/도보로 가는 경로가 없는 경우 "길을 찾을 수 없습니다"라고 표시됩니다.

제 원래 답변은 이쪽에서 확인하실 수 있습니다.

인 Android 를 'Android Maps'에서 .Intent.setClassName★★★★★★ 。

Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse("geo:37.827500,-122.481670"));
i.setClassName("com.google.android.apps.maps",
    "com.google.android.maps.MapsActivity");
startActivity(i);

다중 웨이 포인트의 경우 다음 항목도 사용할 수 있습니다.

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
    Uri.parse("https://www.google.com/maps/dir/48.8276261,2.3350114/48.8476794,2.340595/48.8550395,2.300022/48.8417122,2.3028844"));
startActivity(intent);

첫 번째 좌표 집합이 시작 위치입니다.다음은 모두 경유지이며 표시된 경로가 통과합니다.

끝부분에 "/latitude, latitude"를 넣어서 중간점을 계속 추가하세요.구글 문서에 따르면 23개의 경유지 제한이 있는 것 같습니다.그것이 안드로이드에도 적용되는지는 잘 모르겠습니다.

lakshman sai가 언급한 최신 크로스 플랫폼 답변을 사용한 멋진 코틀린 솔루션...

단, 불필요한 URI.toString 및 URI.parse는 없습니다.이 답변은 깨끗하고 최소입니다.

 val intentUri = Uri.Builder().apply {
      scheme("https")
      authority("www.google.com")
      appendPath("maps")
      appendPath("dir")
      appendPath("")
      appendQueryParameter("api", "1")
      appendQueryParameter("destination", "${yourLocation.latitude},${yourLocation.longitude}")
 }.build()
 startActivity(Intent(Intent.ACTION_VIEW).apply {
      data = intentUri
 })

현재 방향에서 위도와 경도를 표시하는 경우 다음을 사용할 수 있습니다.

사용자의 현재 위치에서 항상 지시가 제공됩니다.

다음 쿼리는 이를 수행하는 데 도움이 됩니다.목적지의 위도와 경도를 전달할 수 있습니다.

google.navigation:q=latitude,longitude

위의 용도:

Uri gmmIntentUri = Uri.parse("google.navigation:q=latitude,longitude");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);

또는 로케이션 경유로 표시하는 경우는, 다음과 같이 합니다.

google.navigation:q=a+street+address

자세한 내용은 이쪽: Android용 Google 지도 정보

HMS가 포함된 HUWAI 기기에 있는 지도 앱을 엽니다.

const val GOOGLE_MAPS_APP = "com.google.android.apps.maps"
const val HUAWEI_MAPS_APP = "com.huawei.maps.app"

    fun openMap(lat:Double,lon:Double) {
    val packName = if (isHmsOnly(context)) {
        HUAWEI_MAPS_APP
    } else {
        GOOGLE_MAPS_APP
    }

        val uri = Uri.parse("geo:$lat,$lon?q=$lat,$lon")
        val intent = Intent(Intent.ACTION_VIEW, uri)
        intent.setPackage(packName);
        if (intent.resolveActivity(context.packageManager) != null) {
            context.startActivity(intent)
        } else {
            openMapOptions(lat, lon)
        }
}

private fun openMapOptions(lat: Double, lon: Double) {
    val intent = Intent(
        Intent.ACTION_VIEW,
        Uri.parse("geo:$lat,$lon?q=$lat,$lon")
    )
    context.startActivity(intent)
}

HMS 체크:

private fun isHmsAvailable(context: Context?): Boolean {
var isAvailable = false
if (null != context) {
    val result =
        HuaweiApiAvailability.getInstance().isHuaweiMobileServicesAvailable(context)
    isAvailable = ConnectionResult.SUCCESS == result
}
return isAvailable}

private fun isGmsAvailable(context: Context?): Boolean {
    var isAvailable = false
    if (null != context) {
        val result: Int = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)
        isAvailable = com.google.android.gms.common.ConnectionResult.SUCCESS == result
    }
    return isAvailable }

fun isHmsOnly(context: Context?) = isHmsAvailable(context) && !isGmsAvailable(context)

이것이 나에게 효과가 있었다.

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://maps.google.co.in/maps?q=" + yourAddress));
if (intent.resolveActivity(getPackageManager()) != null) {
   startActivity(intent);
}

이거 먹어봐

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr="+src_lat+","+src_ltg+"&daddr="+des_lat+","+des_ltg));
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);

구글DirectionsView송신원 로케이션을 현재 로케이션으로, 행선지 로케이션을 문자열로 지정합니다.

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?f=d&daddr="+destinationCityName));
intent.setComponent(new ComponentName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity"));
if (intent.resolveActivity(getPackageManager()) != null) {
    startActivity(intent);
}

상기의 경우destinationCityName는 필요에 따라 변경할 수 있는 문자열입니다.

점 A, 점 B(및 그 사이에 있는 기능이나 트랙)를 알고 있는 경우는, 목적과 함께 KML 파일을 사용할 수 있습니다.

String kmlWebAddress = "http://www.afischer-online.de/sos/AFTrack/tracks/e1/01.24.Soltau2Wietzendorf.kml";
String uri = String.format(Locale.ENGLISH, "geo:0,0?q=%s",kmlWebAddress);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);

자세한 내용은 이 SO 답변을 참조하십시오.

메모: 이 예에서는 (3월 13일 현재) 아직 온라인 상태인 샘플파일을 사용하고 있습니다.오프라인으로 전환된 경우 온라인으로 kml 파일을 찾아 URL을 변경합니다.

먼저 암묵적인 의도를 사용할 수 있으므로 Android 문서에서는 2개의 파라미터로 새로운 의도를 작성하기 위해 필요한 맵 의도를 구현하기 위한 매우 상세한 공통 의도를 제공합니다.

  • 액션.
  • URI

액션에 사용할 수 있습니다.Intent.ACTION_VIEW그리고 URI의 경우 아래에 액티비티를 작성, 구축, 시작하기 위한 샘플 코드를 첨부합니다.

 String addressString = "1600 Amphitheatre Parkway, CA";

    /*
    Build the uri 
     */
    Uri.Builder builder = new Uri.Builder();
    builder.scheme("geo")
            .path("0,0")
            .query(addressString);
    Uri addressUri = builder.build();
    /*
    Intent to open the map
     */
    Intent intent = new Intent(Intent.ACTION_VIEW, addressUri);

    /*
    verify if the devise can launch the map intent
     */
    if (intent.resolveActivity(getPackageManager()) != null) {
       /*
       launch the intent
        */
        startActivity(intent);
    }

이 방법을 통해 Android를 통해 Google 지도 길잡이를 시작할 수 있습니다.

btn_search_route.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String source = et_source.getText().toString();
            String destination = et_destination.getText().toString();

            if (TextUtils.isEmpty(source)) {
                et_source.setError("Enter Soruce point");
            } else if (TextUtils.isEmpty(destination)) {
                et_destination.setError("Enter Destination Point");
            } else {
                String sendstring="http://maps.google.com/maps?saddr=" +
                        source +
                        "&daddr=" +
                        destination;
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse(sendstring));
                startActivity(intent);
            }
        }

    });

업데이트된 목적의 Google 지도 주소 위치를 사용해 보십시오.

 Uri gmmIntentUri1 = Uri.parse("geo:0,0?q=" + Uri.encode(address));
    Intent mapIntent1 = new Intent(Intent.ACTION_VIEW, gmmIntentUri1);
    mapIntent1.setPackage("com.google.android.apps.maps");
    startActivity(mapIntent1);

언급URL : https://stackoverflow.com/questions/2662531/launching-google-maps-directions-via-an-intent-on-android

반응형