- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想为此定期(比如每 2 分钟)获取当前位置更新 我遵循官方文档,我编写了这段代码,但它不会每两分钟提供一次当前位置更新,即使在我传递的 LocationRequest 对象中指定也是如此在 requestLocationUpdates() 中,这里是代码:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private FusedLocationProviderClient FusedLocationClient;
private GoogleApiClient mGoogleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
SupportMapFragment map =
getSupportFragmentManager().findFragmentById(R.id.map));
map.getMapAsync(this);
FusedLocationClient LocationServices.getFusedLocationProviderClient(this);
}
@Override
public void onConnected(Bundle bundle) {
FusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
Log.i("MainActivity ", "" + location.getLongitude())
}
}
});
FusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
FusedLocationClient.requestLocationUpdates(requestLocation(),
new LocationCallback(){
@Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
Log.i("MainActivity ", "" + location.getLongitude());
//not getting current location updates every 2 minutes
}
};
},null);
}
@Override
public void onConnectionSuspended(int i) {}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
最佳答案
这类似于我的 other answer here , 更新为使用最近推出的 FusedLocationProviderClient类。
为了将 FusedLocationProviderClient 与 Google map 结合使用:
等到 Google map 准备好
如果需要,在运行时请求位置权限
获得许可后请求位置更新
获取用户位置后更新 Google map
首先确保您至少使用 Google Play 服务版本 11,因为旧版本没有 FusedLocationProviderClient 类(新版本也可以):
dependencies {
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'
//........
}
请注意,FusedLocationProviderClient 存在于 11.0.2 版本中,但由于初始实现中的错误,建议您仅在 11.6.0 及更高版本上使用此类。来自文档:
Note: It's recommended to use Google Play services version 11.6.0 or higher, which includes bug fixes for this class.
在AndroidManifest.xml文件中,manifest
标签内,application
标签外添加位置权限:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
将 API key 添加到 application
标记内的 AndroidManifest.xml 中:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIza___YOUR_KEY_HERE______"/>
Kotlin
这是 Kotlin 中的完整 Activity 类:
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
lateinit var mGoogleMap: GoogleMap
var mapFrag: SupportMapFragment? = null
lateinit var mLocationRequest: LocationRequest
var mLastLocation: Location? = null
internal var mCurrLocationMarker: Marker? = null
internal var mFusedLocationClient: FusedLocationProviderClient? = null
internal var mLocationCallback: LocationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
val locationList = locationResult.locations
if (locationList.isNotEmpty()) {
//The last location in the list is the newest
val location = locationList.last()
Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude())
mLastLocation = location
if (mCurrLocationMarker != null) {
mCurrLocationMarker?.remove()
}
//Place current location marker
val latLng = LatLng(location.latitude, location.longitude)
val markerOptions = MarkerOptions()
markerOptions.position(latLng)
markerOptions.title("Current Position")
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA))
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions)
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11.0F))
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
supportActionBar?.title = "Map Location Activity"
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
mapFrag = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
mapFrag?.getMapAsync(this)
}
public override fun onPause() {
super.onPause()
//stop location updates when Activity is no longer active
mFusedLocationClient?.removeLocationUpdates(mLocationCallback)
}
override fun onMapReady(googleMap: GoogleMap) {
mGoogleMap = googleMap
mGoogleMap.mapType = GoogleMap.MAP_TYPE_HYBRID
mLocationRequest = LocationRequest()
mLocationRequest.interval = 120000 // two minute interval
mLocationRequest.fastestInterval = 120000
mLocationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
//Location Permission already granted
mFusedLocationClient?.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper())
mGoogleMap.isMyLocationEnabled = true
} else {
//Request Location Permission
checkLocationPermission()
}
} else {
mFusedLocationClient?.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper())
mGoogleMap.isMyLocationEnabled = true
}
}
private fun checkLocationPermission() {
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.ACCESS_FINE_LOCATION
)
) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton(
"OK"
) { _, _ ->
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(
this@MapsActivity,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
MY_PERMISSIONS_REQUEST_LOCATION
)
}
.create()
.show()
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
MY_PERMISSIONS_REQUEST_LOCATION
)
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>, grantResults: IntArray
) {
when (requestCode) {
MY_PERMISSIONS_REQUEST_LOCATION -> {
// If request is cancelled, the result arrays are empty.
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
mFusedLocationClient?.requestLocationUpdates(
mLocationRequest,
mLocationCallback,
Looper.myLooper()
)
mGoogleMap.setMyLocationEnabled(true)
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show()
}
return
}
}// other 'case' lines to check for other
// permissions this app might request
}
companion object {
val MY_PERMISSIONS_REQUEST_LOCATION = 99
}
}
Java
这是 Java 中完整的 Activity 类:
public class MapsActivity extends AppCompatActivity
implements OnMapReadyCallback {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
FusedLocationProviderClient mFusedLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
getSupportActionBar().setTitle("Map Location Activity");
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
@Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(120000); // two minute interval
mLocationRequest.setFastestInterval(120000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
}
LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
//The last location in the list is the newest
Location location = locationList.get(locationList.size() - 1);
Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude());
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
}
};
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
activity_maps.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".map.MapsActivity">
<fragment android:id="@+id/map"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".map.MapsActivity"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</androidx.constraintlayout.widget.ConstraintLayout>
系统将提示用户接受位置权限:
位置将在应用启动时更新,并且每两分钟更新一次:
关于 AndroidX 的额外说明
如果您使用的是 AndroidX,you might need to add these lines到您的 gradle.properties
文件(有关更多信息,请参阅 here):
android.useAndroidX=true
android.enableJetifier=true
关于java - 如何使用 FusedLocationProviderClient 在 GoogleMap 中获取当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48633859/
我正在尝试将 Google map 集成到我的 xcode 项目中。我严格按照说明here .不幸的是我得到一个错误: error: 'GoogleMaps/GoogleMaps.h' file no
对不起,我是 iOS 开发新手。我使用来自 here 的库在谷歌地图中获取两个地方的方向。我曾经使用过谷歌地图。导入 Google Maps Framework 后,仍然出现错误... 问题是: 如何
我的应用程序有问题。 当我尝试在 上构建它时Android Studio 一切正常,但是当我尝试在 上构建它时Xcode 我遇到错误并且构建失败。 原因似乎来自AirMaps: 词法或预处理器问题'G
昨天我收到一封来自谷歌的电子邮件,说我可以访问 ios 的 map api,我从应用程序控制台生成了我的 key ,然后我按照 https://developers.google.com/maps/d
我想使用谷歌地图显示一些标记。信息(坐标)存储在本地 *.csv 文件中(我想使用“资源文件”)。 如何读取这个 *.csv 文件?如果我使用“jQuery.get('myFile.csv', fun
我正在尝试找出为什么谷歌地图在一天后的表现与一天前有所不同。 我最近将客户的网站上线。地理定位出现错误,我已修复它。但没有在测试站点上修复它。 今天,在两侧(固定一侧和测试一侧)我的地理位置开始显示非
我正在尝试使用地理编码来获取地址,计算出经度和纬度,然后在 map 上显示叠加层。 我正在使用下面的代码,但是日志条目 Log.e("Found",""+lat);永远不会触发,我不知道为什么。有人可
我尝试了大约 4 个小时,但没有发生。尝试开发一个应用程序来显示谷歌地图中的特定位置。 执行以下代码: GooglemapsActivity.java package com.example.gps2
我在尝试显示 googlemaps 时遇到错误 如果我加载 googlemaps javascript 源 我在 Firebug 中得到这个错误 syntax error [Break on this
我正在尝试在 swift 上创建一个 View Controller 来显示用户所在的位置。我已经实现了谷歌地图,所以现在我所要做的就是插入正确的代码。这样做时,我不断收到这两条错误消息,然后应用程序
我正在构建一个出租车应用程序,我设法将所有带有出租车标记图标的汽车添加到它们的确切位置。 但不知为何,所有的图标都看错了方向, 这是我想要实现的目标: 但我得到: 我的代码: 在这里,我只是将我从服务
问题是我向我的应用程序添加了 GoogleMap Activity ,我什至获得了 key ,但 map 只显示在模拟器中。当我在不同的设备上下载我的应用程序时, map 无法使用。我所能看到的只是一
我有两个动画要按顺序在谷歌地图上执行。所以在动画 1 完成后,动画 2 可以继续。 这可以通过这样的回调轻松完成: googleMap.animateCamera(CameraUpdateFacto
最近我的客户想添加这样的功能:当用户有 Internet 连接时, map 会正常显示,但当用户离线启动应用程序时(即使刚刚安装后), map 不会显示,但他仍然可以看到其区域上的标记,但带有自定义背
我正在处理一个处理 map Activity 的项目。我正在运行一个由单个 Activity MaptestActivity 组成的测试应用程序,它扩展了 MapActivity 并且什么都不做。我将
在我的应用程序中,我使用 GoogleMap (play-services-maps:10.2.1)。我已将 map 的位置固定在特定位置,但我不希望我的用户能够移动 map 。我只希望他能够放大它。
我是 java 和 android 的新手。我遇到了一个基本问题。 在这个给定的 fragment 中,我可以将 GoogleMap 对象添加为 parcelable 而无需任何额外的 pracela
我用 googlemap api 制作了一个 android 应用程序,并在叠加层上绘制了一些 16x16 png(大约 200 个)。当我移动或放大/放大 map View 时,经常出现“内存不足”
我正在关注https://developers.google.com/maps/documentation/javascript/directions到目前为止, map 计算特定点之间的距离,但我需
我的 VueJS/Laravel 应用程序没有像我预期的那样正确加载到 GoogleMaps 中。我不明白为什么不调用回调。该功能可用并且应该加载。你能帮助我吗?我没有发现我的错误。我不希望看到 ma
我是一名优秀的程序员,十分优秀!