簡體   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