在Android中,可以使用Google Play服务的定位功能来获取当前位置并在Google地图上显示。以下是在Android中定位当前位置的步骤:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
implementation 'com.google.android.gms:play-services-location:17.1.0'
private GoogleApiClient googleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 请求定位权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
return;
}
Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null) {
double latitude = lastLocation.getLatitude();
double longitude = lastLocation.getLongitude();
// 在Google地图上显示当前位置
showLocationOnMap(latitude, longitude);
}
}
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
以上步骤中,我们使用了Google Play服务的FusedLocationApi来获取最后已知的位置。如果需要实时位置更新,可以使用LocationRequest和LocationListener。
推荐的腾讯云相关产品:腾讯位置服务(https://cloud.tencent.com/product/location)提供了丰富的定位服务,包括地理围栏、逆地址解析等功能,可与Android应用集成使用。
领取专属 10元无门槛券
手把手带您无忧上云