Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
animateCamera android返回活动时不工作_Android_Google Maps_Google Maps Markers_Google Maps Android Api 2 - Fatal编程技术网

animateCamera android返回活动时不工作

animateCamera android返回活动时不工作,android,google-maps,google-maps-markers,google-maps-android-api-2,Android,Google Maps,Google Maps Markers,Google Maps Android Api 2,我正在努力使用Android谷歌地图API的animateCamera方法,但它只运行一次。一段时间后,当我回到活动中时,它根本不起作用。我不知道为什么当我第一次打开“活动”时它不工作,但在那之后它就不工作了,我调试代码并检查是否抛出了任何错误,但没有捕获到任何错误。即使animateCamera方法调用也在平稳运行,但在再次返回活动后,map并没有设置动画以定位 public class MapsActivity extends Activity { private static G

我正在努力使用Android谷歌地图API的animateCamera方法,但它只运行一次。一段时间后,当我回到活动中时,它根本不起作用。我不知道为什么当我第一次打开“活动”时它不工作,但在那之后它就不工作了,我调试代码并检查是否抛出了任何错误,但没有捕获到任何错误。即使animateCamera方法调用也在平稳运行,但在再次返回活动后,map并没有设置动画以定位

public class MapsActivity extends Activity {

    private static GoogleMap mGoogleMap = null;
    private static final String TAG = "MapsActivity";
    private Button mBtnStartRide, mBtnPauseRide, mBtnStopRide = null;
    private static TextView mTxtLatLong, mTxtTimer, mTxtTotalSize,
            mTxtSpeed = null;
    private static PolylineOptions mRectLine = null;
    // Storing the directions returned by the direcction api
    private static ArrayList<LatLng> mDirectionsPoints = new ArrayList<LatLng>();
    private SharedPreferences mPreferences = null;
    private MyBroadcastReceiver receiver = null;

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

        receiver = new MyBroadcastReceiver();
        mPreferences = getSharedPreferences(Preferences.PREFERENCES,
                Context.MODE_PRIVATE);

        mTxtLatLong = (TextView) findViewById(R.id.txtLatLong);
        mTxtTimer = (TextView) findViewById(R.id.txtTimer);
        mTxtTotalSize = (TextView) findViewById(R.id.txtDirectionsSize);
        mTxtSpeed = (TextView) findViewById(R.id.txtSpeed);

        mBtnStartRide = (Button) findViewById(R.id.btn_start_ride);
        mBtnPauseRide = (Button) findViewById(R.id.btn_pause_ride);
        mBtnStopRide = (Button) findViewById(R.id.btn_stop_ride);

        mBtnStartRide.setOnClickListener(btnStartRideClickListener);
        mBtnPauseRide.setOnClickListener(btnPauseRideClickListener);
        mBtnStopRide.setOnClickListener(btnStopRideClickListener);

        initilizeMap();
    }

    /**
     * Start Ride Button Click Listener
     */
    private OnClickListener btnStartRideClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mPreferences.getBoolean(Preferences.IS_RIDE_PAUSE, false)) {
                if (RidingTimerService.getInstance() != null) {
                    RidingTimerService.getInstance().reStartRide();
                }
            } else {
                startService(new Intent(MapsActivity.this,
                        RidingTimerService.class));
            }

            mPreferences.edit()
                    .putBoolean(Preferences.IS_RIDE_STOPPED, false)
                    .commit();

            mBtnStartRide.setVisibility(View.GONE);
            mBtnPauseRide.setVisibility(View.VISIBLE);
            mBtnStopRide.setVisibility(View.VISIBLE);
        }
    };

    /**
     * Start Ride Button Click Listener
     */
    private OnClickListener btnPauseRideClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            RidingTimerService.getInstance().pauseRide();
            mPreferences.edit().putBoolean(Preferences.IS_RIDE_PAUSE, true)
                    .commit();
            mBtnStartRide.setVisibility(View.VISIBLE);
            mBtnPauseRide.setVisibility(View.GONE);
            mBtnStopRide.setVisibility(View.VISIBLE);
        }
    };

    /**
     * Stop Ride Button Click Listener
     */
    private OnClickListener btnStopRideClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            stopService(new Intent(MapsActivity.this,
                    RidingTimerService.class));
            mPreferences.edit().remove(Preferences.IS_RIDE_PAUSE).commit();
            mPreferences.edit()
                    .putBoolean(Preferences.IS_RIDE_STOPPED, true).commit();
            mDirectionsPoints.clear();
            mBtnStartRide.setVisibility(View.VISIBLE);
            mBtnPauseRide.setVisibility(View.GONE);
            mBtnStopRide.setVisibility(View.GONE);
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, new IntentFilter(
                Constants.BROADCAST_INTENT));
        initilizeMap();

        if (mPreferences.getBoolean(Preferences.IS_RIDE_STOPPED, false)) {
            // Show start button and gone Pause & Stop both
            mBtnStartRide.setVisibility(View.VISIBLE);
            mBtnPauseRide.setVisibility(View.GONE);
            mBtnStopRide.setVisibility(View.GONE);
        } else if (mPreferences
                .getBoolean(Preferences.IS_RIDE_PAUSE, false)) {
            mBtnStartRide.setVisibility(View.VISIBLE);
            mBtnPauseRide.setVisibility(View.GONE);
            mBtnStopRide.setVisibility(View.VISIBLE);
        } else {
            mBtnStartRide.setVisibility(View.GONE);
            mBtnPauseRide.setVisibility(View.VISIBLE);
            mBtnStopRide.setVisibility(View.VISIBLE);
        }

        setAllText();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    /**
     * Function to load map. If map is not created it will create it for you
     * */
    private void initilizeMap() {
        if (mGoogleMap == null) {
            mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();
            // check if map is created successfully or not
            if (mGoogleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            } else {
                mGoogleMap.setMyLocationEnabled(true);
                mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
                mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
                mGoogleMap.getUiSettings().setCompassEnabled(true);
                mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
                mGoogleMap.getUiSettings().setZoomControlsEnabled(true);

                mRectLine = new PolylineOptions().width(6).color(Color.BLUE);
            }
        } else {
            mGoogleMap.setMyLocationEnabled(true);
            mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
            mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
            mGoogleMap.getUiSettings().setCompassEnabled(true);
            mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
            mGoogleMap.getUiSettings().setZoomControlsEnabled(true);

            mRectLine = new PolylineOptions().width(6).color(Color.BLUE);
            animateCameraTo(mDirectionsPoints.get(0).latitude,
                    mDirectionsPoints.get(0).longitude);
        }
    }

    /**
     * Handler which handle the timer of ride
     */
    public static Handler mCountDownHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            Log.i(TAG, msg.getData().getString("time"));
            mTxtTimer.setText("Timer - " + msg.getData().getString("time"));
        };
    };

    /**
     * @author Scorpion
     * 
     */
    private class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            mDirectionsPoints.add(new LatLng(intent.getExtras().getDouble(
                    Preferences.LATITUDE), intent.getExtras().getDouble(
                    Preferences.LONGITUDE)));

            setAllText();

            if (!mDirectionsPoints.isEmpty() && mDirectionsPoints.size() == 1) {
                mGoogleMap.addMarker(new MarkerOptions()
                        .position(mDirectionsPoints.get(0)).anchor(0.8f, 1.0f)
                        .title("Your Location"));
            }

            animateCameraTo(
                    intent.getExtras().getDouble(Preferences.LATITUDE),
                    intent.getExtras().getDouble(Preferences.LONGITUDE));
        }

    }

    /**
     * 
     */
    public void setAllText() {
        mTxtLatLong.setText("Lat - "
                + mPreferences.getString(Preferences.LATITUDE, "0.0")
                + ", Lng - "
                + mPreferences.getString(Preferences.LONGITUDE, "0.0"));

        mTxtSpeed.setText("Speed - "
                + mPreferences.getString(Preferences.SPEED, "0.0"));

        mTxtTotalSize.setText("Distance - "
                + mPreferences.getString(Preferences.DISTANCE, "0.0"));
    }

    /**
     * Animate to position on Google Maps
     * 
     * @param lat
     * @param lng
     */
    private void animateCameraTo(final double lat, final double lng) {
        // Saving the points in a polyline
        for (int i = 0; i < mDirectionsPoints.size(); i++) {
            // Elevation array
            mRectLine.add(mDirectionsPoints.get(i));
        }

        // Drawing the path on the map
        mGoogleMap.addPolyline(mRectLine);

        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
                new LatLng(lat, lng), 17);
        mGoogleMap.animateCamera(cameraUpdate);
    }
}
我所希望的是,每当用户再次返回此活动时,他也应该能够看到路径和位置标记。我正在存储所有的lat长度,所以这对我来说不是问题,但是animateCamera和markers现在都不起作用。第一次使用谷歌地图v2,所以不确定到底是什么问题。期待得到一些快速的帮助或提示。

试试这个:

创建自己的类,如:

public class MapUtil {

    public static void animateMapToPositionAndZoom(GoogleMap googleMap, LatLng position, float zoomLevel) {
        Log.i("animate map to position and zoom","Camera update on location change inclucding zoom");
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(position, zoomLevel);
        googleMap.moveCamera(cameraUpdate);
    }
}
在活动中覆盖此选项:

private LatLng myLatLng;
@Override
public void onConnected(Bundle arg0) {
    if (myLatLng!= null) {
        MapUtil.animateMapToPositionAndZoom(googleMap, myLatLng, currentZoomLevel);
    }
}

希望它能帮助您。

您好,您可以使用SharedReference然后缓存位置。重新打开应用程序时,你可以调用animateCamera。重要性,位置更改时保存位置

public View onCreateView(final LayoutInflater layoutInflater, final ViewGroup viewGroup, final Bundle bundle) {
    SupportMapFragment.newInstance();
    ...


    new Thread(new Runnable() {
        @Override
        public void run() {
            SystemClock.sleep(1000);
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    // same SharedPreference
                    String model = SharedManager.getInstant(activity).getModel(Constant.CACHE_LOCATION);
                    if(model == null || model.isEmpty()){
                        return;
                    }
                    try {
                        LatLng latLng = new Gson().fromJson(model, LatLng.class);
                        animateCamera(latLng);
                    } catch (Exception e) {
                    }
                }
            });
        }
    }).start();
    return inflate;
}

private void animateCamera(LatLng latLng) {
    final CameraPosition cameraPosition = new CameraPosition.Builder().target(
            latLng).zoom(15).build();
    googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), new GoogleMap.CancelableCallback() {
        @Override
        public void onFinish() {
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    // todo something
                }
            });
        }

        @Override
        public void onCancel() {

        }
    });
}

当我返回到其他活动并返回到此活动时,它只加载地图,而不加载其他内容。但所有与animateCamera和标记相关的代码都会执行。
public View onCreateView(final LayoutInflater layoutInflater, final ViewGroup viewGroup, final Bundle bundle) {
    SupportMapFragment.newInstance();
    ...


    new Thread(new Runnable() {
        @Override
        public void run() {
            SystemClock.sleep(1000);
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    // same SharedPreference
                    String model = SharedManager.getInstant(activity).getModel(Constant.CACHE_LOCATION);
                    if(model == null || model.isEmpty()){
                        return;
                    }
                    try {
                        LatLng latLng = new Gson().fromJson(model, LatLng.class);
                        animateCamera(latLng);
                    } catch (Exception e) {
                    }
                }
            });
        }
    }).start();
    return inflate;
}

private void animateCamera(LatLng latLng) {
    final CameraPosition cameraPosition = new CameraPosition.Builder().target(
            latLng).zoom(15).build();
    googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), new GoogleMap.CancelableCallback() {
        @Override
        public void onFinish() {
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    // todo something
                }
            });
        }

        @Override
        public void onCancel() {

        }
    });
}