Как убрать маркер по одному в гугл карте? - PullRequest
0 голосов
/ 30 сентября 2019

enter image description here
Как убрать маркер по одному на карте Google? Я нажимаю кнопку Отменить, чтобы удалить маркер.

       mFbClearLastPins = (Button) rootView.findViewById(R.id.fab_last_one_clear);
        mFbClearLastPins.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("index-size", String.valueOf(latLng));
                Log.d("index", String.valueOf(index));
                Log.d("latLng", String.valueOf(latLng.size()));
                if (index > 0 && latLng.size() > 0) {
                    try {
                        latLng.remove(index - 1);
                        remove(mMarkers.get("name" + String.valueOf(index)).getTitle());
                        //  remove(mMarkers.get("marker" + String.valueOf(index)).getSnippet());
                        index--;
                        options = new PolylineOptions().width(20).color(Color.YELLOW).geodesic(true);
                    } catch (ArrayIndexOutOfBoundsException e) {
                        e.printStackTrace();
                    }

                } else {
                    googleMap.clear();
                }

            }
        });


package com.vvsugar.fragments.plotmaster;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

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.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.vvsugar.R;
import com.vvsugar.activity.MainActivity;
import com.vvsugar.dbview.plotmeasure.PlotMeasureDb;
import com.vvsugar.utils.AmtPref;
import com.vvsugar.utils.AppUtils;
import com.vvsugar.utils.Conversion;
import com.vvsugar.utils.GPSTracker;
import com.vvsugar.utils.SphericalUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import static android.content.ContentValues.TAG;


public class Map extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {
    static final int REQUEST_LOCATION = 2;
    private final java.util.Map<String, MarkerOptions> mMarkers = new ConcurrentHashMap<String, MarkerOptions>();
    protected LocationManager locationManager;
    MapView mMapView;
    ArrayList<LatLng> markerPoints;
    GoogleApiClient mGoogleApiClient;
    GPSTracker gpsTracker;
    List<LatLng> latLng = new ArrayList<>();
    PolylineOptions options = new PolylineOptions().width(20).color(Color.YELLOW).geodesic(true);
    PlotMeasureDb measureDb;
    View screen;
    Location mLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;
    ArrayList<LatLng> points;
    private GoogleMap googleMap;
    private FloatingActionButton sds;
    private Button mFabCompleted, mFabChangeTheme, mFabClearAllPins, mFbClearLastPins, mFabGetCurrentLocation;
    private int index = 0;
    private Polyline mPolyLine;
    private Location mCurrentLocation;
    private double longitude;
    private double latitude;
    private boolean isFirstTime = true;
    private FrameLayout mapdetail;
    private TextView areaFinder;
    private Button mDoneBtn;
    private Dialog dialog;
    private Bitmap bmScreen;
    private List<Marker> markers = new ArrayList<>();
    private MarkerOptions marker;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.plot_measure_fragment, container, false);
        gpsTracker = new GPSTracker(getActivity());
        mMapView = (MapView) rootView.findViewById(R.id.mapView);
        screen = rootView.findViewById(R.id.mapView);
        mapdetail = rootView.findViewById(R.id.mapdetail);
        areaFinder = rootView.findViewById(R.id.textViewAcre);
        mDoneBtn = rootView.findViewById(R.id.done);
        mFabChangeTheme = (Button) rootView.findViewById(R.id.fab_change_theme);
        mMapView.getMapAsync(this);

        mFabChangeTheme.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (googleMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL) {
                    mFabChangeTheme.setText("Map");
                    googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                } else {
                    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                    mFabChangeTheme.setText("Satelite View");
                }
            }
        });
        checkLocationPermission();
        mFabCompleted = (Button) rootView.findViewById(R.id.fab_completed);
        mFabCompleted.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int i;
                if (latLng.size() > 0) {
                    // latLng.clear();
                    for (i = 0; i < latLng.size(); i++) {
                        Log.d(TAG, "onMapReady: " + latLng.get(i));

                        options.add(latLng.get(i));
                    }
                    if (i > 0) {
                        options.add(latLng.get(0));

                        mPolyLine = googleMap.addPolyline(options);


                    }
                }


                mapdetail.setVisibility(View.VISIBLE);
                double metere = 1.329409963886882 * 0.0002471053815;
                final double acre = Conversion.meterToAcre(Conversion.arrondi(SphericalUtil.computeArea(latLng)));
                areaFinder.setText(String.format("%.2f", Double.parseDouble(String.valueOf(acre))) + " acr");
                mDoneBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DecimalFormat df = new DecimalFormat("#0.00");
                        measureDb = new PlotMeasureDb(AmtPref.getInstance().getPlotBitName(), String.valueOf(df.format(acre)));
                        measureDb.save();

                        AppUtils.switchFragment(new PlotMeasureDetailsGetFragment(), "Masters", true, (MainActivity) getActivity());

                    }
                });
                Log.d(TAG, "showmeasureArea: " + SphericalUtil.computeArea(latLng) + "meter-" + metere + "acre" + acre);
                Log.d(TAG, "acre: " + acre);
            }
        });
        mFabClearAllPins = (Button) rootView.findViewById(R.id.fab_all_clear);

        mFabClearAllPins.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: " + "called");
                if (mPolyLine != null)
                    mPolyLine.remove();
                latLng.clear();
                index = 0;
                Log.d("clearlatLng", String.valueOf(latLng.size()));
                options = new PolylineOptions().width(20).color(Color.YELLOW).geodesic(true);
                googleMap.clear();

            }
        });
        mFbClearLastPins = (Button) rootView.findViewById(R.id.fab_last_one_clear);
        mFbClearLastPins.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("index-size", String.valueOf(latLng));
                Log.d("index", String.valueOf(index));
                Log.d("latLng", String.valueOf(latLng.size()));
                if (index > 0 && latLng.size() > 0) {
                    try {
                        latLng.remove(index - 1);
                        remove(mMarkers.get("name" + String.valueOf(index)).getTitle());
                        //  remove(mMarkers.get("marker" + String.valueOf(index)).getSnippet());
                        index--;
                        options = new PolylineOptions().width(20).color(Color.YELLOW).geodesic(true);
                    } catch (ArrayIndexOutOfBoundsException e) {
                        e.printStackTrace();
                    }

                } else {
                    googleMap.clear();
                }

            }
        });
        mFabGetCurrentLocation = (Button) rootView.findViewById(R.id.fab_get_current_location);
        mFabGetCurrentLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {


                DrawPolyLines(googleMap);


            }
        });
        mMapView.onCreate(savedInstanceState);

        mMapView.onResume();

        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        mMapView.getMapAsync(this);

        return rootView;
    }

    private void remove(String name) {
        mMarkers.remove(name);

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                googleMap.clear();

                for (MarkerOptions item : mMarkers.values()) {
                    googleMap.addMarker(item);
                }
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();

    }


    @SuppressLint("MissingPermission")
    public void DrawPolyLines(GoogleMap mMap) {
        double latitude;
        double longitude;
        index++;
        googleMap = mMap;
        mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mCurrentLocation != null) {
            latitude = mCurrentLocation.getLatitude();
            longitude = mCurrentLocation.getLongitude();
        } else {
            latitude = gpsTracker.getLatitude();
            longitude = gpsTracker.getLongitude();
        }

        Toast.makeText(getContext(), String.valueOf(latitude + " " + longitude), Toast.LENGTH_LONG).show();

        int sze = latLng.size();
        Toast.makeText(getContext(), String.valueOf(sze), Toast.LENGTH_LONG).show();

        marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("" + String.valueOf(index));
        mMarkers.put("name" + String.valueOf(index), marker);
      /*  marker = new MarkerOptions().position(new LatLng(latitude, longitude)).snippet("" + String.valueOf(index));
        mMarkers.put("marker" + String.valueOf(index), marker);*/


        googleMap.addMarker(marker);


        // markers.add(mark);
        latLng.add(new LatLng(latitude, longitude));
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 100));
        //  Log.d(TAG, "onMapDistance: " + computeDistanceBetween(latLng.get(0), new LatLng(13.060233, 80.264376)));
        //    Log.d(TAG, "onMapComputeArea: " + computeArea(this.latLng));
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();


    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }

    public boolean checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

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


                new AlertDialog.Builder(getActivity())
                        .setTitle("")
                        .setMessage("")
                        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                ActivityCompat.requestPermissions(getActivity(), new String[]
                                        {Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                            }
                        })
                        .create()
                        .show();


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

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {


                    if (ContextCompat.checkSelfPermission(getActivity(),
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {


                        googleMap.setMyLocationEnabled(true);
                    }

                } else {


                }
                return;
            }


        }

    }

    @SuppressLint("MissingPermission")
    @Override
    public void onMapReady(GoogleMap googleMap) {
        this.googleMap = googleMap;

        googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                buildGoogleApiClient();
                googleMap.setMyLocationEnabled(true);
            }
        } else {
            buildGoogleApiClient();
            googleMap.setMyLocationEnabled(true);
        }


    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //dbAdapter = new DbAdapter(getContext());
    }

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

    @Override
    public void onLocationChanged(Location location) {

        mCurrentLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //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.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = googleMap.addMarker(markerOptions);

        Toast.makeText(getContext(), String.valueOf(mCurrentLocation.getLatitude() + " " + mCurrentLocation.getLongitude()), Toast.LENGTH_LONG).show();
        //move map camera
        //   googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 100));

        //stop location updates
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

        }

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            //  LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

            //move map camera
            mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            if (mCurrentLocation != null) {
                LatLng latLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(latLng);
                markerOptions.title("Current Position");
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
                mCurrLocationMarker = googleMap.addMarker(markerOptions);
                Toast.makeText(getContext(), String.valueOf(mCurrentLocation.getLatitude() + " " + mCurrentLocation.getLongitude()), Toast.LENGTH_LONG).show();
                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 100));
            }
            if (mGoogleApiClient.isConnected())
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

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

    }
}
google map pic


  [1]: https://i.stack.imgur.com/MiQd0.jpg

1 Ответ

0 голосов
/ 30 сентября 2019

Вы можете взять ArrayList, и когда вы добавляете маркер на карту Google, вам также необходимо добавить маркер в список.

ArrayList<Marker> markers = new ArrayList();

final Marker marker = activity.mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)));
markers.add(marker);

Когда вы хотите удалить маркер, вы можете получить маркер из списка и удалить его. маркер с карты.

Marker marker1 =markers.get(0);
marker1.remove();
...