маркеры в GoogleMap подскакивают случайным образом - PullRequest
1 голос
/ 17 октября 2019

My Dashboard Fragment:

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
 View rootView = inflater.inflate(R.layout.fragment_dashboard, container, false);

 initActionBar(rootView);
 initView(rootView);
 return rootView;
}

private void initView(View rootView) {

 mViewPager = rootView.findViewById(R.id.viewPager);
 mTab = (TabLayout) rootView.findViewById(R.id.tabLayout);
 addFragment();
 viewPagerAdapter = new ViewPagerAdapter(fragList, getChildFragmentManager());
 mViewPager.setAdapter(viewPagerAdapter);
 mTab.setupWithViewPager(mViewPager);
 mViewPager.setOffscreenPageLimit(3);
 setNavigationView(rootView);
 setDrawerView();
 new Handler().postDelayed(new Runnable() {
  @Override
  public void run() {
   getCurrentLocation();
  }
 }, 3500);

}

private void addFragment() {

 fragList = new ArrayList < Fragment > ();
 fragList.add(HomeFragment.getInstance(Constants.ALL_SPOT));
 fragList.add(HomeFragment.getInstance(Constants.TRAVEL_SPOT));
 fragList.add(HomeFragment.getInstance(Constants.DINNING_SPOT));
 fragList.add(HomeFragment.getInstance(Constants.CONVENIENCES_SPOT));

}
@Override
public void gpsLocationResult(int resultCode, Location location) {

 if (resultCode == GpsLocationConstants.REQUEST_CODE_PERMISSION_DEINED) {
  showRequiredLocationDialog();
 } else {
  if (resultCode == GpsLocationConstants.REQUEST_CODE_PERMISSION_GRANTED && location == null) {
   getCurrentLocation();
  }
  //        mUpdateLocationCallBack.UpdateLocationData(resultCode, location);
  for (int i = 0; i < fragList.size(); i++) {

   HomeFragment homeFragment = (HomeFragment) fragList.get(i);
   homeFragment.gpsLocationResult(resultCode, location);
  }
 }

}

public void getCurrentLocation() {

 ((EasyLocationAppCompatActivity) getActivity()).requestLocation(
  GpsLocationConstants.SINGLE_FIX,
  LocationRequest.PRIORITY_HIGH_ACCURACY,
  3000,
  true);
}

My HomeFragment:

public static HomeFragment getInstance(String Category) {
 HomeFragment myFragment = new HomeFragment();

 Bundle args = new Bundle();
 args.putString(Constants.SPOT_CATEGORY, Category);
 myFragment.setArguments(args);

 return myFragment;
}
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

 rootView = inflater.inflate(R.layout.fragment_home, container, false);

 initView(rootView);

 //  initActionBar(rootView);
 return rootView;
}
private void initViews(rootView) {
 loadMap();
}

private void loadMap() {

 if (getActivity() != null) {
  mapFragment = SupportMapFragment.newInstance();
  getChildFragmentManager().beginTransaction()
   .replace(R.id.home_map_container, mapFragment)
   .commit();
  if (GistUtils.isInternetConnected(getActivity())) {

   mapFragment.getMapAsync(HomeFragment.this);

   //Observable<GoogleMap> mapData = OnMapAndLayoutReady.onMapAndLayoutReadyObservable(mapFragment);

   //mapData.subscribe();


   /*mMap = mapData.toBlocking().first();

   // set map style
   Utils.setMapStyle(getActivity(), mMap);

   hideLocationAndCompassIconsFromMap();

   getCurrentLocation();*/


   //setMapLoadedCallback();
  } else {

   showToast(SyncResourceManager.getString("internet_connection_error"));
  }

 }
}
public void onMapReady(GoogleMap googleMap) {

 //Observable<GoogleMap> mapData = OnMapAndLayoutReady.onMapAndLayoutReadyObservable(mapFragment.getView());
 mMap = googleMap;
 Log.i("HomeFragmentMapLoaded", "" + mMap);
 // set map style
 Utils.setMapStyle(getActivity(), mMap);

 hideLocationAndCompassIconsFromMap();

 //getCurrentLocation();

 /*new Handler().postDelayed(new Runnable() {
     @Override
     public void run() {
         getCurrentLocation();
     }
 }, 3000);*/


 /* mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
      @Override
      public void onMapLoaded() {

      }
  });*/

 mapFragment.getView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
  @Override
  public void onGlobalLayout() {

   mapFragment.getView().getViewTreeObserver().removeOnGlobalLayoutListener(this);

   getCurrentLocation();

   /*new Handler().postDelayed(new Runnable() {
       @Override
       public void run() {

           //getCurrentLocation();
           //testFunc();
       }
   }, 5000);*/
  }
 });

}

Этот метод вызывается при получении данных из базы данных и различении категорий маркеров в соответствии с экземпляром фрагмента. и поместите его

private void addSpotsMarkersAndHandleInfoWindowClickEvents () {

    for (SpotDetail spotItem : mSpotList) {

        if (searchedSpot == null || !(searchedSpot.getPeeSpotId() == spotItem.getPeeSpotId())) {

            if (spotCategory.equals(Constants.CONVENIENCES_SPOT)) {
                if (spotItem.getCategoryId() == 1) {
                    bitmapIcon = BitmapFactory.decodeResource(getResources(), R.drawable.icon_marker_yellow);
                    addMarker(spotItem);
                }
            }
            if (spotCategory.equals(Constants.DINNING_SPOT)) {
                if (spotItem.getCategoryId() == 3) {
                    bitmapIcon = BitmapFactory.decodeResource(getResources(), R.drawable.icon_marker_purple);
                    addMarker(spotItem);
                }
            }
            if (spotCategory.equals(Constants.TRAVEL_SPOT)) {
                if (spotItem.getCategoryId() == 2) {
                    bitmapIcon = BitmapFactory.decodeResource(getResources(), R.drawable.icon_marker_green);
                    addMarker(spotItem);
                }
            }
            if (spotCategory.equals(Constants.ALL_SPOT)) {
                if (spotItem.getCategoryId() == 1) {
                    bitmapIcon = BitmapFactory.decodeResource(getResources(), R.drawable.icon_marker_yellow);
                    addMarker(spotItem);
                }
                if (spotItem.getCategoryId() == 3) {
                    bitmapIcon = BitmapFactory.decodeResource(getResources(), R.drawable.icon_marker_purple);
                    addMarker(spotItem);
                }
                if (spotItem.getCategoryId() == 2) {
                    bitmapIcon = BitmapFactory.decodeResource(getResources(), R.drawable.icon_marker_green);
                    addMarker(spotItem);
                }
            }
        }
    }

    // set adapter
    mMap.setInfoWindowAdapter(new PeeSpotInfoAdapter(getActivity()));

    // handle click when user tap on popup
    mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {

            // hide spot Info popup
            marker.hideInfoWindow();

            // navigate To Spot Detail View
            SpotDetail spotItem = (SpotDetail) marker.getTag();
            navigateToSpotDetailView(spotItem);
        }
    });

    // long click listener on map when user wants to add new spot
    mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
        @Override
        public void onMapLongClick(LatLng latLng) {

            if (isSpotWithinUserRadius(latLng)) {

                mLatLng = latLng;

                // find address by location using google api
                locationPresenter.getRawData(latLng, HomeFragment.this);

            } else {

                String spotOutsideRadius = SyncResourceManager.getString("filter_screen_txt_spot_outside_radius");
                showToast(spotOutsideRadius);
            }
        }
    });

    // when user tap on spot marker, It shows the popup info
    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {

            Object tag = marker.getTag();

            // show info popup only when its spot
            if (tag instanceof SpotDetail) {

                lastOpenMarker = marker;
                return false;
            }

            // disable popup info
            return true;
        }
    });


}

это метод addmarker private void addMarker (final SpotDetail spotItem) {

    String latitude = spotItem.getLatitude();
    String longitude = spotItem.getLongitude();


    if (latitude != null && !latitude.isEmpty() && longitude != null && !longitude.isEmpty()) {

        final LatLng latLng = new LatLng(
                Double.parseDouble(latitude),
                Double.parseDouble(longitude));

        if (spotItem.getPeeSpotIcon() != null && spotItem.getPeeSpotIcon().trim().length() > 0) {
            Target target = new Target() {
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    // Add Marker
                    float aFloat = Float.parseFloat(spotItem.getLongitude());
                    Random r = new Random();
                    float random = 3f + r.nextFloat() * (15.2f - 3.15f);
                    float zIndex = aFloat + random;
                    Marker marker = mMap.addMarker(
                            new MarkerOptions()
                                    .position(latLng)
                                    .title(spotItem.getPeeSpotId() + "")
                                    .anchor(0.5f, 0.5f)
                                    .zIndex(zIndex)

// .icon((BitmapDescriptorFactory.fromBitmap (растровый))));.Icon ((BitmapDescriptorFactory.fromBitmap (getMarkerBitmapFromView (растровый)))));marker.setTag (spotItem);mMarkerList.add (маркер);targets.remove (это);Log.i («Цели», «Удаление:»);}

                @Override
                public void onBitmapFailed(Drawable errorDrawable) {
                    targets.remove(this);
                }

                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {
                    Log.i("Targets", "Preparing: ");
                }
            };
            targets.add(target);
            Picasso.with(getContext()).load(spotItem.getPeeSpotIcon()).into(target);
        } else {
            float aFloat = Float.parseFloat(longitude);
            Random r = new Random();
            float random = 5f + r.nextFloat() * (75.23523f - 5.15413f);
            float zIndex = aFloat + random;
            // Add Marker
            Marker marker = mMap.addMarker(
                    new MarkerOptions()
                            .position(latLng)
                            .title(spotItem.getPeeSpotId() + "")
                            .zIndex(zIndex)
                            .anchor(0.5f, 0.5f)
                            .icon((BitmapDescriptorFactory.fromBitmap(bitmapIcon))));
            marker.setTag(spotItem);
            mMarkerList.add(marker);

        }
    }
}
...