Java 谷歌地图api v2标记在我旋转手机和地图之前不会移动;“刷新”;
我有以下代码: 公共类MapsActivity扩展了FragmentActivity实现 GoogleAppClient.ConnectionCallbacks, GoogleAppClient.OnConnectionFailedListener, 位置侦听器{Java 谷歌地图api v2标记在我旋转手机和地图之前不会移动;“刷新”;,java,android,google-maps,location,marker,Java,Android,Google Maps,Location,Marker,我有以下代码: 公共类MapsActivity扩展了FragmentActivity实现 GoogleAppClient.ConnectionCallbacks, GoogleAppClient.OnConnectionFailedListener, 位置侦听器{ private GoogleMap mMap; // Might be null if Google Play services APK is not available. // LogCat tag private static
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
// LogCat tag
private static final String TAG = MapsActivity.class.getSimpleName();
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
// Location updates intervals in sec
private static int UPDATE_INTERVAL = 5000; // 10 sec
private static int FASTEST_INTERVAL = 1000; // 5 sec
private static int DISPLACEMENT = 5; // 10 meters
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
}
return false;
}
return true;
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
// First we need to check availability of play services
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
createLocationRequest();
}
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
@Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {//eliminando updates y desconectando
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// hacer una pruba de null para saber si mMap esta activo
if (mMap == null) {
// obtener el mapa por SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// verificar si el mapa esta activo
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {@link #mMap} is not null.
*/
private void setUpMap() {
}
@Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Servicios de localización activados");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) { //Se llama cuando no hay una ultima localización disponible
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
}
}
@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Servicios de localización suspendidos. Favor de reconectar.");
}
//Metodo para cuando la localización cambia
@Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Servicio de localización falló con el siguiente codigo: "+connectionResult.getErrorCode());
}
private void handleNewLocation(Location location) {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
//añadir un nuevo marker con la posición de la variable latLng
MarkerOptions camion = new MarkerOptions()
.position(latLng)
.title("Camión");
mMap.addMarker(camion);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(19);
mMap.animateCamera(zoom);
}
}
private GoogleMap mMap;//如果Google Play services APK不可用,则可能为空。
//LogCat标签
私有静态最终字符串标记=MapsActivity.class.getSimpleName();
专用最终静态整数播放服务解析请求=1000;
私人场所;
//Google客户端与Google API交互
私人GoogleapClient MGoogleapClient;
//用于切换定期位置更新的布尔标志
私有布尔值mRequestingLocationUpdates=false;
私人位置请求mLocationRequest;
//位置更新间隔(秒)
私有静态整型更新间隔=5000;//10秒
私有静态int最快_间隔=1000;//5秒
专用静态int位移=5;//10米
私有布尔值checkPlayServices(){
int resultCode=GooglePlayServicesUtil
.isGooglePlayServicesAvailable(此);
if(resultCode!=ConnectionResult.SUCCESS){
if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)){
GooglePlayServicesUtil.getErrorDialog(结果代码,此,
播放服务解决方案请求)。显示();
}
返回false;
}
返回true;
}
受保护的同步无效BuildGoogleAppClient(){
mgoogleapclient=新的Googleapclient.Builder(此)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API).build();
}
受保护的void createLocationRequest(){
mlLocationRequest=新位置请求();
mLocationRequest.setInterval(更新间隔);
mLocationRequest.SetFastTestInterval(最快间隔);
mLocationRequest.setPriority(位置请求.优先级高精度);
M定位请求。设置最小位移(位移);
}
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
setupmapifneed();
//首先,我们需要检查播放服务的可用性
如果(checkPlayServices()){
//构建GoogleApi客户端
buildGoogleAppClient();
createLocationRequest();
}
}
@凌驾
受保护的void onResume(){
super.onResume();
setupmapifneed();
mGoogleApiClient.connect();
}
@凌驾
受保护的void onPause(){
super.onPause();
如果(mgoogleapclient.isConnected()){//eliminando更新y desconectando
LocationServices.FusedLocationApi.RemovelocationUpdate(mgoogleapClient,this);
mGoogleApiClient.disconnect();
}
}
@凌驾
受保护的void onStop(){
super.onStop();
if(mgoogleapClient.isConnected()){
mGoogleApiClient.disconnect();
}
}
私有void setUpMapIfNeeded(){
//如果你的武器是空的,那么你就必须采取行动
如果(mMap==null){
//obtener el-mapa por SupportMapFragment。
mMap=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
//在地图上确认是否已激活
如果(mMap!=null){
setUpMap();
}
}
}
/**
*在这里,我们可以添加标记或线条、添加侦听器或移动摄影机
*在非洲附近加一个标记。
*
*当我们确定{@link#mMap}不是null时,应该只调用一次。
*/
私有void setUpMap(){
}
@凌驾
未连接的公共空间(捆绑包){
Log.i(标签“活动服务”);
Location Location=LocationServices.FusedLocationApi.getLastLocation(mgoogleapClient);
如果(location==null){//Se llama cuando no hay una ultima localización disponsible
LocationServices.FusedLocationApi.RequestLocationUpdate(mgoogleapClient、mlLocationRequest、this);
}
否则{
手柄位置(位置);
}
}
@凌驾
公共空间连接暂停(int i){
Log.i(标签“Servicios de localización suspendidos.Favor de reconectar.”);
}
//梅托多·帕拉·坎比亚地区
@凌驾
已更改位置上的公共无效(位置){
手柄位置(位置);
}
@凌驾
公共无效onConnectionFailed(ConnectionResult ConnectionResult){
Log.i(标签“Servicio de localización fallócon el siguiente codigo:”+connectionResult.getErrorCode());
}
专用无效句柄ewlocation(位置){
mLastLocation=LocationServices.FusedLocationApi
.getLastLocation(MGoogleapClient);
如果(mLastLocation!=null){
双纬度=mLastLocation.getLatitude();
double longitude=mLastLocation.getLongitude();
LatLng LatLng=新LatLng(纬度、经度);
//这是一个新的标记,它可以用来标记变量的位置
MarkerOptions camion=新的MarkerOptions()
.位置(车床)
.头衔(“卡米翁”);
mMap.addMarker(camion);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(19);
mMap.animateCamera(缩放);
}
}
我希望标记在手机移动时移动,但它不会移动,直到我旋转手机,屏幕旋转,然后地图刷新,标记移动到我的实际位置,有时标记会重复,如果我旋转手机,重复的标记会消失。
知道为什么会发生这种情况吗?谢谢当标记被复制时,您看到的实际上是系统在工作:
handleNewLocation(location)
并在上面添加一个新的标记:mMap.addMarker(camion);
if(mCamionMarker == null){
mCamionMarker = mMap.addMarker(camion);
}else{
mCamionMarker.setPosition(latLng);
}