如何使用Android中的Google Map上的当前位置更新当前位置标记

时间:2016-08-10 05:54:20

标签: android google-maps

我正在制作App。当我将一个位置移动到另一个位置时,我想在current location marker上使用current location更新我的Google Map。当前标记应该使用用户当前位置运行。

请告诉我如何使用以下源代码更新此内容...

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener,LocationListener {

GoogleMap mMap;
SupportMapFragment mFragment;
GoogleApiClient mGoogleApiClient;
LatLng latLng;
Marker CurrentMarker;
LocationRequest mLocationRequest;
Location mLastLocation;
boolean firstRun = true;
private Boolean exit = false;

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

   /* Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
      setSupportActionBar(toolbar);*/

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkLocationPermission();
        }

        mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mFragment.getMapAsync(this);
}

//for location permission marshmalow
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
    if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED){

        if(ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)){

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    }else{
        return true;
    }

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();

}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.getUiSettings().setMyLocationButtonEnabled(false);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                ==PackageManager.PERMISSION_GRANTED){
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);

        }
    }
    else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }

}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;

    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onConnected(Bundle bundle) {

    mLocationRequest = new LocationRequest();
    //  mLocationRequest.setInterval(1000);
    // mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this);
    }

}

@Override
public void onConnectionSuspended(int i) {
    Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();

}

@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;
    if(CurrentMarker != null){
        CurrentMarker.remove();
    }

    LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
    MarkerOptions markerOption = new MarkerOptions();
    markerOption.position(latLng);
    markerOption.title("Current Position");
    markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
    CurrentMarker = mMap.addMarker(markerOption);
    Toast.makeText(this,"Location changed",Toast.LENGTH_SHORT).show();
    CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(13).build();
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));


    if(mGoogleApiClient != null){
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
    }
}

// handle pemission after the allow the location of app..

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResult){
    switch (requestCode){
        case MY_PERMISSIONS_REQUEST_LOCATION: {

            if(grantResult.length > 0
                    && grantResult[0] == PackageManager.PERMISSION_GRANTED){
                if(ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    if(mGoogleApiClient == null){
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }

            }else {
                Toast.makeText(this, "permisison denied", Toast.LENGTH_LONG).show();
            }
            return;
        }
    }
}
}

当我将一个位置移动到另一个位置时,我当前的标记应该与当前位置一起移动。请告诉我..

由于

2 个答案:

答案 0 :(得分:1)

试试这样:

   private class Mylocationlistener implements LocationListener {

   private boolean zoomed = false;
   private boolean firstPass = true;

   @Override
   public void onLocationChanged(Location location) {

    if (location != null) {
        // ---Get current location latitude, longitude---

        Log.d("LOCATION CHANGED", location.getLatitude() + "");
        Log.d("LOCATION CHANGED", location.getLongitude() + "");
        currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
        currentLatLng = new LatLng(location.getLatitude(), location.getLongitude());
        Marker currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location"));
        // Move the camera instantly to hamburg with a zoom of 15.
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 15));
        // Zoom in, animating the camera.
        if (!zoomed) {
            mMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
            zoomed = true;
        }                                       
        if (!firstPass){
            currentLocationMarker.remove();
        }
        firstPass = false;
        Toast.makeText(MapViewActivity.this,"Latitude = "+
                location.getLatitude() + "" +"Longitude = "+ location.getLongitude(),
                Toast.LENGTH_LONG).show();

    }
}

或尝试这样

MarkerOptions a = new MarkerOptions()
a.position(LatLng);
Marker m = map.addMarker(a);
m.setPosition(LatLng);

答案 1 :(得分:0)

每次清除地图并在每次更改位置时添加新标记。请尝试使用此代码 -

 @Override
 public void onLocationChanged(Location location) {

   map.clear();

   MarkerOptions mp = new MarkerOptions();

   mp.position(new LatLng(location.getLatitude(), location.getLongitude()));

   mp.title("my position");

   map.addMarker(mp);

   map.animateCamera(CameraUpdateFactory.newLatLngZoom(
    new LatLng(location.getLatitude(), location.getLongitude()), 16));

  }