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

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

ภาพรวม

  1. ผสานรวม Navigation 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 ยังใช้เป็นอีกทางเลือกหนึ่งสำหรับ Fragment ในรูปแบบ NavigationView ได้ด้วย โปรดดูข้อมูลที่ด้านบนของคำอธิบายชั้นเรียน โดยเฉพาะเกี่ยวกับข้อกำหนดในการส่งต่อวิธีการสำหรับวงจรชีวิต

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

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

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

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

    <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. ลบล้างโค้ดเรียกกลับของ 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() เพื่อเริ่มการนำทางเมื่อตัวนำทางพร้อม

    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 กับคอมพิวเตอร์ ทำตามinstructionsเพื่อเปิดใช้ตัวเลือกสำหรับนักพัฒนาซอฟต์แวร์ในอุปกรณ์ Android และกำหนดค่าระบบให้ตรวจหาอุปกรณ์ดังกล่าว (หรือจะใช้ Android Virtual Device Manager (AVD) Manager เพื่อกำหนดค่าอุปกรณ์เสมือนก็ได้) เมื่อเลือกโปรแกรมจำลอง โปรดตรวจสอบว่าคุณได้เลือกอิมเมจที่มี Google APIs)
  2. ใน Android Studio ให้คลิกตัวเลือกเมนูเรียกใช้ (หรือไอคอนปุ่มเล่น) เลือกอุปกรณ์ตามข้อความแจ้ง

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

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