Android Маркер API GoogleMap добавлен на карту, и нажатие на маркер не является одним и тем же объектом - PullRequest
0 голосов
/ 21 апреля 2020

Я новичок в Android разработке и пытаюсь реализовать представление карты о нескольких маркерах. Маркеры изначально не добавляются на карту. Маркер добавляется на карту только тогда, когда фрагмент наблюдает за изменением данных viewModel. LiveData представляет собой список объектов с местоположением (широта и долгота), и наблюдатель будет все все элементы в списке в качестве маркера на карте и установить тег этого маркера.

Однако, когда я щелкнул маркер, информация о маркере не извлекается должным образом. Извлекаются только заголовок и фрагмент маркера, а marker.getTag () возвращает ноль. Я использовал отладчик для отладки и найти маркер, отслеживаемый внутри clickListener, и маркер, добавленный на карту, не является тем же объектом ??? у них разные ссылки ... Это действительно странно. Кто-нибудь поможет?

Вот код

public class MapFragment extends BaseFragment<MapViewModel, MapRepository>
        implements OnMapReadyCallback, GoogleMap.InfoWindowAdapter,
        GoogleMap.OnInfoWindowClickListener {

    private MapFragmentBinding binding;
    private MapView mapView;
    private GoogleMap googleMap;
    private NavigationManager navigationManager;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding =  MapFragmentBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mapView = (MapView) view.findViewById(R.id.event_map_view);
        if (mapView != null) {
            mapView.onCreate(null);
            mapView.onResume();
            mapView.getMapAsync(this);
        }
        FloatingActionButton fab = view.findViewById(R.id.fab_return);
        fab.setOnClickListener( v -> {
            navigationManager.navigateTo(new HomeListFragment());
        });
        FloatingActionButton returnFab = view.findViewById(R.id.fab_center);
        returnFab.setOnClickListener( v -> {
            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(Config.lat, Config.lon))
                    .zoom(10)
                    .build();

            googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        });
        viewModel.getListMutableLiveData().observe(getViewLifecycleOwner(), list -> {
            if (list != null) {
                addJobToMap(list);
            }
        });
    }


   // .....on attach,  on resume, on pause and other functions that seems unrelated

    @Override
    public void onMapReady(GoogleMap googleMap) {
        MapsInitializer.initialize(Objects.requireNonNull(getContext()));
        this.googleMap = googleMap;
        this.googleMap.setMapStyle(MapStyleOptions
                .loadRawResourceStyle(Objects.requireNonNull(getActivity()), R.raw.style_json));

        LatLng position = new LatLng(Config.lat, Config.lon);
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(position)
                .zoom(10)
                .build();

        googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        MarkerOptions markerOptions = new MarkerOptions().position(position).title("Me");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
        googleMap.addMarker(markerOptions);
        googleMap.setInfoWindowAdapter(this);
        googleMap.setOnInfoWindowClickListener(this);
    }

    @Override
    protected MapViewModel getViewModel() {
        return new ViewModelProvider(requireActivity(), getFactory()).get(MapViewModel.class);
    }

    @Override
    protected ViewModelProvider.Factory getFactory() {
        return new ViewModelProvider.Factory() {
            @NonNull
            @Override
            public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
                return (T) new MapViewModel(getRepository());
            }
        };
    }

    @Override
    protected MapRepository getRepository() {
        return new MapRepository();
    }

    private void addJobToMap(List<Job> jobs) {
        if (jobs == null) {
            Utils.constructToast(getContext(), "Null List!").show();
            return;
        }

        for (Job job : jobs) {
            LatLng position = new LatLng(job.location.latitude, job.location.longitude);
            MarkerOptions markerOptions = new MarkerOptions()
                    .position(position)
                    .title(job.name)
                    .snippet(job.itemId)
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
            googleMap.addMarker(markerOptions);
            Marker marker = googleMap.addMarker(markerOptions);
            marker.setTag(job);
        }

    }

    @Override
    public View getInfoWindow(Marker marker) {
        if (!(marker.getTag() instanceof Job)) {
            return null;
        }
        Job currJob = (Job) marker.getTag();
        if (currJob == null) {
            return null;
        }
        CustomMapInfoWindowBinding binding = CustomMapInfoWindowBinding.inflate(getLayoutInflater());
        binding.tvTitle.setText(currJob.name);
        binding.tvCompanyName.setText(currJob.company);
        binding.tvLocation.setText(currJob.address);
        if (!currJob.imageUrl.isEmpty()) {
            Picasso.get().setLoggingEnabled(true);
            Picasso.get().load(currJob.imageUrl).placeholder(R.drawable.ic_center)
                    .resize(100,100)
                    .into(binding.imgInfo);

        }
        return binding.getRoot();
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
        if (!(marker.getTag() instanceof Job)) {
            return;
        }
        Job currJob = (Job) marker.getTag();
        if (currJob == null) {
            return;
        }
        Utils.constructToast(getContext(), currJob.name).show();
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...