Location Data

Một trong những tính năng độc đáo của ứng dụng dành cho thiết bị di động là nhận biết vị trí. Người dùng thiết bị di động mang theo thiết bị bên mình đi khắp mọi nơi và thêm vị trí cho ứng dụng của bạn nhằm cung cấp cho người dùng trải nghiệm theo bối cảnh cụ thể hơn.

Mã mẫu

Kho lưu trữ Apidemos trên GitHub bao gồm mẫu minh hoạ công dụng của vị trí trên bản đồ:

Kotlin

Java

Làm việc với dữ liệu vị trí

Dữ liệu vị trí mà thiết bị Android có thể sử dụng bao gồm cả thông tin vị trí hiện tại của thiết bị — được xác định chính xác bằng cách sử dụng kết hợp các công nghệ — hướng và phương pháp di chuyển cũng như liệu thiết bị có di chuyển qua không ranh giới địa lý hoặc khoanh vùng địa lý được xác định trước. Tuỳ thuộc vào nhu cầu của ứng dụng của mình, bạn có thể chọn trong số một số cách làm việc với thông tin vị trí dữ liệu:

  • Lớp Vị trí của tôi cung cấp một cách đơn giản để hiển thị vị trí trên bản đồ. Tài sản này không cung cấp dữ liệu.
  • API Vị trí của Dịch vụ Google Play được đề xuất cho tất cả các yêu cầu có lập trình cho dữ liệu vị trí.
  • Giao diện LocationSource cho phép bạn cung cấp trình cung cấp vị trí tuỳ chỉnh.

Quyền truy cập vị trí

Nếu ứng dụng của bạn cần truy cập vào thông tin vị trí của người dùng, bạn phải yêu cầu quyền trước thêm quyền truy cập thông tin vị trí liên quan trên Android vào ứng dụng của bạn.

Android cung cấp hai quyền truy cập thông tin vị trí: ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATION Quyền bạn chọn sẽ xác định độ chính xác của vị trí được API trả về.

  • android.permission.ACCESS_COARSE_LOCATION – Cho phép API trả về vị trí ước chừng của thiết bị. Chiến lược phát hành đĩa đơn sẽ cung cấp thông tin ước đoán về vị trí của thiết bị dựa trên các dịch vụ vị trí, chẳng hạn như được mô tả trong tài liệu về vị trí ước chừng .
  • android.permission.ACCESS_FINE_LOCATION – Cho phép API xác định vị trí chính xác nhất có thể từ nhà cung cấp vị trí có sẵn, bao gồm Hệ thống định vị toàn cầu (GPS) cũng như Wi-Fi và dữ liệu di động.

Thêm quyền vào tệp kê khai ứng dụng

Nếu ứng dụng của bạn chỉ cần thông tin vị trí ước chừng để hoạt động, hãy thêm thuộc tính Quyền ACCESS_COARSE_LOCATION đối với tệp kê khai của ứng dụng:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp" >
  ...
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  ...
</manifest>

Tuy nhiên, nếu cần vị trí chính xác, hãy thêm cả ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATION vào tệp kê khai của ứng dụng:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp" >
  ...
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  ...
</manifest>

Yêu cầu quyền khi bắt đầu chạy

Android 6.0 (Marshmallow) giới thiệu một mô hình mới để xử lý quyền Đơn giản hoá quy trình cho người dùng khi họ cài đặt và nâng cấp ứng dụng. Nếu ứng dụng nhắm đến API cấp 23 trở lên, thì bạn có thể sử dụng mô hình quản lý quyền mới.

Nếu ứng dụng của bạn hỗ trợ mô hình quản lý quyền mới và thiết bị đang chạy Android 6.0 (Marshmallow) trở lên, người dùng không cần phải cấp bất kỳ quyền nào khi cài đặt hoặc nâng cấp ứng dụng. Ứng dụng phải kiểm tra xem có quyền cần thiết trong thời gian chạy và yêu cầu quyền đó nếu có chưa có. Hệ thống sẽ hiển thị hộp thoại để người dùng yêu cầu cấp quyền.

Để người dùng có trải nghiệm tốt nhất, bạn cần yêu cầu cấp quyền theo bối cảnh. Nếu thông tin vị trí là yếu tố thiết yếu đối với hoạt động của ứng dụng, thì bạn nên yêu cầu quyền truy cập thông tin vị trí khi khởi động ứng dụng. Một cách hay để làm việc này là dùng màn hình chào mừng hoặc trình hướng dẫn để cho người dùng biết lý do yêu cầu quyền là bắt buộc.

Nếu ứng dụng chỉ yêu cầu quyền cho một phần chức năng của ứng dụng, thì bạn phải yêu cầu quyền truy cập thông tin vị trí tại thời điểm ứng dụng thực hiện hành động yêu cầu quyền đó.

Ứng dụng phải xử lý linh hoạt trường hợp người dùng không cấp quyền quyền. Ví dụ: nếu quyền đó là cần thiết cho một tính năng cụ thể, có thể tắt tính năng đó. Nếu quyền này cần thiết để ứng dụng chức năng của ứng dụng, ứng dụng có thể vô hiệu hoá tất cả chức năng của nó và cho người dùng biết rằng họ cần cấp quyền.

Mã mẫu sau đây sẽ kiểm tra quyền bằng thư viện AndroidX trước khi bật lớp Vị trí của tôi. Sau đó, phương thức này xử lý kết quả của bằng cách triển khai ActivityCompat.OnRequestPermissionsResultCallback trong Thư viện hỗ trợ:

Kotlin

// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.example.kotlindemos

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback
import androidx.core.content.ContextCompat
import com.example.kotlindemos.PermissionUtils.PermissionDeniedDialog.Companion.newInstance
import com.example.kotlindemos.PermissionUtils.isPermissionGranted
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener
import com.google.android.gms.maps.GoogleMap.OnMyLocationClickListener
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment

/**
 * This demo shows how GMS Location can be used to check for changes to the users location.  The
 * "My Location" button uses GMS Location to set the blue dot representing the users location.
 * Permission for [Manifest.permission.ACCESS_FINE_LOCATION] and [Manifest.permission.ACCESS_COARSE_LOCATION]
 * are requested at run time. If either permission is not granted, the Activity is finished with an error message.
 */
class MyLocationDemoActivity : AppCompatActivity(),
    OnMyLocationButtonClickListener,
    OnMyLocationClickListener, OnMapReadyCallback,
    OnRequestPermissionsResultCallback {
    /**
     * Flag indicating whether a requested permission has been denied after returning in
     * [.onRequestPermissionsResult].
     */
    private var permissionDenied = false
    private lateinit var map: GoogleMap
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.my_location_demo)
        val mapFragment =
            supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
        mapFragment?.getMapAsync(this)
    }

    override fun onMapReady(googleMap: GoogleMap) {
        map = googleMap
        googleMap.setOnMyLocationButtonClickListener(this)
        googleMap.setOnMyLocationClickListener(this)
        enableMyLocation()
    }

    /**
     * Enables the My Location layer if the fine location permission has been granted.
     */
    @SuppressLint("MissingPermission")
    private fun enableMyLocation() {

        // 1. Check if permissions are granted, if so, enable the my location layer
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            map.isMyLocationEnabled = true
            return
        }

        // 2. If if a permission rationale dialog should be shown
        if (ActivityCompat.shouldShowRequestPermissionRationale(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) || ActivityCompat.shouldShowRequestPermissionRationale(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
        ) {
            PermissionUtils.RationaleDialog.newInstance(
                LOCATION_PERMISSION_REQUEST_CODE, true
            ).show(supportFragmentManager, "dialog")
            return
        }

        // 3. Otherwise, request permission
        ActivityCompat.requestPermissions(
            this,
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ),
            LOCATION_PERMISSION_REQUEST_CODE
        )
    }

    override fun onMyLocationButtonClick(): Boolean {
        Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT)
            .show()
        // Return false so that we don't consume the event and the default behavior still occurs
        // (the camera animates to the user's current position).
        return false
    }

    override fun onMyLocationClick(location: Location) {
        Toast.makeText(this, "Current location:\n$location", Toast.LENGTH_LONG)
            .show()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
            super.onRequestPermissionsResult(
                requestCode,
                permissions,
                grantResults
            )
            return
        }

        if (isPermissionGranted(
                permissions,
                grantResults,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) || isPermissionGranted(
                permissions,
                grantResults,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
        ) {
            // Enable the my location layer if the permission has been granted.
            enableMyLocation()
        } else {
            // Permission was denied. Display an error message
            // Display the missing permission error dialog when the fragments resume.
            permissionDenied = true
        }
    }

    override fun onResumeFragments() {
        super.onResumeFragments()
        if (permissionDenied) {
            // Permission was not granted, display error dialog.
            showMissingPermissionError()
            permissionDenied = false
        }
    }

    /**
     * Displays a dialog with error message explaining that the location permission is missing.
     */
    private fun showMissingPermissionError() {
        newInstance(true).show(supportFragmentManager, "dialog")
    }

    companion object {
        /**
         * Request code for location permission request.
         *
         * @see .onRequestPermissionsResult
         */
        private const val LOCATION_PERMISSION_REQUEST_CODE = 1
    }
}

Java

// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.


package com.example.mapdemo;

import android.Manifest.permission;
import android.annotation.SuppressLint;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationClickListener;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.widget.Toast;

/**
 * This demo shows how GMS Location can be used to check for changes to the users location.  The "My
 * Location" button uses GMS Location to set the blue dot representing the users location.
 * Permission for {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and {@link
 * android.Manifest.permission#ACCESS_COARSE_LOCATION} are requested at run time. If either
 * permission is not granted, the Activity is finished with an error message.
 */
public class MyLocationDemoActivity extends AppCompatActivity
    implements
    OnMyLocationButtonClickListener,
    OnMyLocationClickListener,
    OnMapReadyCallback,
    ActivityCompat.OnRequestPermissionsResultCallback {

    /**
     * Request code for location permission request.
     *
     * @see #onRequestPermissionsResult(int, String[], int[])
     */
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;

    /**
     * Flag indicating whether a requested permission has been denied after returning in {@link
     * #onRequestPermissionsResult(int, String[], int[])}.
     */
    private boolean permissionDenied = false;

    private GoogleMap map;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_location_demo);

        SupportMapFragment mapFragment =
            (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(@NonNull GoogleMap googleMap) {
        map = googleMap;
        map.setOnMyLocationButtonClickListener(this);
        map.setOnMyLocationClickListener(this);
        enableMyLocation();
    }

    /**
     * Enables the My Location layer if the fine location permission has been granted.
     */
    @SuppressLint("MissingPermission")
    private void enableMyLocation() {
        // 1. Check if permissions are granted, if so, enable the my location layer
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED
            || ContextCompat.checkSelfPermission(this, permission.ACCESS_COARSE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
            map.setMyLocationEnabled(true);
            return;
        }

        // 2. Otherwise, request location permissions from the user.
        PermissionUtils.requestLocationPermissions(this, LOCATION_PERMISSION_REQUEST_CODE, true);
    }

    @Override
    public boolean onMyLocationButtonClick() {
        Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
        // Return false so that we don't consume the event and the default behavior still occurs
        // (the camera animates to the user's current position).
        return false;
    }

    @Override
    public void onMyLocationClick(@NonNull Location location) {
        Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
        if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            return;
        }

        if (PermissionUtils.isPermissionGranted(permissions, grantResults,
            Manifest.permission.ACCESS_FINE_LOCATION) || PermissionUtils
            .isPermissionGranted(permissions, grantResults,
                Manifest.permission.ACCESS_COARSE_LOCATION)) {
            // Enable the my location layer if the permission has been granted.
            enableMyLocation();
        } else {
            // Permission was denied. Display an error message
            // Display the missing permission error dialog when the fragments resume.
            permissionDenied = true;
        }
    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        if (permissionDenied) {
            // Permission was not granted, display error dialog.
            showMissingPermissionError();
            permissionDenied = false;
        }
    }

    /**
     * Displays a dialog with error message explaining that the location permission is missing.
     */
    private void showMissingPermissionError() {
        PermissionUtils.PermissionDeniedDialog
            .newInstance(true).show(getSupportFragmentManager(), "dialog");
    }

}

Lớp Vị trí của tôi

Bạn có thể sử dụng lớp Vị trí của tôi và nút Vị trí của tôi để hiển thị sử dụng vị trí hiện tại của họ trên bản đồ. Gọi cho mMap.setMyLocationEnabled() để bật lớp Vị trí của tôi trên bản đồ.

Mẫu sau đây trình bày cách sử dụng đơn giản lớp Vị trí của tôi:

Kotlin



// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.maps.example.kotlin

import android.annotation.SuppressLint
import android.location.Location
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener
import com.google.android.gms.maps.GoogleMap.OnMyLocationClickListener
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.maps.example.R

internal class MyLocationLayerActivity : AppCompatActivity(),
    OnMyLocationButtonClickListener,
    OnMyLocationClickListener,
    OnMapReadyCallback {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_location)
        val mapFragment =
            supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }

    @SuppressLint("MissingPermission")
    override fun onMapReady(map: GoogleMap) {
        // TODO: Before enabling the My Location layer, you must request
        // location permission from the user. This sample does not include
        // a request for location permission.
        map.isMyLocationEnabled = true
        map.setOnMyLocationButtonClickListener(this)
        map.setOnMyLocationClickListener(this)
    }

    override fun onMyLocationClick(location: Location) {
        Toast.makeText(this, "Current location:\n$location", Toast.LENGTH_LONG)
            .show()
    }

    override fun onMyLocationButtonClick(): Boolean {
        Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT)
            .show()
        // Return false so that we don't consume the event and the default behavior still occurs
        // (the camera animates to the user's current position).
        return false
    }
}


      

Java


// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.maps.example;

import android.annotation.SuppressLint;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;

class MyLocationLayerActivity extends AppCompatActivity
    implements GoogleMap.OnMyLocationButtonClickListener,
    GoogleMap.OnMyLocationClickListener,
    OnMapReadyCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_location);

        SupportMapFragment mapFragment =
            (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onMapReady(GoogleMap map) {
        // TODO: Before enabling the My Location layer, you must request
        // location permission from the user. This sample does not include
        // a request for location permission.
        map.setMyLocationEnabled(true);
        map.setOnMyLocationButtonClickListener(this);
        map.setOnMyLocationClickListener(this);
    }

    @Override
    public void onMyLocationClick(@NonNull Location location) {
        Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG)
            .show();
    }

    @Override
    public boolean onMyLocationButtonClick() {
        Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT)
            .show();
        // Return false so that we don't consume the event and the default behavior still occurs
        // (the camera animates to the user's current position).
        return false;
    }
}


      

Khi lớp Vị trí của tôi được bật, nút Vị trí của tôi xuất hiện trong góc trên cùng bên phải của bản đồ. Khi người dùng nhấp vào nút, máy ảnh sẽ căn giữa bản đồ ở vị trí hiện tại của thiết bị (nếu đã biết). Vị trí được biểu thị bằng một chấm nhỏ màu xanh lam trên bản đồ nếu thiết bị đang đứng yên, hoặc dưới dạng dấu chữ v nếu thiết bị đang di chuyển.

Ảnh chụp màn hình sau đây hiển thị nút Vị trí của tôi ở trên cùng bên phải và Chấm Vị trí của tôi màu xanh dương ở giữa bản đồ:

Bạn có thể ngăn nút Vị trí của tôi xuất hiện bằng cách gọi UiSettings.setMyLocationButtonEnabled(false).

Ứng dụng của bạn có thể phản hồi các sự kiện sau:

  • Nếu người dùng nhấp vào nút Vị trí của tôi, ứng dụng của bạn sẽ nhận được Lệnh gọi lại onMyLocationButtonClick() từ GoogleMap.OnMyLocationButtonClickListener.
  • Nếu người dùng nhấp vào chấm màu xanh dương Vị trí của tôi, ứng dụng của bạn sẽ nhận được Lệnh gọi lại onMyLocationClick() từ GoogleMap.OnMyLocationClickListener.

API Vị trí của Dịch vụ Google Play

API Vị trí của Dịch vụ Google Play là phương thức ưu tiên để thêm tính năng nhận biết vị trí vào ứng dụng Android của bạn. Bộ công cụ này bao gồm cho phép bạn:

  • Xác định vị trí thiết bị.
  • Nghe các thay đổi về vị trí.
  • Xác định phương thức giao thông nếu thiết bị đang di chuyển.
  • Tạo và giám sát các khu vực địa lý đã xác định trước, còn được gọi là khoanh vùng địa lý.

API vị trí giúp bạn dễ dàng xây dựng hiệu quả nguồn điện, ứng dụng nhận biết vị trí. Giống như SDK Maps dành cho Android, Vị trí API được phân phối trong SDK Dịch vụ Google Play. Để biết thêm thông tin về API Vị trí, vui lòng tham khảo lớp đào tạo về Android Nhận biết vị trí ứng dụng của bạn hoặc API Vị trí Tệp đối chiếu. Ví dụ về mã được đưa vào như một phần của chính sách SDK Dịch vụ Play.