Android Studio中的地图片段中的当前位置
创始人
2024-08-18 10:00:37
0

要在Android Studio中获取设备的当前位置,可以使用Android的定位服务。以下是一个示例代码,演示如何在Android Studio中获取设备的当前位置并在地图上显示出来:

  1. 首先,确保在AndroidManifest.xml文件中添加以下权限:

  1. 在你的Activity或Fragment中,添加以下代码来获取设备的当前位置:
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;

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

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    private GoogleMap mMap;
    private FusedLocationProviderClient mFusedLocationClient;
    private LocationCallback mLocationCallback;

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

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

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

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
            startLocationUpdates();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    LOCATION_PERMISSION_REQUEST_CODE);
        }
    }

    private void startLocationUpdates() {
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(5000); // 5 seconds

        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                if (locationResult == null) {
                    return;
                }
                for (Location location : locationResult.getLocations()) {
                    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                    mMap.clear(); // remove previous marker
                    mMap.addMarker(new MarkerOptions().position(latLng));
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
                }
            }
        };

        mFusedLocationClient.requestLocationUpdates(locationRequest, mLocationCallback, null);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    mMap.setMyLocationEnabled(true);
                    startLocationUpdates();
                }
            } else {
                Toast.makeText(this, "Location permission denied. Please grant the permission to use this feature.",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationCallback != null) {
            mFusedLocationClient.removeLocationUpdates(mLocationCallback);
        }
    }
}

在这个示例中,我们使用了Google Maps API来显示地图,并使用了FusedLocationProviderClient来获取设备的当前位置。首先,我们检查是否已授予了定位权限。如果已授予权限,我们启用地图的我的位置功能,并开始定位更新。如果没有授予权限,我们会请求用户授予权限。

在startLocationUpdates()方法中,我们创建了一个LocationRequest对象,设置了定位的优先级和更新间隔。然后,我们使用FusedLocationProviderClient的requestLocationUpdates()方法来请求位置更新。当位置更新时,回调函数onLocationResult()会被调用。在这个回调函数中,我们获取最新的位置,并

相关内容

热门资讯

安装Pillow时遇到了问题:... 遇到这个问题,可能是因为缺少libwebpmux3软件包。解决方法是手动安装libwebpmux3软...
安装ug未能链接到许可证服务器 安装UG未能链接到许可证服务器是UG用户在安装软件时常遇到的问题之一。该问题的解决方法需要技术向的知...
安装Python库"... 安装Python库"firedrake"的解决方法如下:打开终端或命令提示符(Windows系统)。...
安装React Native时... 当安装React Native时出现构建错误的情况,可以尝试以下解决方法:确保已经安装了最新版本的C...
安卓 - 谷歌地图卡住了 问题描述:在安卓设备上使用谷歌地图应用时,地图卡住了,无法进行任何操作。解决方法一:清除应用缓存和数...
按转换模式过滤日志【%t】。 要按照转换模式过滤日志,可以使用正则表达式来实现。下面是一个示例代码,使用Java语言的Patter...
安装react-native-... 要安装react-native-onesignal并在应用关闭时仍能接收通知,可以按照以下步骤进行:...
安装Rails时构建webso... 在安装Rails时,如果构建websocket-driver时发生错误,可以尝试以下解决方法:更新系...
Apache Nifi在Kub... Apache Nifi可以在Kubernetes上运行,并且已经准备好用于生产环境。下面是一个使用H...
安装React-Scripts... 这是因为React-Scripts使用Facebook工具包中的一些脚本。 joinAdIntere...