แสดงตำแหน่งของฉัน

ตัวอย่างนี้แสดงวิธีเปิดใช้เลเยอร์ตำแหน่งของฉัน และแสดงปุ่มตำแหน่งของฉันเพื่อแสดงตำแหน่งปัจจุบันของอุปกรณ์ซึ่งแสดงด้วยจุดสีน้ำเงินบนแผนที่

ดูข้อมูลเพิ่มเติมได้ที่เอกสารประกอบ

เริ่มต้นใช้งาน

คุณต้องกําหนดค่าสภาพแวดล้อมการพัฒนาก่อนจึงจะลองใช้โค้ดตัวอย่างได้ ดูข้อมูลเพิ่มเติมได้ที่ตัวอย่างโค้ด Maps SDK สำหรับ Android

ดูโค้ด

Kotlin

class MyLocationDemoActivity : SamplesBaseActivity(),     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)         applyInsets(findViewById<View?>(R.id.map_container))     }      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             // ...         }     }      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

public class MyLocationDemoActivity extends SamplesBaseActivity     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(com.example.common_ui.R.layout.my_location_demo);          SupportMapFragment mapFragment =             (SupportMapFragment) getSupportFragmentManager().findFragmentById(com.example.common_ui.R.id.map);         mapFragment.getMapAsync(this);         applyInsets(findViewById(com.example.common_ui.R.id.map_container));     }      @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             // ...         }     }      @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");     }  }        

โคลนและเรียกใช้ตัวอย่าง

คุณต้องใช้ Git เพื่อเรียกใช้ตัวอย่างนี้ในเครื่อง คำสั่งต่อไปนี้จะโคลนที่เก็บแอปพลิเคชันตัวอย่าง

git clone [email protected]:googlemaps-samples/android-samples.git

นําเข้าโปรเจ็กต์ตัวอย่างไปยัง Android Studio โดยทำดังนี้

  1. ใน Android Studio ให้เลือกไฟล์ > ใหม่ > นำเข้าโปรเจ็กต์
  2. ไปที่ตำแหน่งที่คุณบันทึกที่เก็บไว้ แล้วเลือกไดเรกทอรีโปรเจ็กต์สำหรับ Kotlin หรือ Java

    • Kotlin: PATH-REPO/android-samples/ApiDemos/kotlin
    • Java: PATH-REPO/android-samples/ApiDemos/java
  3. เลือกเปิด Android Studio จะสร้างโปรเจ็กต์โดยใช้เครื่องมือบิลด์ Gradle
  4. สร้างไฟล์ secrets.properties ว่างในไดเรกทอรีเดียวกับไฟล์ local.properties ของโปรเจ็กต์ ดูข้อมูลเพิ่มเติมเกี่ยวกับไฟล์นี้ได้ที่หัวข้อเพิ่มคีย์ API ลงในโปรเจ็กต์
  5. รับคีย์ API จากโปรเจ็กต์ที่เปิดใช้ Maps SDK สำหรับ Android
  6. เพิ่มสตริงต่อไปนี้ลงใน secrets.properties โดยแทนที่ YOUR_API_KEY ด้วยค่าของคีย์ API

    MAPS_API_KEY=YOUR_API_KEY
  7. เรียกใช้แอป