Удаление старых полилиний в зависимости от текущего местоположения пользователя - PullRequest
0 голосов
/ 09 июля 2019

Всякий раз, когда я пытаюсь обновить текущее местоположение пользователя, мне нужно удалить старую полилинию, но я могу переместить маркер в зависимости от текущего местоположения пользователя

Я пытался инициировать новый HTTP-запрос из моего приложения через каждые 200 метров, рассчитанные изпредыдущее местоположение пользователя.Я не получил никакого ответа, и приложение зависает.Без нового http-запроса мне нужно обновить текущую полилинию

Мой файл активности карт отображает все обратные вызовы отсюда.Я использовал шаблон проектирования MVVM

весь ответ от respo будет триггером в этой функции

            private void initViewModel() {
                viewModel = ViewModelProviders.of(this).get(MapsViewModel.class);
                viewModel.init();
                viewModel.askLocationUpdates(this);
                viewModel.getApplicationHelper().observe(this, this);
                viewModel.getCurrentLocation().observe(this, new Observer<Location>() {
                    @Override
                    public void onChanged(Location location) {

                        if (!isDirectionsMode) {


                            updateUserCurrentLocation(mMap, location);
                        } else {

                            mMap.clear();

        if(PolyUtil.isLocationOnPath(new LatLng(location.getLatitude(),location.getLongitude()),polylines.get(0).getPoints(),true,10));
                            {

                                Log.d(TAG, "has path ");
                            }


                        }

                    }
                });


                viewModel.checkServices();
                viewModel.getDirectionsResults().observe(this, new Observer<PolylineOptions>() {
                    @Override
                    public void onChanged(PolylineOptions polylineOptions) {
                        Log.d(TAG, "drawed");
                        oldpolylineoptions = polylineOptions;
                        drawPathDirections(polylineOptions);
                    }
                });


            }

            private void drawPathDirections(PolylineOptions latLngList) {
                if (isDirectionsMode) {
                    for (Polyline line: polylines) {
                        line.remove();
                    }
                    polylines.clear();
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                               int[] grantResults)


                        return;
                    }
                }
                mMap.setMyLocationEnabled(false);
                int height = 100;
                int width = 100;
                BitmapDrawable bitmapdrawOrigin = (BitmapDrawable) getResources().getDrawable(R.drawable.mylocation);
                Bitmap bitmapdrawOriginBitmap = bitmapdrawOrigin.getBitmap();
                Bitmap smallMarkerOrigin = Bitmap.createScaledBitmap(bitmapdrawOriginBitmap, width, height, false);


                BitmapDrawable bitmapdrawDest = (BitmapDrawable) getResources().getDrawable(R.drawable.destination);
                Bitmap bitmapdrawDestBitmap = bitmapdrawDest.getBitmap();
                Bitmap smallMarkerDest = Bitmap.createScaledBitmap(bitmapdrawDestBitmap, width, height, false);

                mMap.addMarker(new MarkerOptions().position(new LatLng(originPlace.getLatitude(), originPlace.getLongitude())).icon(BitmapDescriptorFactory.fromBitmap(smallMarkerDest)).snippet("Your location"));
                mMap.addMarker(new MarkerOptions().position(new LatLng(DestinationPlace.getLatitude(), DestinationPlace.getLongitude())).icon(BitmapDescriptorFactory.fromBitmap(smallMarkerOrigin)).snippet("Destination place"));

                polylines.add(mMap.addPolyline(latLngList));


            }

Всякий раз, когда пользователь устанавливает свое место назначения, этот метод будет запускаться из действия, которое я буду просить картыактивность respo из модели представления .. in respo, все мои HTTP-запросы будут там

            @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (requestCode == SEARCH_VIEW_RESULT) {
                    if (resultCode == RESULT_OK) {
                        if (isDirectionsMode) {
                            for (Polyline line : polylines) {
                                line.remove();
                            }

                        }


                        mMap.clear();

                        isDirectionsMode = true;
                        Place place = Autocomplete.getPlaceFromIntent(data);
                        final Location temp = new Location(LocationManager.GPS_PROVIDER);
                        temp.setLatitude(place.getLatLng().latitude);
                        temp.setLongitude(place.getLatLng().longitude);
                        DestinationPlace = temp;
                        previousLocation = originPlace;
                        viewModel.askDirectionFromCurrentLocation(temp);


                    } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
                        // TODO: Handle the error.
                        Status status = Autocomplete.getStatusFromIntent(data);
                        Log.i(TAG, status.getStatusMessage());
                    } else if (resultCode == RESULT_CANCELED) {
                        // The user canceled the operation.
                    }
                }


            }

Этот метод будет запускаться, когда приложение успешно находит текущее местоположение пользователя на основе значений, оно обновит карту


            private void updateUserCurrentLocation(GoogleMap mMap, Location location) {
                if (mapReady) {
                    mMap.clear();


                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), DEFAULT_ZOOM));


             originPlace = location;enter code here
                   mMap.setMyLocationEnabled(true);

                }
            }
...