繁体   English   中英

自动更新地图活动中的用户位置(Android)

[英]Automatically updating the users location in a maps activity (Android)

所以我写了一个类,可以找到用户的位置并找到到另一个点的距离,但是我有一个随机数生成器,所以当我调用我在活动中使用的方法(重新启动活动)时,随机数会发生变化不想发生。 如果有人告诉我如何在单击按钮时刷新用户位置而不重新启动整个活动,那将是一个很大的帮助

public class MapsActivity extends FragmentActivity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    //These variable are initalized here as they need to be used in more than one methid
    private double currentLatitude; //lat of user
    private double currentLongitude; //long of user

    Random rand = new Random();
    int n = rand.nextInt(5) + 1;

    int score = 0;

    public static final String TAG = MapsActivity.class.getSimpleName();

    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

    //contains lat and lon of another place
    private void setUpMap() {


        if (n == 1) {
            MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
            mMap.addMarker(marker); // adding marker
        } else if (n == 2) {
            MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeSU, longitudeSU)).title("2"); //create marker
            mMap.addMarker(marker); // adding marker
        } else if (n == 3) {
            MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeArtsBuilding, longitudeArtsBuilding)).title("3"); //create marker
            mMap.addMarker(marker); // adding marker
        } else if (n == 4) {
            MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeJH, longitudeJH)).title("4"); //create marker
            mMap.addMarker(marker); // adding marker
        } else if (n == 5) {
            MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeForebell, longitudeForebell)).title("5"); //create marker
            mMap.addMarker(marker); // adding marker
        }
    }
    //contains your lat and lon
    private void handleNewLocation(Location location) {
        Log.d(TAG, location.toString());

        currentLatitude = location.getLatitude();
        currentLongitude = location.getLongitude();

        LatLng latLng = new LatLng(currentLatitude, currentLongitude);

        //mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
        MarkerOptions options = new MarkerOptions()
                .position(latLng)
                .title("You are here");
        mMap.addMarker(options);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom((latLng), 11.0F));
    }




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

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        // Create the LocationRequest object
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds

        //Refresh button. Will reset the location of your flag
        //If the user clicks the button, the activity is finished and restarted
        Button button2=(Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            public void onClick (View w){
                Intent intent = getIntent();
                finish();
                startActivity(intent);
            }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }

        }
    }
    @Override
    public void onConnected(Bundle bundle) {
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
        else {
            handleNewLocation(location);
        }
    }
    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                /*
                 * Thrown if Google Play services canceled the original
                 * PendingIntent
                 */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        handleNewLocation(location);
    }
 }

请注意,如果代码存在问题,我将其删除很多,因此仅是括号和其他内容。 我刚刚发布了所有这些信息,因此您可以了解发生了什么。 我只想刷新您的位置,而不是整个活动

Intent intent = getIntent();
                    finish();
                    startActivity(intent);

你可以试试这个吗? 我没有测试。

MarkerOptions markerOptions;
Marker marker;

private void setUpMap() {
  if(marker!= null)
    marker.remove();
  markerOptions = null;
  if (n == 1) {
        markerOptions = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker

  } else if (n == 2) {
        markerOptions =  new MarkerOptions().position(new LatLng(latitudeSU, longitudeSU)).title("2"); //create marker

  } else if (n == 3) {
        markerOptions = new MarkerOptions().position(new LatLng(latitudeArtsBuilding, longitudeArtsBuilding)).title("3"); //create marker

  } else if (n == 4) {
      markerOptions = new MarkerOptions().position(new LatLng(latitudeJH, longitudeJH)).title("4"); //create marker

  } else if (n == 5) {
        markerOptions = new MarkerOptions().position(new LatLng(latitudeForebell, longitudeForebell)).title("5"); //create marker

  }
 if(markerOptions!=null)
  marker = mMap.addMarker(markerOptions); // adding marker
}

然后在您的onclicklistener

 button2.setOnClickListener(new View.OnClickListener() {
        public void onClick (View w){
           n = rand.nextInt(5) + 1;
           setUpMap();
        }
});

或者,您可以使用marker.setPosition(LatLng); 如果您的标记不为空

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM