กําหนดเส้นทางสําหรับหลายปลายทาง

ทำตามคู่มือนี้เพื่อวางแผนเส้นทางภายในแอปไปยังหลายปลายทาง หรือที่เรียกว่าจุดอ้างอิง โดยใช้ Navigation SDK สำหรับ Android

ภาพรวม

  1. ผสานรวม SDK การนำทางในแอปของคุณ ที่อธิบายไว้ในหัวข้อตั้งค่าโปรเจ็กต์
  2. เพิ่ม SupportNavigationFragment หรือ NavigationView ไปยังแอปของคุณ องค์ประกอบ UI นี้ เพิ่มแผนที่แบบอินเทอร์แอกทีฟและ UI การนำทางแบบเลี้ยวต่อเลี้ยวลงในกิจกรรมของคุณ
  3. ใช้คลาส NavigationApi เพื่อเริ่มต้นใช้งาน SDK
  4. กำหนด Navigator เพื่อควบคุมการนำทางแบบเลี้ยวต่อเลี้ยว ดังนี้

    • เพิ่มปลายทางโดยใช้ setDestinations()
    • เริ่มนำทางด้วย startGuidance()
    • ใช้ getSimulator() เพื่อจำลองความคืบหน้าของฟิลด์ ยานพาหนะตามเส้นทาง เพื่อทดสอบ แก้ไขข้อบกพร่อง และแสดงให้เห็น แอป
  5. สร้างและเรียกใช้แอป

ดูโค้ด

เพิ่มส่วนย่อยการนำทาง

SupportNavigationFragment คือคอมโพเนนต์ UI ที่แสดง การแสดงผลภาพของการนำทาง ซึ่งรวมถึงแผนที่แบบอินเทอร์แอคทีฟและแบบเลี้ยวต่อเลี้ยว เส้นทาง คุณประกาศส่วนย่อยในไฟล์เลย์เอาต์ XML ได้ดังที่แสดงด้านล่าง

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:name="com.google.android.libraries.navigation.SupportNavigationFragment"
    android:id="@+id/navigation_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

หรือคุณจะสร้างส่วนย่อยแบบเป็นโปรแกรมก็ได้ ตามที่อธิบายไว้ใน เอกสารประกอบของ Android โดยใช้ FragmentActivity.getSupportFragmentManager()

นอกจากส่วนย่อยแล้ว คอมโพเนนต์ UI ยังทำหน้าที่เป็น NavigationView โปรดทราบว่าข้อมูลที่ด้านบนของ คำอธิบายชั้นเรียน โดยเฉพาะอย่างยิ่งเกี่ยวกับข้อกำหนดในการส่งต่อวงจร

ขอสิทธิ์เข้าถึงตำแหน่ง

แอปของคุณต้องขอสิทธิ์เข้าถึงตำแหน่งเพื่อระบุ ตำแหน่งของอุปกรณ์

บทแนะนำนี้มีโค้ดที่คุณต้องขอสิทธิ์เข้าถึงตำแหน่งอย่างละเอียด โปรดดูรายละเอียดเพิ่มเติมในคำแนะนำเกี่ยวกับสิทธิ์ของ Android

  1. เพิ่มสิทธิ์เป็นองค์ประกอบย่อยขององค์ประกอบ <manifest> ใน Android ไฟล์ Manifest:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.navsdkmultidestination">
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    </manifest>
    
  2. ขอสิทธิ์รันไทม์ในแอปเพื่อให้ผู้ใช้มีโอกาส เพื่ออนุญาตหรือปฏิเสธสิทธิ์เข้าถึงตำแหน่ง โค้ดต่อไปนี้จะตรวจสอบว่า ผู้ใช้ ได้ให้สิทธิ์เข้าถึงตำแหน่งโดยละเอียด ไม่เช่นนั้น ระบบจะขอสิทธิ์ต่อไปนี้

    if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
            android.Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
        mLocationPermissionGranted = true;
    } else {
        ActivityCompat.requestPermissions(this,
                new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION },
                PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
    }
    
    if (!mLocationPermissionGranted) {
        displayMessage("Error loading Navigation SDK: "
                + "The user has not granted location permission.", DISPLAY_BOTH);
        return;
    }
    
  3. ลบล้าง Callback ของ onRequestPermissionsResult() เพื่อจัดการผลลัพธ์ของ คำขอสิทธิ์:

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        mLocationPermissionGranted = false;
        switch (requestCode) {
            case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
                // If request is canceled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mLocationPermissionGranted = true;
                }
            }
        }
    }
    

เริ่มต้น Navigation SDK และกำหนดค่าเส้นทาง

คลาส NavigationApi จะมีตรรกะการเริ่มต้น ที่อนุญาตให้แอปของคุณใช้การนำทางของ Google Navigator คลาสจะให้การควบคุมการกำหนดค่าและการเริ่ม/หยุดการนำทาง

  1. สร้างเมธอดตัวช่วยเพื่อแสดงข้อความบนหน้าจอและในบันทึก

    private void displayMessage(String errorMessage, String displayMedium) {
        if (displayMedium.equals(DISPLAY_BOTH) || displayMedium.equals(DISPLAY_TOAST)) {
            Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
        }
    
        if (displayMedium.equals(DISPLAY_BOTH) || displayMedium.equals(DISPLAY_LOG)) {
            Log.d(TAG, errorMessage);
        }
    }
    
  2. เริ่มต้น Navigation SDK และลบล้าง onNavigatorReady() Callback เพื่อเริ่มการนำทางเมื่อตัวนำทางคือ พร้อมแล้ว:

    NavigationApi.getNavigator(this, new NavigationApi.NavigatorListener() {
                /**
                 * Sets up the navigation UI when the navigator is ready for use.
                 */
                @Override
                public void onNavigatorReady(Navigator navigator) {
                    displayMessage("Navigator ready.", DISPLAY_BOTH);
                    mNavigator = navigator;
                    mNavFragment = (SupportNavigationFragment) getFragmentManager()
                            .findFragmentById(R.id.navigation_fragment);
    
                    // Set the camera to follow the device location with 'TILTED' driving view.
                    mNavFragment.getCamera().followMyLocation(Camera.Perspective.TILTED);
    
                    // Navigate to the specified places.
                    navigateToPlaces();
                }
    
                /**
                 * Handles errors from the Navigation SDK.
                 * @param errorCode The error code returned by the navigator.
                 */
                @Override
                public void onError(@NavigationApi.ErrorCode int errorCode) {
                    switch (errorCode) {
                        case NavigationApi.ErrorCode.NOT_AUTHORIZED:
                            displayMessage("Error loading Navigation SDK: Your API key is "
                                    + "invalid or not authorized to use the Navigation SDK.",
                                    DISPLAY_BOTH);
                            break;
                        case NavigationApi.ErrorCode.TERMS_NOT_ACCEPTED:
                            displayMessage("Error loading Navigation SDK: User did not accept "
                                    + "the Navigation Terms of Use.", DISPLAY_BOTH);
                            break;
                        case NavigationApi.ErrorCode.NETWORK_ERROR:
                            displayMessage("Error loading Navigation SDK: Network error.",
                                    DISPLAY_BOTH);
                            break;
                        case NavigationApi.ErrorCode.LOCATION_PERMISSION_MISSING:
                            displayMessage("Error loading Navigation SDK: Location permission "
                                    + "is missing.", DISPLAY_BOTH);
                            break;
                        default:
                            displayMessage("Error loading Navigation SDK: " + errorCode,
                                    DISPLAY_BOTH);
                    }
                }
            });
    
  3. เพิ่มวิธีสร้างออบเจ็กต์ Waypoint จากสถานที่ที่ระบุ รหัสและชื่อ

    private void createWaypoint(String placeId, String title) {
        try {
            mWaypoints.add(
              Waypoint.builder()
                     .setPlaceIdString(placeId)
                     .setTitle(title)
                     .build()
            );
        } catch (Waypoint.UnsupportedPlaceIdException e) {
            displayMessage("Error starting navigation: Place ID is not supported: " + placeId,
                    DISPLAY_BOTH);
        }
    }
    
  4. เพิ่มวิธีเพื่อแสดงเวลาในการเดินทางและระยะทางที่คำนวณไว้สำหรับแต่ละวิธี จุดอ้างอิง

    private void displayTimesAndDistances() {
        List<TimeAndDistance> timesAndDistances = mNavigator.getTimeAndDistanceList();
        int leg = 1;
        String message = "You're on your way!";
        for (TimeAndDistance timeAndDistance : timesAndDistances) {
            message = message + "\nRoute leg: " + leg++
                    + ": Travel time (seconds): " + timeAndDistance.getSeconds()
                    + ". Distance (meters): " + timeAndDistance.getMeters();
        }
        displayMessage(message, DISPLAY_BOTH);
    }
    
  5. กำหนดจุดอ้างอิงทั้งหมดสำหรับการเดินทางนี้ (โปรดทราบว่าคุณอาจได้รับข้อผิดพลาด ถ้าคุณใช้รหัสสถานที่ที่ตัวนำทางไม่สามารถวางแผนเส้นทางได้ ตัวอย่าง แอปในบทแนะนำนี้ใช้รหัสสถานที่สำหรับจุดอ้างอิงในออสเตรเลีย ดูหมายเหตุ ด้านล่างเกี่ยวกับการรับรหัสสถานที่ที่ต่างกัน) หลังจากคำนวณแล้ว เส้น SupportNavigationFragment จะแสดงเส้นประกอบ ซึ่งแสดงเส้นทางบนแผนที่ โดยมีเครื่องหมายบอกตำแหน่งแต่ละจุด

    private void navigateToPlaces() {
    
        // Set up a waypoint for each place that we want to go to.
        createWaypoint("ChIJq6qq6jauEmsRJAf7FjrKnXI", "Sydney Star");
        createWaypoint("ChIJ3S-JXmauEmsRUcIaWtf4MzE", "Sydney Opera House");
        createWaypoint("ChIJLwgLFGmuEmsRzpDhHQuyyoU", "Sydney Conservatorium of Music");
    
        // If this journey is already in progress, no need to restart navigation.
        // This can happen when the user rotates the device, or sends the app to the background.
        if (mSavedInstanceState != null
                && mSavedInstanceState.containsKey(KEY_JOURNEY_IN_PROGRESS)
                && mSavedInstanceState.getInt(KEY_JOURNEY_IN_PROGRESS) == 1) {
            return;
        }
    
        // Create a future to await the result of the asynchronous navigator task.
        ListenableResultFuture<Navigator.RouteStatus> pendingRoute =
                mNavigator.setDestinations(mWaypoints);
    
        // Define the action to perform when the SDK has determined the route.
        pendingRoute.setOnResultListener(
                new ListenableResultFuture.OnResultListener<Navigator.RouteStatus>() {
                    @Override
                    public void onResult(Navigator.RouteStatus code) {
                        switch (code) {
                            case OK:
                                mJourneyInProgress = true;
                                // Hide the toolbar to maximize the navigation UI.
                                if (getActionBar() != null) {
                                    getActionBar().hide();
                                }
    
                                // Register some listeners for navigation events.
                                registerNavigationListeners();
    
                                // Display the time and distance to each waypoint.
                                displayTimesAndDistances();
    
                                // Enable voice audio guidance (through the device speaker).
                                mNavigator.setAudioGuidance(
                                        Navigator.AudioGuidance.VOICE_ALERTS_AND_GUIDANCE);
    
                                // Simulate vehicle progress along the route for demo/debug builds.
                                if (BuildConfig.DEBUG) {
                                    mNavigator.getSimulator().simulateLocationsAlongExistingRoute(
                                            new SimulationOptions().speedMultiplier(5));
                                }
    
                                // Start turn-by-turn guidance along the current route.
                                mNavigator.startGuidance();
                                break;
                            // Handle error conditions returned by the navigator.
                            case NO_ROUTE_FOUND:
                                displayMessage("Error starting navigation: No route found.",
                                        DISPLAY_BOTH);
                                break;
                            case NETWORK_ERROR:
                                displayMessage("Error starting navigation: Network error.",
                                        DISPLAY_BOTH);
                                break;
                            case ROUTE_CANCELED:
                                displayMessage("Error starting navigation: Route canceled.",
                                        DISPLAY_BOTH);
                                break;
                            default:
                                displayMessage("Error starting navigation: "
                                        + String.valueOf(code), DISPLAY_BOTH);
                        }
                    }
                });
    }
    

สร้างและเรียกใช้แอป

  1. เชื่อมต่ออุปกรณ์ Android กับคอมพิวเตอร์ ทำตาม วิธีการเปิดใช้ตัวเลือกของนักพัฒนาซอฟต์แวร์บน Android ของคุณ อุปกรณ์และกำหนดค่าระบบให้ตรวจหาอุปกรณ์ (หรือคุณสามารถ ให้ใช้ โปรแกรมจัดการอุปกรณ์เสมือน (AVD) ของ Android เพื่อกำหนดค่าระบบเสมือน อุปกรณ์ เมื่อเลือกโปรแกรมจำลอง โปรดเลือกรูปภาพที่มี Google API)
  2. ใน Android Studio ให้คลิกตัวเลือกเมนูเรียกใช้ (หรือไอคอนปุ่มเล่น) เลือกอุปกรณ์ตามข้อความแจ้ง

คำแนะนำเพื่อประสบการณ์ของผู้ใช้ที่ดีขึ้น

  • ผู้ใช้ต้องยอมรับข้อกำหนดในการให้บริการของ Google การนำทางก่อน การนำทางพร้อมใช้งาน การยอมรับนี้ทำเพียงครั้งเดียว โดย ค่าเริ่มต้น SDK จะแสดงข้อความให้ยอมรับในครั้งแรกที่ตัวนำทาง ที่เรียกใช้ หากต้องการ คุณสามารถเรียกใช้กล่องโต้ตอบข้อกำหนดในการให้บริการของการนำทางได้ ในช่วงแรกของขั้นตอน UX ของแอป เช่น ระหว่างการลงชื่อสมัครใช้หรือการเข้าสู่ระบบ showTermsAndConditionsDialog()
  • คุณภาพของการนำทางและความแม่นยำของเวลาถึงโดยประมาณจะได้รับการปรับปรุงให้ดีขึ้นอย่างมากหากคุณใช้ รหัสตำแหน่งเพื่อเริ่มต้นการชี้ทางแทนที่จะเป็นละติจูด/ลองจิจูด ปลายทาง
  • ตัวอย่างนี้ได้จุดอ้างอิงจากสถานที่ที่เฉพาะเจาะจง รหัส วิธีอื่นๆ ในการรับรหัสสถานที่มีดังนี้