如何在MapView上每10秒显示一次当前位置



我想显示一个带有设备位置的MapView,并且每10秒更新一次位置。我已经找到了很多解决方案,但都不起作用,即使是官方的谷歌地图API也不起作用。我现在的代码是基本的MapActivity:

package org.cuatrovientos.app.pamplonanegra;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
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 MapActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Pamplona, Spain.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Cuatrovientos and move the camera
LatLng cuatrovientos = new LatLng(42.82452261, -1.6601049900);
mMap.addMarker(new MarkerOptions().position(cuatrovientos).title("Marker in Cuatrovientos"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(cuatrovientos));
}
}

我有以下权限:

<!-- Permisions -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.LOCATION" />
<uses-permission android:name="android.permission.PHONE" />
<uses-permission android:name="android.permission.INTERNET" />

当然,我在清单中有Google API密钥,这是在应用程序的build.gradle中编译的:

compile 'com.google.android.gms:play-services-maps:11.0.4'
compile 'com.google.android.gms:play-services-location:11.0.4'

我该怎么做?感谢

您在代码中没有请求用户位置,您只是显示地图并移动相机。

您需要按照文档中的描述进行请求

一些相关代码:

mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
})
.addOnFailureListener(new OnFailureListener() {
(...)                       
}
});

编辑:要使用最新版本的库,您必须将Google Repository添加到您的parent项目build.gradle中,方法如下:

allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}

这将有助于你不断更新你的SDK依赖,特别是"谷歌存储库">

最新更新