从谷歌地图Android中删除最后一条折线?

时间:2016-08-25 12:21:24

标签: android google-maps android-maps-v2 android-maps-utils

我在select创建了一个latitudes longitudesqlite的课程,然后在地图上标记,然后绘制polyLine

问题:

每当我select我的记录100到100,当我看到前100然后我清除地图然后我得到第二100但是当我开始动画它最后显示我polyline我怎么能清除最后折线?

我的代码:

public class PathActivity_F extends AppCompatActivity implements OnMapReadyCallback {
    private GoogleMap mMap;
    Query_DB QDB;
    private List<Marker> markers = new ArrayList<>();
    private final Handler mHandler = new Handler();
    ImageView imgBack, imgClear, imgStop, imgPath, imgToggle, imgForward;
    boolean flag = true;
    int loadLimit = 0;
    int ival = 0;
    boolean ff = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_path);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.mapPath);
        mapFragment.getMapAsync(this);
        imgBack = (ImageView) findViewById(R.id.imgBack);
        imgClear = (ImageView) findViewById(R.id.imgClear);
        imgStop = (ImageView) findViewById(R.id.imgStop);
        imgPath = (ImageView) findViewById(R.id.imgPath);
        imgToggle = (ImageView) findViewById(R.id.imgToggle);
        imgForward = (ImageView) findViewById(R.id.imgForward);
        Button btnFill = (Button) findViewById(R.id.btnFill);
        Button btnStop = (Button) findViewById(R.id.btnStop);
        Button btnClear = (Button) findViewById(R.id.btnClear);
        Button btnToggle = (Button) findViewById(R.id.btnToggle);*/
        QDB = new Query_DB(PathActivity_F.this);

        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addLocations();
            }
        });
        imgForward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        imgPath.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                animator.startAnimation(true);
            }
        });
        imgStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                animator.stopAnimation();
            }
        });
        imgClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearMarkers();
            }
        });
        imgToggle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleStyle();
            }
        });

    }

    public void toggleStyle() {
        if (GoogleMap.MAP_TYPE_NORMAL == mMap.getMapType()) {
            mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        } else {
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        }
    }

    /**
     * Clears all markers from the map.
     */
    public void clearMarkers() {
        mMap.clear();
        markers.clear();
    }


    private void addLocations() {
        List<Marketing_Points_B> listPath = new ArrayList<>();
        listPath.clear();
        markers.clear();
        String query;

        if (flag) {
            query = "select Time,Lat,Lng from ReportAct_tbl group by LatLng order by Time ASC LIMIT 100; ";
            flag = false;
        } else {
            loadLimit = ival + 100;
            ival = loadLimit;
            query = "select Time,Lat,Lng from ReportAct_tbl group by LatLng order by Time ASC LIMIT 100 OFFSET " + loadLimit + ";";
        }
        Cursor cursor = QDB.db().rawQuery(query, null);
        cursor.moveToFirst();


        try {
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    do {
                        Marketing_Points_B MP = new Marketing_Points_B();
                        Double lat = cursor.getDouble(cursor.getColumnIndex("Lat"));
                        Double lng = cursor.getDouble(cursor.getColumnIndex("Lng"));
                        String Time = cursor.getString(cursor.getColumnIndex("Time"));
                        MP.setLat(lat);
                        MP.setLng(lng);
                        MP.setTime(Time);
                        listPath.add(MP);
                    } while (cursor.moveToNext());
                }
            }
        } catch (Exception ex) {
        } finally {
            cursor.close();
            QDB.db().close();
        }

        for (int i = 0; i < listPath.size(); i++) {
            Double lat = listPath.get(i).getLat();
            Double lng = listPath.get(i).getLng();
            addMarkerToMap(new LatLng(lat, lng));
        }


    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(34.637727, 50.877688);
        mMap.addMarker(new MarkerOptions().position(sydney).title("OK").icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_red)));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));


    }

    private Animator animator = new Animator();
    int currentPt;

    GoogleMap.CancelableCallback MyCancelableCallback =
            new GoogleMap.CancelableCallback() {

                @Override
                public void onCancel() {
                    System.out.println("onCancelled called");
                }

                @Override
                public void onFinish() {


                    if (++currentPt < markers.size()) {

                        float targetBearing = bearingBetweenLatLngs(mMap.getCameraPosition().target, markers.get(currentPt).getPosition());

                        LatLng targetLatLng = markers.get(currentPt).getPosition();


                        Log.i("currentPt", "currentPt  = " + currentPt);
                        Log.i("size", "size  = " + markers.size());
                        //Create a new CameraPosition
                        CameraPosition cameraPosition =
                                new CameraPosition.Builder()
                                        .target(targetLatLng)
                                        .tilt(currentPt < markers.size() - 1 ? 90 : 0)
                                        .bearing(targetBearing)
                                        .zoom(mMap.getCameraPosition().zoom)
                                        .build();


                        mMap.animateCamera(
                                CameraUpdateFactory.newCameraPosition(cameraPosition),
                                3000,
                                MyCancelableCallback);
                        System.out.println("Animate to: " + markers.get(currentPt).getPosition() + "\n" +
                                "Bearing: " + targetBearing);

                        markers.get(currentPt).showInfoWindow();

                    } else {
                    }

                }

            };

    private float bearingBetweenLatLngs(LatLng begin, LatLng end) {
        Location beginL = convertLatLngToLocation(begin);
        Location endL = convertLatLngToLocation(end);

        return beginL.bearingTo(endL);
    }

    private Location convertLatLngToLocation(LatLng latLng) {
        Location loc = new Location("someLoc");
        loc.setLatitude(latLng.latitude);
        loc.setLongitude(latLng.longitude);
        return loc;
    }

    public class Animator implements Runnable {

        private static final int ANIMATE_SPEEED = 100;
        private static final int ANIMATE_SPEEED_TURN = 1000;
        private static final int BEARING_OFFSET = 20;

        private final Interpolator interpolator = new LinearInterpolator();

        int currentIndex = 0;

        float tilt = 90;
        float zoom = 15.5f;
        boolean upward = true;

        long start = SystemClock.uptimeMillis();

        LatLng endLatLng = null;
        LatLng beginLatLng = null;

        boolean showPolyline = false;

        private Marker trackingMarker;

        public void reset() {
            resetMarkers();
            start = SystemClock.uptimeMillis();
            currentIndex = 0;
            endLatLng = getEndLatLng();
            beginLatLng = getBeginLatLng();

        }

        public void stop() {
            trackingMarker.remove();
            mHandler.removeCallbacks(animator);

        }

        public void initialize(boolean showPolyLine) {
            reset();
            this.showPolyline = showPolyLine;
            highLightMarker(0);

            if (showPolyLine) {
                polyLine = initializePolyLine();
            }

            // We first need to put the camera in the correct position for the first run (we need 2 markers for this).....
            LatLng markerPos = markers.get(0).getPosition();
            LatLng secondPos = markers.get(1).getPosition();

            setupCameraPositionForMovement(markerPos, secondPos);

        }

        private void setupCameraPositionForMovement(LatLng markerPos,
                                                    LatLng secondPos) {

            float bearing = bearingBetweenLatLngs(markerPos, secondPos);

            trackingMarker = mMap.addMarker(new MarkerOptions().position(markerPos)
                    .title("title")
                    .snippet("snippet").icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_red)));

            CameraPosition cameraPosition =
                    new CameraPosition.Builder()
                            .target(markerPos)
                            .bearing(bearing + BEARING_OFFSET)
                            .tilt(90)
                            .zoom(mMap.getCameraPosition().zoom >= 16 ? mMap.getCameraPosition().zoom : 16)
                            .build();

            mMap.animateCamera(
                    CameraUpdateFactory.newCameraPosition(cameraPosition),
                    ANIMATE_SPEEED_TURN,
                    new GoogleMap.CancelableCallback() {

                        @Override
                        public void onFinish() {
                            System.out.println("finished camera");
                            animator.reset();
                            Handler handler = new Handler();
                            handler.post(animator);
                        }

                        @Override
                        public void onCancel() {
                            System.out.println("cancelling camera");
                        }
                    }
            );
        }

        private Polyline polyLine;
        private PolylineOptions rectOptions = new PolylineOptions();

        private Polyline initializePolyLine() {

            //polyLinePoints = new ArrayList<LatLng>();
            rectOptions.add(markers.get(0).getPosition());
            return mMap.addPolyline(rectOptions);
        }
        /**
         * Add the marker to the polyline.
         */
        private void updatePolyLine(LatLng latLng) {
            List<LatLng> points = polyLine.getPoints();
            points.add(latLng);
            polyLine.setPoints(points);
        }


        public void stopAnimation() {
            animator.stop();
        }

        public void startAnimation(boolean showPolyLine) {
            if (markers.size() > 2) {
                animator.initialize(showPolyLine);
            }
        }


        @Override
        public void run() {

            long elapsed = SystemClock.uptimeMillis() - start;
            double t = interpolator.getInterpolation((float) elapsed / ANIMATE_SPEEED);

            double lat = t * endLatLng.latitude + (1 - t) * beginLatLng.latitude;
            double lng = t * endLatLng.longitude + (1 - t) * beginLatLng.longitude;
            LatLng newPosition = new LatLng(lat, lng);

            trackingMarker.setPosition(newPosition);

            if (showPolyline) {
                updatePolyLine(newPosition);
            }

            // It's not possible to move the marker + center it through a cameraposition update while another camerapostioning was already happening.
            //navigateToPoint(newPosition,tilt,bearing,currentZoom,false);
            //navigateToPoint(newPosition,false);

            if (t < 1) {
                mHandler.postDelayed(this, 16);
            } else {

                System.out.println("Move to next marker.... current = " + currentIndex + " and size = " + markers.size());
                // imagine 5 elements -  0|1|2|3|4 currentindex must be smaller than 4
                if (currentIndex < markers.size() - 2) {

                    currentIndex++;

                    endLatLng = getEndLatLng();
                    beginLatLng = getBeginLatLng();


                    start = SystemClock.uptimeMillis();

                    LatLng begin = getBeginLatLng();
                    LatLng end = getEndLatLng();

                    float bearingL = bearingBetweenLatLngs(begin, end);

                    highLightMarker(currentIndex);

                    CameraPosition cameraPosition =
                            new CameraPosition.Builder()
                                    .target(end) // changed this...
                                    .bearing(bearingL + BEARING_OFFSET)
                                    .tilt(tilt)
                                    .zoom(mMap.getCameraPosition().zoom)
                                    .build();


                    mMap.animateCamera(
                            CameraUpdateFactory.newCameraPosition(cameraPosition),
                            ANIMATE_SPEEED_TURN,
                            null
                    );

                    start = SystemClock.uptimeMillis();
                    mHandler.postDelayed(animator, 16);

                } else {
                    currentIndex++;
                    highLightMarker(currentIndex);
                    stopAnimation();
                }

            }
        }


        private LatLng getEndLatLng() {
            return markers.get(currentIndex + 1).getPosition();
        }

        private LatLng getBeginLatLng() {
            return markers.get(currentIndex).getPosition();
        }

        private void adjustCameraPosition() {
            if (upward) {

                if (tilt < 90) {
                    tilt++;
                    zoom -= 0.01f;
                } else {
                    upward = false;
                }

            } else {
                if (tilt > 0) {
                    tilt--;
                    zoom += 0.01f;
                } else {
                    upward = true;
                }
            }
        }
    }

    /**
     * Adds a marker to the map.
     */
    public void addMarkerToMap(LatLng latLng) {

        Marker marker = mMap.addMarker(new MarkerOptions().position(latLng)
                .title("title")
                .snippet("snippet").icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_red)));

        markers.add(marker);

    }

    private void resetMarkers() {
        for (Marker marker : this.markers) {
            marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_green));
        }
    }

    /**
     * Highlight the marker by index.
     */
    private void highLightMarker(int index) {
        highLightMarker(markers.get(index));
    }

    /**
     * Highlight the marker by marker.
     */
    private void highLightMarker(Marker marker) {
        marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_yellow));
        marker.showInfoWindow();

    }
}

2 个答案:

答案 0 :(得分:1)

解决我的问题,我评论了这一行:

//rectOptions.add(markers.get(0).getPosition());

答案 1 :(得分:0)

在地图上添加了多道线,并通过polyline.remove();将其删除。作为参考,您可以使用How to remove all the polylines from a map