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

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

ภาพรวม

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

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

ดูรหัส

เพิ่ม Fragment การนำทาง

SupportNavigationFragment เป็นคอมโพเนนต์ UI ที่แสดงเอาต์พุตภาพของการนำทาง ซึ่งรวมถึงแผนที่แบบอินเทอร์แอกทีฟและ เส้นทางแบบเลี้ยวต่อเลี้ยว คุณสามารถประกาศ Fragment ในไฟล์เลย์เอาต์ 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"/>

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

นอกจาก Fragment แล้ว คอมโพเนนต์ UI ยังมีให้ใช้งานในรูปแบบ NavigationView ด้วย ในกรณีส่วนใหญ่ เราขอแนะนำให้ใช้ SupportNavigationFragment, ซึ่งเป็น Wrapper สำหรับ NavigationView, แทนการโต้ตอบกับ 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() เพื่อเริ่มการนำทางเมื่อ Navigator พร้อมใช้งาน

        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. ตั้งจุดแวะพักได้สูงสุด 25 แห่งสำหรับการเดินทางนี้ หลังจากคำนวณเส้นทางแล้ว 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).
                                    AudioGuidanceSettings audioSettings =
                                            AudioGuidanceSettings.builder()
                                                    .setGuidanceMode(
                                                            AudioGuidanceSettings.GuidanceMode
                                                                    .VOICE_ALERTS_AND_GUIDANCE)
                                                    .build();
                                    mNavigator.setAudioGuidanceSettings(audioSettings);
    
                                    // 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 และกำหนดค่าระบบให้ตรวจหาอุปกรณ์ (หรือคุณจะใช้ ใช้ Android Virtual Device (AVD) Manager เพื่อกำหนดค่าอุปกรณ์เสมือน Android ก็ได้ เมื่อเลือกโปรแกรมจำลอง ให้เลือกอิมเมจที่มี Google API)
  2. ใน Android Studio ให้คลิกตัวเลือกเมนูเรียกใช้ (หรือไอคอนปุ่มเล่น) เลือกอุปกรณ์ตามที่ระบบแจ้ง

เคล็ดลับในการปรับปรุงประสบการณ์ของผู้ใช้

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

  • ใช้เครื่องมือค้นหารหัสสถานที่เพื่อรับรหัสสถานที่สำหรับสถานที่ที่เฉพาะเจาะจง

  • ใช้ Geocoding API เพื่อค้นหารหัสสถานที่ สำหรับที่อยู่ที่ระบุ Geocoding API จะทำงานได้ดีหากคุณมี ที่อยู่ที่สมบูรณ์และไม่กำกวมสำหรับจุดแวะพัก ดูคำแนะนำแนวทางปฏิบัติแนะนำในการเข้ารหัสพิกัดภูมิศาสตร์

  • ใช้การค้นหาข้อความ Places API เพื่อค้นหารหัสสถานที่ สำหรับที่อยู่ที่ระบุ Places API จะทำงานได้ดีหากคุณมีที่อยู่ที่ไม่สมบูรณ์หรือกำกวมสำหรับจุดแวะพัก ดูคำแนะนำแนวทางปฏิบัติแนะนำในการเข้ารหัสพิกัดภูมิศาสตร์