当我的位置到达时隐藏标记并在我离开时再次显示

时间:2016-04-28 22:48:06

标签: android google-maps google-maps-android-api-2

我在地图中放了很多标记,并且已经提供了我当前的位置服务,所以只想在我当前位置到达时隐藏标记并在我离开时再次显示,请在回复时具体说明因为我是初学者“使用Android Studio 1.5.1”

这是我在MapsActivity.java中的代码

package com.example.karim.trysomething;

import android.content.Context;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;



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

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


private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

private GoogleMap mMap; 

private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;

@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();




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


}

@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 setUpMap() {



    if (ActivityCompat.checkSelfPermission(this,  android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        String[] permissions,

        return;
    }
    mMap.setMyLocationEnabled(true);


    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


    Criteria criteria = new Criteria();


    String provider = locationManager.getBestProvider(criteria, true);

    Location myLocation = locationManager.getLastKnownLocation(provider);


    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);



    double latitude = myLocation.getLatitude();


    double longitude = myLocation.getLongitude();


    LatLng latLng = new LatLng(latitude, longitude);


    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));


    mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
    mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located"));

    mMap.addMarker( new MarkerOptions()
            .position(new LatLng(30.121683, 31.139405) )
            .title("Location")
            .snippet("ركنة المطحن")).showInfoWindow();     


}



@Override
public void onConnected(Bundle bundle) {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location == null) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

    if (connectionResult.hasResolution()) {
        try {

            connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
        } catch (IntentSender.SendIntentException e) {

            e.printStackTrace();
        }
    } else {
        Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
    }
}


@Override
public void onLocationChanged(Location location) {

}
}

2 个答案:

答案 0 :(得分:2)

在深入研究代码之前,您应该定义“show”规则(逻辑)。简单地说,假设您每次都在半径250米的圆心(粉红色标记)。更改位置后,将每个标记位置与您的圆圈进行比较。隐藏位于圆圈中的标记,并显示其他标记。

enter image description here enter image description here

每当您的位置发生变化时,请调用此类方法

 // You have received new location and calling this method. 
 private void filterMarkers(LatLng myLocation){

    double myLatitude = myLocation.latitude;
    double myLongitude = myLocation.longitude;

    float[] distance = new float[2];
    for(int m = 0; m < mMarkers.size(); m++){
        Marker marker = mMarkers.get(m);
        LatLng position = marker.getPosition();
        double lat = position.latitude;
        double lon = position.longitude;

        /* distanceBetween method calculates the distance between two locations. 
           As i said above, you are in center of circle, means your location and 
           circle's location are same.

           Also you could look distanceBetween method
           http://developer.android.com/reference/android/location/Location.html#distanceBetween(double, double, double, double, float[])
         */
        Location.distanceBetween(lat, lon, myLatitude,
                myLongitude, distance);


        boolean inCircle = distance[0] <= mCircleRadius;
        // If marker is in circle hide it, otherwise show.
        marker.setVisible(!inCircle);
    }
}

答案 1 :(得分:0)

为了实现这一目标,你需要 1.使用标记lat / long比较当前纬度/经度,在回调中执行此操作,例如onMarkerRender,然后更改当前标记。 2.当您切换到下一个标记

时,保留当前标记,然后更改相同的标记