我要如何停止继续在Google Map中移动标记一次的地址?我想在Google Map上移动标记的特定点的地址

时间:2018-10-21 07:36:11

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

我的标记笔在地图上移动了一次,我一直在获取地址。如果我将标记笔移动到古吉拉特邦(印度),它将继续显示该位置的吐司消息,我该如何停止呢?

public class MainActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {

    private GoogleMap mMap;
    private boolean mLocationPermissionGranted = false;
    private final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 101;
    private FusedLocationProviderClient mFusedLocationClient;
    private Location mLastKnownLocation,mChangeLocation=new Location("");
    AddressResultReceiver mreceiver = null;
    private GoogleMap.OnCameraIdleListener onCameraIdleListener;
    private ImageView markerPin;
    private Marker mCurrLocationMarker;
    private LocationRequest mLocationRequest;

    private long UPDATE_INTERVAL = 10 * 1000;  /* 10 secs */
    private long FASTEST_INTERVAL = 2000; /* 2 sec */
    FusedLocationProviderClient mFusedLocationClient1;

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

        markerPin = (ImageView) findViewById(R.id.imgMarker);
        MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mFusedLocationClient = getFusedLocationProviderClient(this);
        getLocationPermission();
    }
    private void configureCameraIdle() {
        mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
            @Override
            public void onCameraIdle() {

                mMap.clear();
                LatLng latLng = mMap.getCameraPosition().target;
                Log.i("latLag",latLng.toString());
                mChangeLocation.setLatitude(latLng.latitude);
                mChangeLocation.setLongitude(latLng.longitude);
                MarkerOptions markerOptions1=new MarkerOptions();
                markerOptions1.position(latLng);
                mMap.addMarker(markerOptions1);
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
                //mMap.addMarker(new MarkerOptions().position(latLng).title("new"));
                startIntentService();

            }
        });
    }

    private void getLocationPermission() {
        Log.i("first","firstmethod");
        if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
                android.Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            Log.i("second","second");
            mLocationPermissionGranted = true;

            Task<Location> locationTask = mFusedLocationClient.getLastLocation();
            locationTask.addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // Got last known location
                    if (location != null) {
                        mLastKnownLocation = location;
                        Log.d("result", mLastKnownLocation.toString());
                        setMarker(location);
                        //configureCameraIdle();
                        //startLocationUpdates();

                    }
                }
            });
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                    PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
        }
    }

    private void setMarker(Location location) {

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin));
        mCurrLocationMarker = mMap.addMarker(markerOptions);
        //move map camera

        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 100);
        mMap.animateCamera(cameraUpdate);
        configureCameraIdle();

    }


    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        mLocationPermissionGranted = false;
        switch (requestCode) {
            case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mLocationPermissionGranted = true;
                }
            }
        }
    }

    void startIntentService() {

        mreceiver = new AddressResultReceiver(new android.os.Handler());
        Intent intent = new Intent(this, FetchAddressIntentService.class);
        intent.putExtra(FetchAddressIntentService.Constants.RECEIVER, mreceiver);
        intent.putExtra(FetchAddressIntentService.Constants.LOCATION_DATA_EXTRA, mChangeLocation);
        startService(intent);

    }


    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

    }

    @Override
    public void onConnectionSuspended(int i) {

    }
    class AddressResultReceiver extends ResultReceiver
    {

        Handler handler=new Handler();
        public AddressResultReceiver(Handler handler) {
            super(handler);
            this.handler=handler;
        }

        protected void onReceiveResult(int resultCode, Bundle resultData) {
            String  mAddressOutput = resultData.getString(FetchAddressIntentService.Constants.RESULT_DATA_KEY);
            Log.i("address", mAddressOutput);
            //address.setText(mAddressOutput);

            if (resultCode == FetchAddressIntentService.Constants.SUCCESS_RESULT) {

                Toast.makeText(MainActivity.this,mAddressOutput,Toast.LENGTH_LONG).show();
            }
        }
    }
}

FetchAddressIntentService.java:

public class FetchAddressIntentService extends IntentService {

    ResultReceiver myReciever;

    public FetchAddressIntentService(){
        super("Fetching address");

    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        String errorMessage = "";
        //Get the location passed to this serviec thorugh an extra
        Location location = intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);
        myReciever=intent.getParcelableExtra(Constants.RECEIVER);

        List<Address> address = null;
        try{
            address = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
            Toast.makeText(this,address.get(0).getAddressLine(0).toString(),Toast.LENGTH_LONG).show();
        }
        catch(Exception e){
            Toast.makeText(this,e.getMessage(), Toast.LENGTH_LONG).show();
        }

        //Handle the case when there is no location found
        if(address == null || address.size() == 0){
            Toast.makeText(this, "No address found", Toast.LENGTH_LONG).show();
            deliverResulttoReciever(Constants.FAILURE_RESULT,"No address Found");
        }
        else{
            Address currentAddress = address.get(0);
            ArrayList<String> addressFragment = new ArrayList<String>();

            //Fetch the address lines using getAddressLine
            //join them and send them to the thread
            for(int i = 0;i<=currentAddress.getMaxAddressLineIndex();i++)
            {
                addressFragment.add(currentAddress.getAddressLine(i));
            }
            deliverResulttoReciever(Constants.SUCCESS_RESULT, TextUtils.join(System.getProperty("line.saparator"),addressFragment));
        }

    }

    private void deliverResulttoReciever(int resultCode, String message) {
        Bundle bundle = new Bundle();
        bundle.putString(Constants.RESULT_DATA_KEY,message);
        myReciever.send(resultCode,bundle);
    }

    public final class Constants {
        public static final int SUCCESS_RESULT = 0;
        public static final int FAILURE_RESULT = 1;
        public static final String PACKAGE_NAME =
                "com.google.android.gms.location.sample.locationaddress";
        public static final String RECEIVER = PACKAGE_NAME + ".RECEIVER";
        public static final String RESULT_DATA_KEY = PACKAGE_NAME +
                ".RESULT_DATA_KEY";
        public static final String LOCATION_DATA_EXTRA = PACKAGE_NAME +
                ".LOCATION_DATA_EXTRA";
    }
}

我的标记笔在地图上移动了一次,我一直在获取地址。如果我将标记笔移动到古吉拉特邦(印度),它将继续显示该位置的吐司消息,我该如何停止呢?

LogCat:

I/address: Gujarat 383317, India I/address: Gujarat 383317, India I/address: Gujarat 383317, India I/address: Gujarat 383317, India I/address: Gujarat 383317, India I/address: Gujarat 383317, India I/address: Gujarat 383317, India I/address: Gujarat 383317, India I/address: Gujarat 383317, India I/address: Gujarat 383317, India I/address: Gujarat 383317, India I/address: Gujarat 383317, India I/address: Gujarat 383317, India I/address: Gujarat 383317, India I/address: Gujarat 383317, India I/address: Gujarat 383317, India I/address: Gujarat 383317, India

0 个答案:

没有答案