الحصول على آخر موقع جغرافي معروف
تنظيم صفحاتك في مجموعات
يمكنك حفظ المحتوى وتصنيفه حسب إعداداتك المفضّلة.
باستخدام واجهات برمجة التطبيقات الخاصة بالموقع الجغرافي في "خدمات Google Play"، يمكن لتطبيقك طلب آخر موقع جغرافي معروف لجهاز المستخدم. في معظم الحالات، يهمّك معرفة الموقع الجغرافي الحالي للمستخدم، وهو عادةً ما يعادل آخر موقع جغرافي معروف للجهاز.
على وجه التحديد، استخدِم مزوّد الموقع الجغرافي المدمج لاسترداد آخر موقع جغرافي معروف للجهاز. موفِّر الموقع المدمج هو إحدى واجهات برمجة التطبيقات الخاصة بالموقع الجغرافي في "خدمات Google Play". وتدير هذه الخدمة تكنولوجيا الموقع الجغرافي الأساسية وتوفّر واجهة برمجة تطبيقات بسيطة تتيح لك تحديد المتطلبات على مستوى عالٍ، مثل الدقة العالية أو استهلاك الطاقة المنخفض.
ويحسِّن أيضًا استخدام الجهاز لطاقة البطارية.
ملاحظة: عندما يكون تطبيقك يعمل في الخلفية، يجب أن يكون الوصول إلى بيانات الموقع الجغرافي ضروريًا للوظائف الأساسية للتطبيق، ويجب أن يكون مصحوبًا ببيان إفصاح مناسب للمستخدمين.
يوضّح لك هذا الدرس كيفية إرسال طلب واحد للحصول على الموقع الجغرافي لجهاز باستخدام طريقة getLastLocation()
في "موفّر الموقع المدمج".
إعداد "خدمات Google Play"
للوصول إلى "مزوّد الموقع الجغرافي المدمج"، يجب أن يتضمّن مشروع تطوير تطبيقك "خدمات Google Play". نزِّل مكوّن "خدمات Google Play" وثبِّته من خلال مدير حزمة تطوير البرامج (SDK) وأضِف المكتبة إلى مشروعك. لمعرفة التفاصيل، يُرجى الاطّلاع على دليل إعداد خدمات Google Play.
تحديد أذونات التطبيق
يجب أن تطلب التطبيقات أذونات تحديد الموقع الجغرافي التي تستخدم ميزاتها خدمات الموقع الجغرافي، وذلك حسب حالات استخدام هذه الميزات.
إنشاء عميل لخدمات الموقع الجغرافي
في طريقة onCreate()
الخاصة بنشاطك، أنشئ مثيلاً من FusedLocationProviderClient كما يوضّح مقتطف الرمز التالي.
Kotlin
private lateinit var fusedLocationClient: FusedLocationProviderClient
override fun onCreate(savedInstanceState: Bundle?) {
// ...
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}
Java
private FusedLocationProviderClient fusedLocationClient;
// ..
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
الحصول على آخر موقع جغرافي معروف
بعد إنشاء برنامج Location Services، يمكنك الحصول على آخر موقع جغرافي معروف لجهاز أحد المستخدمين. عندما يكون تطبيقك
متصلاً بهذه الخدمات، يمكنك استخدام طريقة
getLastLocation()
الخاصة بمزوّد الموقع الجغرافي المدمج لاسترداد الموقع الجغرافي للجهاز. تتحدّد دقة الموقع الجغرافي الذي تعرضه هذه المكالمة من خلال إعدادات الأذونات التي تضعها في ملف بيان التطبيق، كما هو موضّح في الدليل حول كيفية طلب أذونات تحديد الموقع الجغرافي.
لطلب آخر موقع جغرافي معروف، استدعِ طريقة
getLastLocation()
. يوضّح مقتطف الرمز التالي الطلب وطريقة بسيطة للتعامل مع الردّ:
Kotlin
fusedLocationClient.lastLocation
.addOnSuccessListener { location : Location? ->
// Got last known location. In some rare situations this can be null.
}
Java
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
}
}
});
تعرض الطريقة
getLastLocation()
العنصر Task
الذي يمكنك استخدامه للحصول على
العنصر Location
الذي يتضمّن إحداثيات خطوط الطول والعرض الخاصة بموقع جغرافي. قد يكون كائن الموقع الجغرافي null
في الحالات التالية:
- تم إيقاف الموقع الجغرافي في إعدادات الجهاز. قد تكون النتيجة
null
حتى إذا تم استرداد آخر موقع جغرافي سابقًا، لأنّ إيقاف الموقع الجغرافي يؤدي أيضًا إلى محو ذاكرة التخزين المؤقت.
- لم يسجّل الجهاز موقعه الجغرافي مطلقًا، كما هو الحال مع جهاز جديد أو جهاز تمت إعادة ضبطه على الإعدادات الأصلية.
- تمت إعادة تشغيل "خدمات Google Play" على الجهاز، ولا يتوفّر أي عميل نشط في Fused Location Provider طلب الموقع الجغرافي بعد إعادة تشغيل الخدمات. لتجنُّب هذه الحالة، يمكنك إنشاء عميل جديد وطلب تعديلات على الموقع الجغرافي بنفسك. لمزيد من المعلومات، يُرجى الاطّلاع على مقالة طلب تلقّي تحديثات حول الموقع الجغرافي.
اختيار أفضل تقدير للموقع الجغرافي
توفّر السمة FusedLocationProviderClient
عدة طرق لاسترداد معلومات الموقع الجغرافي للجهاز. اختَر أحد الخيارات التالية حسب حالة استخدام تطبيقك:
- يساعد
getLastLocation()
في الحصول على تقدير للموقع الجغرافي بشكل أسرع ويقلّل من استهلاك البطارية الذي يمكن أن يعزى إلى تطبيقك. ومع ذلك، قد تكون معلومات الموقع الجغرافي قديمة إذا لم يستخدم أي عملاء آخرين الموقع الجغرافي بشكل نشط مؤخرًا.
getCurrentLocation()
يحصل على موقع جغرافي أحدث وأكثر دقة بشكل أكثر اتساقًا. ومع ذلك، يمكن أن تؤدي هذه الطريقة إلى احتساب الموقع الجغرافي النشط على الجهاز.
هذه هي الطريقة المقترَحة للحصول على موقع جغرافي جديد كلما أمكن ذلك، وهي أكثر أمانًا من البدائل، مثل بدء وإدارة عمليات تعديل الموقع الجغرافي بنفسك باستخدام requestLocationUpdates()
. إذا كان تطبيقك يستدعي requestLocationUpdates()
، قد يستهلك تطبيقك أحيانًا كميات كبيرة من الطاقة إذا لم يتوفّر الموقع الجغرافي، أو إذا لم يتم إيقاف الطلب بشكل صحيح بعد الحصول على موقع جغرافي جديد.
مراجع إضافية
لمزيد من المعلومات حول جلب الموقع الجغرافي الحالي في Android، اطّلِع على المواد التالية:
نماذج
- تطبيق نموذجي لتوضيح أفضل الممارسات أثناء جلب الموقع الجغرافي الحالي
يخضع كل من المحتوى وعيّنات التعليمات البرمجية في هذه الصفحة للتراخيص الموضحّة في ترخيص استخدام المحتوى. إنّ Java وOpenJDK هما علامتان تجاريتان مسجَّلتان لشركة Oracle و/أو الشركات التابعة لها.
تاريخ التعديل الأخير: 2025-08-27 (حسب التوقيت العالمي المتفَّق عليه)
[[["يسهُل فهم المحتوى.","easyToUnderstand","thumb-up"],["ساعَدني المحتوى في حلّ مشكلتي.","solvedMyProblem","thumb-up"],["غير ذلك","otherUp","thumb-up"]],[["لا يحتوي على المعلومات التي أحتاج إليها.","missingTheInformationINeed","thumb-down"],["الخطوات معقدة للغاية / كثيرة جدًا.","tooComplicatedTooManySteps","thumb-down"],["المحتوى قديم.","outOfDate","thumb-down"],["ثمة مشكلة في الترجمة.","translationIssue","thumb-down"],["مشكلة في العيّنات / التعليمات البرمجية","samplesCodeIssue","thumb-down"],["غير ذلك","otherDown","thumb-down"]],["تاريخ التعديل الأخير: 2025-08-27 (حسب التوقيت العالمي المتفَّق عليه)"],[],[],null,["Using the Google Play services location APIs, your app can request the last\nknown location of the user's device. In most cases, you are interested in the\nuser's current location, which is usually equivalent to the last known\nlocation of the device.\n\nSpecifically, use the\n[fused\nlocation provider](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html) to retrieve the device's last known location. The fused\nlocation provider is one of the location APIs in Google Play services. It\nmanages the underlying location technology and provides a simple API so that\nyou can specify requirements at a high level, like high accuracy or low power.\nIt also optimizes the device's use of battery power. \n**Note:** When your app is running in the background,\n[access to location](/training/location/background) should be\ncritical to the core functionality of the app and is accompanied with proper\ndisclosure to users.\n\nThis lesson shows you how to make a single request for the location of a\ndevice using the\n[`getLastLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html#getLastLocation())\nmethod in the fused location provider.\n\nSet up Google Play services\n\nTo access the fused location provider, your app's development project must\ninclude Google Play services. Download and install the Google Play services\ncomponent via the [SDK\nManager](/tools/help/sdk-manager) and add the library to your project. For details, see the guide to\n[Setting Up Google Play\nServices](/google/play-services/setup).\n\nSpecify app permissions\n\nApps whose features use location services must\n[request location permissions](/training/location/permissions),\ndepending on the use cases of those features.\n\nCreate location services client\n\nIn your activity's [onCreate()](/reference/android/app/Activity#onCreate(android.os.Bundle)) method,\ncreate an instance of the Fused Location Provider Client as the following code snippet shows. \n\nKotlin \n\n```kotlin\nprivate lateinit var fusedLocationClient: FusedLocationProviderClient\n\noverride fun onCreate(savedInstanceState: Bundle?) {\n // ...\n\n fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)\n}\n```\n\nJava \n\n```java\nprivate FusedLocationProviderClient fusedLocationClient;\n\n// ..\n\n@Override\nprotected void onCreate(Bundle savedInstanceState) {\n // ...\n\n fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);\n}\n```\n\nGet the last known location\n\nOnce you have created the Location Services client\nyou can get the last known location of a user's device. When your app is\nconnected to these you can use the fused location provider's\n[`getLastLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html#getLastLocation())\nmethod to retrieve the device location. The precision of the location returned\nby this call is determined by the permission setting you put in your app\nmanifest, as described in the guide on how to\n[request location permissions](/training/location/permissions).\n\nTo request the last known location, call the\n[`getLastLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html#getLastLocation())\nmethod. The following code snippet illustrates the request and a simple handling of the\nresponse: \n\nKotlin \n\n```kotlin\nfusedLocationClient.lastLocation\n .addOnSuccessListener { location : Location? -\u003e\n // Got last known location. In some rare situations this can be null.\n }\n```\n\nJava \n\n```java\nfusedLocationClient.getLastLocation()\n .addOnSuccessListener(this, new OnSuccessListener\u003cLocation\u003e() {\n @Override\n public void onSuccess(Location location) {\n // Got last known location. In some rare situations this can be null.\n if (location != null) {\n // Logic to handle location object\n }\n }\n });\n```\n\nThe\n[`getLastLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html#getLastLocation())\nmethod returns a [`Task`](https://developers.google.com/android/reference/com/google/android/gms/tasks/Task)\nthat you can use to get a\n[`Location`](/reference/android/location/Location)\nobject with the latitude and longitude coordinates of a\ngeographic location. The location object may be `null` in the\nfollowing situations:\n\n- Location is turned off in the device settings. The result could be `null` even if the last location was previously retrieved because disabling location also clears the cache.\n- The device never recorded its location, which could be the case of a new device or a device that has been restored to factory settings.\n- Google Play services on the device has restarted, and there is no active Fused Location Provider client that has requested location after the services restarted. To avoid this situation you can create a new client and request location updates yourself. For more information, see [Request location\n updates](/training/location/receive-location-updates).\n\nChoose the best location estimate\n\nThe `FusedLocationProviderClient` provides several methods to retrieve device\nlocation information. Choose from one of the following, depending on your app's\nuse case:\n\n- [`getLastLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient#getLastLocation()) gets a location estimate more quickly and minimizes battery usage that can be attributed to your app. However, the location information might be out of date, if no other clients have actively used location recently.\n- [`getCurrentLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient#getCurrentLocation(int,%20com.google.android.gms.tasks.CancellationToken))\n gets a fresher, more accurate location more consistently. However, this method\n can cause active location computation to occur on the device\n\n This is the recommended way to get a fresh location, whenever possible, and\n is safer than alternatives like starting and managing location updates\n yourself using `requestLocationUpdates()`. If your app calls\n `requestLocationUpdates()`, your app can sometimes consume large amounts of\n power if location isn't available, or if the request isn't stopped correctly\n after obtaining a fresh location.\n\nAdditional resources\n\nFor more information about fetching current location in Android, view the\nfollowing materials:\n\nSamples\n\n- [Sample app](https://github.com/android/platform-samples/tree/main/samples/location/src/main/java/com/example/platform/location/currentLocation) to demonstrate best practices while fetching current location."]]