使用Google Map utils中的Map Cluster按下标记后InfoWindow中的自定义信息

时间:2014-06-06 04:56:45

标签: android google-maps google-maps-api-3 markerclusterer

我正在尝试使用MarkerCluster

为每个标记呈现具有不同值的自定义InfoWindow

这是我尝试的:

private final GoogleMap.InfoWindowAdapter mInfoWindowAdapter = new GoogleMap.InfoWindowAdapter() {
        @Override
        public View getInfoWindow(Marker marker) {
            View window = null;
            if(getActivity()!=null&&isAdded()){
                window = getActivity().getLayoutInflater().inflate(R.layout.map_objective_overlay, null);
                final CustomFontTextView nameTV = (CustomFontTextView) window.findViewById(R.id.nameTV);

                if(clickedClusterItem!=null){
                    System.out.println("You clicked this: "+clickedClusterItem.getName());
                }else{
                    System.out.println("The clicked cluster item was nulllll");
                }
                if (clickedCluster != null) {
                    for (Objective item : clickedCluster.getItems()) {
                        // Extract data from each item in the cluster as needed
                        if(item.getRemoteId().equals(clickedClusterItem.getRemoteId())){
                            nameTV.setText(clickedClusterItem.getName());
                        }
                    }
                }
            }
            return window;
        }

        @Override
        public View getInfoContents(Marker marker) {
            return null;
        }
    };
    private Objective clickedClusterItem;
    private Cluster<Objective> clickedCluster;

@Override
    public void onResume() {
        super.onResume();
        preferences = getActivity().getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE);
        if (map == null) {
            map = fragment.getMap();
            mClusterManager = new ClusterManager<Objective>(getActivity(), map);
            map.setOnCameraChangeListener(mClusterManager);
            map.setOnMarkerClickListener(mClusterManager);
            latitude = Double.parseDouble(preferences.getString(Constants.LATITUDE, "0"));
            longitude = Double.parseDouble(preferences.getString(Constants.LONGITUDE, "0"));
            map.addMarker(new MarkerOptions()
                    .position(new LatLng(latitude, longitude))
                    .title("Hello " + preferences.getString(Constants.TOURIST_NAME, "tourist"))
                    .snippet("You are here")
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_check_in)));
            map.setInfoWindowAdapter(mClusterManager.getMarkerManager());
            //mClusterManager.setRenderer(new ObjectiveClusterRenderer(getActivity(), map, mClusterManager));
            mClusterManager.getClusterMarkerCollection().setOnInfoWindowAdapter(mInfoWindowAdapter);
            mClusterManager.getMarkerCollection().setOnInfoWindowAdapter(mInfoWindowAdapter);
            map.setOnMarkerClickListener(mClusterManager);

            mClusterManager.setOnClusterClickListener(new ClusterManager.OnClusterClickListener<Objective>() {
                @Override
                public boolean onClusterClick(Cluster<Objective> cluster) {
                    clickedCluster = cluster; // remember for use later in the Adapter
                    return false;
                }
            });
            mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener<Objective>() {
                @Override
                public boolean onClusterItemClick(Objective item) {
                    clickedClusterItem = item;
                    return false;
                }
            });

在这里我将标记添加到clustermanager:

public void setUpClusterer(List<Objective> objectivesList) {
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 10));
        addItems(objectivesList);
    }

    private void addItems(List<Objective> objectiveList) {
        for (Objective anObjectiveList : objectiveList) {
            Objective offsetItem = new Objective();
            offsetItem.setRemoteId(anObjectiveList.getRemoteId());
            offsetItem.setName(anObjectiveList.getName());
            objectiveMap.put(offsetItem.getRemoteId(), offsetItem);
            System.out.println("This is the remote ID: " + offsetItem.getRemoteId());
            mClusterManager.addItem(offsetItem);
        }
    }

InfoWindow的布局没问题,但内容为空clickedClusterItemclickedCluster始终为空...

有关我可能做错的任何提示?

我看到其他一些答案涉及使用标记和相应的对象创建Map,但我不太清楚如何做到这一点。

2 个答案:

答案 0 :(得分:1)

我在我的应用中做到了这一点。试试吧。

    GoogleMap googleMap;    
    Double latitude;
    Double longitude;    
    Marker mark;
    MarkerOptions marker;
    Bitmap bitmap;
    String position, catName, activity;
    ToggleButton listView, mapView;
    Hashtable<Integer, String> markers;

    ArrayList<HomeProperty> list = new ArrayList<HomeProperty>();
    ArrayList<HomeProperty> newList;
    ArrayList<HomeProperty> category = new ArrayList<HomeProperty>();
    ArrayList<SearchProperty> searchList = new ArrayList<SearchProperty>();
    ArrayList<HomeProperty> locationList = new ArrayList<HomeProperty>();

    ProgressDialog dialog;

    ImageLoader imageLoader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // Introduction
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map);
        initilizeMap();
        imageLoader = new ImageLoader(getApplicationContext());

        markers = new Hashtable<Integer, String>();

        listView = (ToggleButton) findViewById(R.id.listView);
        mapView = (ToggleButton) findViewById(R.id.mapView);
        listView.setOnCheckedChangeListener(this);
        mapView.setOnCheckedChangeListener(this);
        mapView.setChecked(true);

        // setting the arraylist containing all data of events
        ArrayData aData = (ArrayData) getIntent().getSerializableExtra("list");
        position = getIntent().getStringExtra("position");
        catName = getIntent().getStringExtra("catName");
        activity = getIntent().getStringExtra("activity");
        list = aData.getList();


        ArrayData categoryData = (ArrayData) getIntent().getSerializableExtra(
                "category");
        category = categoryData.getList();

        if (getIntent().hasExtra("searchData")) {
            SearchData search = (SearchData) getIntent().getSerializableExtra(
                    "searchData");
            searchList = search.getList();
        } else {
            searchList = new ArrayList<SearchProperty>();
        }

        newList = new ArrayList<HomeProperty>();
        // for all categories
        if (catName.equalsIgnoreCase("All")) {
            newList.clear();
            newList.addAll(list);

        } else if (activity.equals("search")) {
            newList.addAll(list);

        }
        // for single category
        else {
            for (int count = 0; count < list.size(); count++) {
                if (list.get(count).getCategoryName().equals(catName)) {
                    newList.add(list.get(count));
                }
            }
        }

        // looping through All Transactions
        for (int count = 0; count < newList.size(); count++) {
            HomeProperty prop = new HomeProperty(newList.get(count).getLatitude(),
                    newList.get(count).getLongitude());

            locationList.add(prop);
        }


        for (int count = 0; count < newList.size(); count++) {
            marker = new MarkerOptions()
                    .position(
                            new LatLng(Double.parseDouble(list.get(count)
                                    .getLatitude()), Double.parseDouble(newList
                                    .get(count).getLongitude())))
                    .title(newList.get(count).getTitle())
                    .snippet(
                            new JSONMethods().SHORTIMAGEURL
                                    + newList.get(count).getImageDirectory()
                                    + "/thumb_" + newList.get(count).getImage());

            googleMap.addMarker(marker);

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(Double.parseDouble(newList.get(count)
                            .getLatitude()), Double.parseDouble(newList.get(count)
                            .getLongitude()))).zoom(12).build();

            googleMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));
            googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
        }


        googleMap.getUiSettings().setZoomGesturesEnabled(true);
        googleMap.getUiSettings().setCompassEnabled(true);
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);
        googleMap.getUiSettings().setRotateGesturesEnabled(true);
    }

    // set action on home button click in action bar
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        // Handle action bar actions click
        switch (item.getItemId()) {
        // case R.id.action_settings:
        // return true;
        case android.R.id.home:
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    private class CustomInfoWindowAdapter implements InfoWindowAdapter {

        private View view;

        public CustomInfoWindowAdapter() {
            view = getLayoutInflater().inflate(R.layout.custominfowindow, null);

        }

        @Override
        public View getInfoContents(Marker mark) {

            if (MapActivity.this.mark != null
                    && MapActivity.this.mark.isInfoWindowShown()) {
                MapActivity.this.mark.showInfoWindow();
            }
            return view;
        }

        @Override
        public View getInfoWindow(final Marker mark) {
            MapActivity.this.mark = mark;

            final ImageView image = ((ImageView) view.findViewById(R.id.badge));

            imageLoader.DisplayImage(mark.getSnippet(), image);

            final String title = mark.getTitle();
            final TextView titleUi = ((TextView) view.findViewById(R.id.title));
            if (title != null) {
                titleUi.setText(title);
            } else {
                titleUi.setText("");
            }

            return view;
        }

    }

答案 1 :(得分:0)

您可以考虑以下方法为我工作:

public void initilizeMap() {
    googleMap = mFragment.getMap();
    googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
    googleMap.getUiSettings().setZoomControlsEnabled(true); // true to`enter code here`
    googleMap.getUiSettings().setZoomGesturesEnabled(true);
    googleMap.getUiSettings().setCompassEnabled(true);
    googleMap.getUiSettings().setMyLocationButtonEnabled(true);
    googleMap.getUiSettings().setRotateGesturesEnabled(true);
    if (googleMap == null) {
        Toast.makeText(getActivity(), "Sorry! unable to create maps",
                Toast.LENGTH_SHORT).show();
    }
    mClusterManager = new ClusterManager<MyItem>(getActivity(),   googleMap );
//          googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
    googleMap.setOnMapLoadedCallback(this);
    googleMap.setMyLocationEnabled(true);
    googleMap.setBuildingsEnabled(true);
    googleMap.getUiSettings().setTiltGesturesEnabled(true);

    MyItem offsetItem = new MyItem(Double.parseDouble(outletList.get(i).getMap_latitude()),
                                       Double.parseDouble(outletList.get(i).getMap_longitude()), title , address);
        mClusterManager.addItem(offsetItem);
        googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(offsetItem));

}

private class CustomInfoWindowAdapter implements InfoWindowAdapter {
  Marker marker;
  private View view;
  private MyItem items;

  public CustomInfoWindowAdapter(MyItem item) {
    view = getActivity().getLayoutInflater().inflate(
        R.layout.custom_info_window, null);
    this.items = item;
  }

  @Override
  public View getInfoContents(Marker marker) {

    if (marker != null && marker.isInfoWindowShown()) {
      marker.hideInfoWindow();
      marker.showInfoWindow();
    }
    return null;
  }

  @Override
  public View getInfoWindow(final Marker marker) {
    this.marker = marker;

    String url = null;

    if (marker.getId() != null && markers != null && markers.size() > 0) {
      if (markers.get(marker.getId()) != null
          && markers.get(marker.getId()) != null) {
        url = markers.get(marker.getId());
      }
    }

    final ImageView image = ((ImageView) view.findViewById(R.id.badge));

    if (url != null && !url.equalsIgnoreCase("null")
        && !url.equalsIgnoreCase("")) {
      imageLoader.displayImage(url, image, options,
          new SimpleImageLoadingListener() {
            @Override
            public void onLoadingComplete(String imageUri, View view,
                Bitmap loadedImage) {
              super.onLoadingComplete(imageUri, view, loadedImage);
              getInfoContents(marker);
            }
          });
    } else {
      image.setImageResource(R.drawable.ic_launcher);
    }

    final String title = items.getTitle();
    Log.e(TAG, "TITLE : " + title);
    final TextView titleUi = ((TextView) view.findViewById(R.id.title));
    if (title != null) {
      titleUi.setText(title);
    } else {
      titleUi.setText("");
    }

    final String address = items.getAddress();
    final TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
    if (address != null) {
      snippetUi.setText(address);
    } else {
      snippetUi.setText("");
    }
  }
}