Mobil uygulamaların benzersiz özelliklerinden biri konum farkındalığıdır. Mobil kullanıcılar cihazlarını yanlarında taşır ve uygulamanıza konum farkındalığı bildirilmesiyle kullanıcılara daha bağlama dayalı bir deneyim sunulur.
Kod örnekleri
GitHub'daki ApiDemos deposu, haritada konumun kullanımını gösteren örnekler içerir:
Java
- MyLocationDemoActivity: Çalışma zamanı izinleri dahil olmak üzere Konumum katmanını kullanma
- LocationSourceDemoActivity: Özel bir
LocationSource
kullanma - CurrentPlaceDetailsOnMap: Bir Android cihazın mevcut konumunu bulma ve bu konumdaki yerin (işletme ya da başka bir önemli nokta) ayrıntılarını görüntüleme. Haritada mevcut yer ayrıntılarını gösterme ile ilgili eğiticiye göz atın.
Kotlin
- MyLocationDemoActivity: Çalışma zamanı izinleri dahil olmak üzere Konumum katmanını kullanma
- LocationSourceDemoActivity: Özel bir
LocationSource
kullanma - CurrentPlaceDetailsOnMap: Bir Android cihazın mevcut konumunu bulma ve bu konumdaki yerin (işletme ya da başka bir önemli nokta) ayrıntılarını görüntüleme. Haritada mevcut yer ayrıntılarını gösterme ile ilgili eğiticiye göz atın.
Konum verileriyle çalışma
Bir Android cihazda kullanılabilen konum verileri, cihazların mevcut konumunu (teknolojilerin bir kombinasyonu kullanılarak belirlenir) içerir. Bunlar, hareketin yönü ve yöntemidir. Ayrıca, cihazın önceden tanımlanmış bir coğrafi sınırın veya coğrafi sınırın geçip geçmediği bilgisi de içerir. Uygulamanızın gereksinimlerine bağlı olarak, konum verileriyle çalışmak için birkaç yöntem arasından seçim yapabilirsiniz:
- Konumum katmanı, haritada bir cihazın konumunu görüntülemek için basit bir yol sağlar. Veri sağlamaz.
- Tüm programatik konum verilerine yönelik istekler için Google Play Services Location API önerilir.
LocationSource
arayüzü, özel bir konum sağlayıcı sağlamanıza olanak tanır.
Konum izinleri
Uygulamanızın kullanıcının konumuna erişmesi gerekiyorsa ilgili Android konum izinlerini uygulamanıza ekleyerek izin istemeniz gerekir.
Android iki konum izni sunar: ACCESS_COARSE_LOCATION
ve
ACCESS_FINE_LOCATION
. Seçtiğiniz izin, API tarafından döndürülen konumun doğruluğunu belirler.
android.permission.ACCESS_COARSE_LOCATION
– API'nin cihazın yaklaşık konumunu döndürmesini sağlar. İzin, yaklaşık konum doğruluğu ile ilgili belgelerde açıklandığı gibi konum hizmetlerinden cihaz konumu tahmini sağlar.android.permission.ACCESS_FINE_LOCATION
– API'nin, Küresel Konumlandırma Sistemi (GPS) ile kablosuz ağ ve mobil hücre verileri de dahil olmak üzere mevcut konum sağlayıcılarından mümkün olduğunca doğru bir konum belirlemesine olanak tanır.
İzinleri uygulama manifestine ekleyin
Yaklaşık konum yalnızca uygulamanızın çalışması için gerekliyse ACCESS_COARSE_LOCATION
iznini uygulamanızın manifest dosyasına ekleyin:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapp" > ... <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> ... </manifest>
Ancak tam konum gerekiyorsa uygulamanızın manifest dosyasına hem ACCESS_COARSE_LOCATION
hem de ACCESS_FINE_LOCATION
izinlerini ekleyin:
<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>
Çalışma zamanı izinleri isteme
Android 6.0 (Marshmallow), izin yönetimi için yeni bir model sunar. Bu model, uygulamaları yükleyen ve yeni sürüme geçiren kullanıcılar için süreci kolaylaştırır. Uygulamanız API düzeyi 23 veya üstünü hedefliyorsa yeni izin modelini kullanabilirsiniz.
Uygulamanız yeni izin modelini destekliyorsa ve cihaz Android 6.0 (Marshmallow) veya sonraki bir sürümü çalıştırıyorsa uygulamayı yüklerken veya yeni sürüme geçirirken kullanıcının herhangi bir izin vermesi gerekmez. Uygulama, çalışma zamanında gerekli izne sahip olup olmadığını kontrol etmeli ve izin yoksa izin istemelidir. Sistem, kullanıcıya izin isteyen bir iletişim kutusu gösterir.
En iyi kullanıcı deneyimi için iznin bir bağlam içinde istenmesi önemlidir. Uygulamanızın çalışması için konum gerekliyse uygulama başlatılırken konum izni istemeniz gerekir. Bunu yapmanın iyi bir yolu, kullanıcıları iznin neden gerekli olduğu konusunda eğiten, sıcak bir karşılama ekranı veya sihirbaz kullanmaktır.
Uygulama, işlevlerinin yalnızca bir kısmı için izin gerektiriyorsa konum iznini, uygulamanın izni gerektiren işlemi gerçekleştirdiği sırada istemelisiniz.
Uygulama, kullanıcının izin vermediği durumlarda sorunsuz bir şekilde çalışmalıdır. Örneğin, belirli bir özellik için izin gerekirse, uygulama bu özelliği devre dışı bırakabilir. Uygulamanın çalışması için izin gerekliyse uygulama tüm işlevlerini devre dışı bırakabilir ve kullanıcıya izni vermesi gerektiğini bildirebilir.
Aşağıdaki kod örneği, Konumum katmanı etkinleştirmeden önce AndroidX kitaplığını kullanarak izni kontrol eder. Daha sonra Destek kitaplığından ActivityCompat.OnRequestPermissionsResultCallback
kodunu uygulayarak izin isteğinin sonucunu işler:
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"); } }
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 } }
Konumum katmanı
Kullanıcınıza haritadaki mevcut konumunu göstermek için Konumum katmanını ve Konumum düğmesini kullanabilirsiniz. Haritadaki Konumum katmanını etkinleştirmek için
mMap.setMyLocationEnabled()
numaralı telefonu arayın.
Aşağıdaki örnekte Konumum katmanının basit bir kullanımı gösterilmektedir:
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; } }
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 } }
Konumum katmanı etkinleştirildiğinde, haritanın sağ üst köşesinde Konumum düğmesi görünür. Kullanıcı düğmeyi tıkladığında kamera, bilinen bir cihazın mevcut konumuna göre haritayı ortalar. Cihaz sabitse konum, haritada küçük bir mavi noktayla veya hareket ediyorsa v ayracı şeklinde gösterilir.
Aşağıdaki ekran görüntüsünde sağ üstte Konumum düğmesi ve haritanın ortasındaki Konumum mavi noktası gösterilmektedir:
UiSettings.setMyLocationButtonEnabled(false)
yöntemini çağırarak Konumum düğmesinin görünmesini engelleyebilirsiniz.
Uygulamanız aşağıdaki etkinliklere yanıt verebilir:
- Kullanıcı Konumum düğmesini tıklarsa uygulamanız
GoogleMap.OnMyLocationButtonClickListener
'danonMyLocationButtonClick()
geri çağırması alır. - Kullanıcı Konumum mavi noktasını tıklarsa uygulamanız
GoogleMap.OnMyLocationClickListener
üzerindenonMyLocationClick()
geri çağırmasını alır.
Google Play Hizmetleri Konum API'si
Google Play Hizmetleri Konum API'si, Android uygulamanıza konum farkındalığını eklemek için tercih edilen yöntemdir. Aşağıdakileri yapmanızı sağlayan işlevler içerir:
- Cihazın konumunu belirleme.
- Konum değişikliklerini dinleyin.
- Cihaz hareket ediyorsa ulaşım şeklini belirleme.
- Geofences olarak bilinen önceden tanımlanmış coğrafi bölgeleri oluşturun ve izleyin.
Konum API'leri, gücü verimli kullanan, konuma duyarlı uygulamalar derlemenizi kolaylaştırır. Android için Haritalar SDK'sı gibi Konum API'si de Google Play Hizmetleri SDK'sının bir parçası olarak dağıtılır. Konum API'si hakkında daha fazla bilgi için lütfen Uygulamanızı Konuma Duyarlı Hale Getirme Android eğitim sınıfına veya Location API Referansı'na bakın. Kod örnekleri, Google Play Hizmetleri SDK'sının bir parçasıdır.