נתוני מיקום

אחת התכונות הייחודיות של אפליקציות לנייד היא גישה למיקום. משתמשים בנייד לוקחים איתם את המכשירים לכל מקום, והוספת מודעות למיקום לאפליקציה מספקת למשתמשים חוויה שמתאימה יותר להקשר.

דוגמאות קוד

מאגר ApiDemos ב-GitHub כולל דוגמאות שממחישות את השימוש במיקום במפה:

Kotlin

Java

איך עובדים עם נתוני מיקום

נתוני המיקום שזמינים למכשיר Android כוללים את המיקום הנוכחי של המכשיר, שנקבע באמצעות שילוב של טכנולוגיות, את כיוון התנועה ושיטת התנועה, ואם המכשיר חצה גבול גיאוגרפי מוגדר מראש, או גבולות וירטואליים. בהתאם לצרכים של האפליקציה, אפשר לבחור מבין כמה דרכים לעבודה עם נתוני מיקום:

  • שכבת המיקום שלי מאפשרת להציג בקלות את מיקום המכשיר במפה. הוא לא מספק נתונים.
  • מומלץ להשתמש ב-Google Play services Location API לכל הבקשות הפרוגרמטיות לנתוני מיקום.
  • הממשק LocationSource מאפשר לכם לספק ספק מיקום בהתאמה אישית.

הרשאות מיקום

אם האפליקציה צריכה לגשת למיקום של המשתמש, צריך לבקש הרשאה על ידי הוספת הרשאות המיקום הרלוונטיות של Android לאפליקציה.

ב-Android יש שתי הרשאות מיקום: ACCESS_COARSE_LOCATION ו-ACCESS_FINE_LOCATION. ההרשאה שתבחרו תקבע את רמת הדיוק של המיקום שיוחזר על ידי ה-API.

  • android.permission.ACCESS_COARSE_LOCATION – מאפשרת ל-API להחזיר את המיקום המשוער של המכשיר. הרשאה זו מספקת הערכה של מיקום המכשיר משירותי המיקום, כפי שמתואר במסמכי התיעוד בנושא דיוק המיקום המשוער.
  • android.permission.ACCESS_FINE_LOCATION – מאפשרת ל-API לקבוע מיקום מדויק ככל האפשר מספקי המיקום הזמינים, כולל מערכת המיקום הגלובלית (GPS), וגם Wi-Fi ונתונים סלולריים.

הוספת ההרשאות לקובץ מניפסט של אפליקציה

אם נדרש מיקום משוער רק כדי שהאפליקציה תפעל, צריך להוסיף את ההרשאה ACCESS_COARSE_LOCATION לקובץ המניפסט של האפליקציה:

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

עם זאת, אם נדרש מיקום מדויק, צריך להוסיף את ההרשאות ACCESS_COARSE_LOCATION ו-ACCESS_FINE_LOCATION לקובץ המניפסט של האפליקציה:

<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>

בקשת הרשאות בתחילת ההפעלה

ב-Android 6.0 (Marshmallow)‎ יש מודל חדש לטיפול בהרשאות, שמייעל את התהליך למשתמשים כשהם מתקינים ומשדרגים אפליקציות. אם האפליקציה שלכם מיועדת לרמת ה-API המיועדת 23 או מאוחר יותר, אתם יכולים להשתמש במודל ההרשאות החדש.

אם האפליקציה תומכת במודל ההרשאות החדש ובמכשיר פועלת מערכת Android מגרסה 6.0 (Marshmallow) ואילך, המשתמש לא צריך להעניק הרשאות כשהוא מתקין או משדרג את האפליקציה. האפליקציה צריכה לבדוק אם יש לה את ההרשאה הנדרשת בזמן הריצה, ולבקש את ההרשאה אם אין לה אותה. המערכת מציגה למשתמש תיבת דו-שיח עם בקשה להרשאה.

כדי לספק את חוויית המשתמש הטובה ביותר, חשוב לבקש את ההרשאה בהקשר המתאים. אם המיקום חיוני לפעולה של האפליקציה, צריך לבקש את הרשאת המיקום כשהאפליקציה מופעלת. דרך טובה לעשות את זה היא באמצעות מסך פתיחה או אשף שמסבירים למשתמשים למה נדרשת ההרשאה.

אם האפליקציה דורשת את ההרשאה רק לחלק מהפונקציונליות שלה, צריך לבקש את הרשאת המיקום בזמן שהאפליקציה מבצעת את הפעולה שדורשת את ההרשאה.

האפליקציה צריכה לטפל בצורה חלקה במקרה שבו המשתמש לא מעניק הרשאה. לדוגמה, אם ההרשאה נדרשת לתכונה ספציפית, האפליקציה יכולה להשבית את התכונה הזו. אם ההרשאה חיונית לפעולת האפליקציה, האפליקציה יכולה להשבית את כל הפונקציונליות שלה ולהודיע למשתמש שהוא צריך לתת את ההרשאה.

בדוגמת הקוד הבאה נבדקת ההרשאה באמצעות ספריית AndroidX לפני הפעלת שכבת 'המיקום שלי'. לאחר מכן, היא מטפלת בתוצאה של בקשת ההרשאה על ידי הטמעת ActivityCompat.OnRequestPermissionsResultCallback מספריית התמיכה:

Kotlin

// Copyright 2026 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 com.example.common_ui.catalog.Sample
import com.example.common_ui.catalog.Complexity
import com.example.common_ui.catalog.Framework

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import android.view.View
import android.widget.Toast

import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback
import androidx.core.content.ContextCompat
import com.example.common_ui.R
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.
 */
@Sample(
    id = "com.example.kotlindemos.MyLocationDemoActivity",
    title = "My Location Layer",
    description = "Enabling blue dot location indicator and My Location button with runtime permissions.",
    category = "Location & Sensors",
    complexity = Complexity.SIMPLE,
    tags = ["#location", "#mylocation", "#permissions", "#bluedot"],
    purpose = "Demonstrates requesting ACCESS_FINE_LOCATION permissions and enabling the blue dot location layer.",
    successCriteria = "Tapping My Location button centers camera on user's current GPS position.",
    failureIndicators = "Permission denial causes unhandled crash or location button missing.",
    framework = Framework.KOTLIN_VIEWS
)
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(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
            // 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 com.example.common_ui.catalog.Sample;
import com.example.common_ui.catalog.Complexity;
import com.example.common_ui.catalog.Framework;

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.
 */
@Sample(
    id = "my_location",
    title = "My Location Layer",
    description = "Enabling blue dot location indicator and My Location button with runtime permissions.",
    category = "Location & Sensors",
    complexity = Complexity.SIMPLE,
    tags = {"#location", "#mylocation", "#permissions", "#bluedot"},
    purpose = "Demonstrates requesting ACCESS_FINE_LOCATION permissions and enabling the blue dot location layer.",
    successCriteria = "Tapping My Location button centers camera on user's current GPS position.",
    failureIndicators = "Permission denial causes unhandled crash or location button missing.",
    framework = Framework.JAVA_VIEWS
)
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
            // 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");
    }

}

שכבת המיקום שלי

אתם יכולים להשתמש בשכבה "המיקום שלי" ובלחצן "המיקום שלי" כדי להציג למשתמש את המיקום הנוכחי שלו במפה. מתקשרים למספר mMap.setMyLocationEnabled() כדי להפעיל את שכבת המיקום שלי במפה.

הדוגמה הבאה ממחישה שימוש פשוט בשכבה "המיקום שלי":

Kotlin

// 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 {
    Toast.makeText(context, "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).
    false
}
map.setOnMyLocationClickListener { location ->
    Toast.makeText(context, "Current location:\n$location", Toast.LENGTH_LONG).show()
}

      

Java

// 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(new GoogleMap.OnMyLocationButtonClickListener() {
    @Override
    public boolean onMyLocationButtonClick() {
        Toast.makeText(context, "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;
    }
});
map.setOnMyLocationClickListener(new GoogleMap.OnMyLocationClickListener() {
    @Override
    public void onMyLocationClick(@NonNull Location location) {
        Toast.makeText(context, "Current location:\n" + location, Toast.LENGTH_LONG).show();
    }
});

      

כשהשכבה "המיקום שלי" מופעלת, הכפתור "המיקום שלי" מופיע בפינה הימנית העליונה של המפה. כשמשתמש לוחץ על הכפתור, המצלמה ממקדת את המפה במיקום הנוכחי של המכשיר, אם הוא ידוע. המיקום מצוין במפה באמצעות נקודה כחולה קטנה אם המכשיר נייח, או באמצעות חץ אם המכשיר בתנועה.

בצילום המסך הבא מוצג הכפתור "המיקום שלי" בפינה השמאלית העליונה, והנקודה הכחולה של "המיקום שלי" במרכז המפה:

כדי למנוע את ההצגה של הלחצן "המיקום שלי", צריך להפעיל את הפונקציה UiSettings.setMyLocationButtonEnabled(false).

האפליקציה יכולה להגיב לאירועים הבאים:

  • אם המשתמש לוחץ על כפתור להרשאת מיקום חד פעמית, האפליקציה מקבלת onMyLocationButtonClick() קריאה חוזרת (callback) מה-GoogleMap.OnMyLocationButtonClickListener.
  • אם המשתמש לוחץ על הנקודה הכחולה של "המיקום שלי", האפליקציה מקבלת קריאה חוזרת (callback) מסוג onMyLocationClick() מה-GoogleMap.OnMyLocationClickListener.

‫Location API של Google Play Services

Location API של Google Play Services הוא השיטה המועדפת להוספת גישה למיקום לאפליקציה ל-Android. היא כוללת פונקציות שמאפשרות לכם:

  • קביעת מיקום המכשיר.
  • חיפוש שינויים במיקום.
  • לקבוע את אמצעי התחבורה, אם המכשיר בתנועה.
  • ליצור ולנטר אזורים גיאוגרפיים מוגדרים מראש, שנקראים גבולות וירטואליים.

ממשקי ה-API של המיקום מאפשרים לכם ליצור בקלות אפליקציות חסכוניות באנרגיה עם גישה למיקום. בדומה ל-SDK של מפות ל-Android, ‏ Location API מופץ כחלק מ-Google Play Services SDK. מידע נוסף על Location API זמין בשיעור ההדרכה של Android בנושא הוספת מודעות למיקום לאפליקציה או במאמרי העזרה של Location API. דוגמאות קוד נכללות כחלק מ-Google Play Services SDK.