High-de map aggregation markers of Android development

Source: Internet
Author: User

The previous article said on the map to achieve a custom markers, but markers too much on the map will be very dense, overlapping overlay, here is the introduction of the markers aggregation. Look at the encapsulated aggregation class first.

  public class markerclusteryellow {    private Activity 
Activity
    private MarkerOptions options;
    private ArrayList<MarkerOptions>includeMarkers;     private LatLngBounds bounds;//  Create area  /** * *  @param  
Activity *  @param  firstmarkers *  @param  projection *  @param  gridsize Region size parameter * *    public markerclusteryellow (activity activity, markeroptions firstmarkers ,          projection projection, int gridsize)
 {         options = new markeroptions ();
         this.activity = activity;          point point = projection.tOscreenlocation (Firstmarkers.getposition ());          point southwestpoint = new point (
Point.x - gridsize, point.y + gridsize);          point northeastpoint = new point (
Point.x + gridsize, point.y - gridsize);          bounds = new latlngbounds (          projection.fromscreenlocation (southwestpoint),    
      projection.fromscreenlocation (Northeastpoint));          options.anchor (0.5f, 0.5f). Title ( Firstmarkers.gettitle ())          .position (
Firstmarkers.getposition ())          .icon (FirstMarkers.getIcon ())           .snippet (Firstmarkers.getsnippet ());          includeMarkers = new ArrayList<
Markeroptions> ();
         includemarkers.add (firstmarkers); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP}  /** *  add marker/  public void addmarker ( markeroptions markeroptions)  {      includemarkers.add (MarkerOptions) ;//  added to the list     /** *  sets the central location of the aggregation point and the icon/Public void setpositionandicon (String  text)  {    string id= "";     int size = 
Includemarkers.size ();     if  (size == 1)  {        
 return;
     }    double lat = 0.0;    double lng = 0.0;
   String snippet =  "";    for  (markeroptions op : includemarkers)  {    
   lat += op.getposition (). latitude;
       lng += op.getposition (). Longitude;
       snippet += op.gettitle ()  +  "\ n";
       id=id+op.gettitle () + ","; &NBSP;&NBSP;&NBSP;&NBSP}    options.position (NEW&NBSP;LATLNG (lat / size, lng
 / size);//  sets the average distance    options.title (ID) of the center position as the aggregation point;
   options.snippet (snippet);
   int iconType = size / 2;      switch  (icontype)  {             default:               &nbsP;options.icon (Bitmapdescriptorfactory                 .frombitmap (Getviewbitmap, GetView (Size,text,         
       r.mipmap.content_icon_positions_yellow)));
          break; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}     }      public  latlngbounds getbounds ()  {       return bounds;   &NBSP;&NBSP}      public markeroptions getoptions ()  {   
     return options;
&NBSP;&NBSP;&NBSP}      public void setoptions (markeroptions options)  {
          this.options = options; &NBSP;&NBSP;&NBSP}   &NBSP;&NBsp; public view getview (Int carnum,string text,int resourceid)  {         view view = activity.getlayoutinflater (). Inflate (
R.layout.my_car_cluster_view, null);         TextView carNumTextView =  (TextView)  
View.findviewbyid (R.id.my_car_num);         TextView tv_price =  (TextView)  
View.findviewbyid (R.id.tv_price);         TextView tv_price_status =  (TextView)  
View.findviewbyid (R.id.tv_price_status);
        tv_price.settext (text);
        tv_price_status.settext ("Yuan/day");
        tv_price.settextcolor (Color.parsecolor ("#FFBB18"));         tv_price_status.settextcOlor (Color.parsecolor ("#FFBB18"));         LinearLayout myCarLayout =  (linearlayout)  
View.findviewbyid (R.ID.MY_CAR_BG);
        mycarlayout.setbackgroundresource (RESOURCEID);
        carnumtextview.settext (string.valueof (carNum));
        return view; &NBSP;&NBSP;&NBSP}  /** *  transforms a view into Bitmap object/public static bitmap getviewbitmap (view  view)  {view.measure (Measurespec.makemeasurespec (0, measurespec.unspecified),    
      measurespec.makemeasurespec (0, measurespec.unspecified));         view.layout (0, 0, view.getmeasuredwidth (), 
View.getmeasuredheight ());
        view.builddrawingcache ();      &nBsp;  bitmap bitmap = view.getdrawingcache ();
        return bitmap; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP}}

On the basis of the previous blog, we do the aggregation, only the following actions are required:

public class fragmentmap extends fragment implements locationsource,  amaplocationlistener,oncamerachangelistener {     private static 

fragmentmap fragment = null;       @ViewInject (R.id.map)      private MapView 

Mapview;

     private AMap aMap;

     private View mapLayout;

     private OnLocationChangedListener mListener;

     private LocationManagerProxy mAMapLocationManager;      private list<positioneneity> positioneneitylist = new

 ArrayList<PositionEneity> ();      private arraylist<markeroptions> markeroptionslistyellow =  new ArrayList<MarkerOptions> ();//  all the MarKer      private ArrayList<MarkerOptions>  Markeroptionslistinviewyellow= new arraylist<markeroptions> () marker    in;//  field of vision

   string yellow= "";      private int height;//  screen height (px)       private int width;//  screen width (px)      private int gridSize  = 50;// marker Point Area size       handler handler = new handler ()  {       @Override       public void  Handlemessage (android.os.message msg)  {          

Super.handlemessage (msg);           if  (msg.what == 0)  {                resetmarks ();//  update markers            }  

     }  };      public static fragment newinstance ()  {         if  (fragment == null)  {             synchronized  (fragmentmap.class)  {                if  (fragment == null)  {                   fragment 

= new fragmentmap ();   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;}          }              return 

Fragment  }   PUBlic view oncreateview (layoutinflater inflater, viewgroup container,bundle 

savedinstancestate)  {      if  (maplayout == null)  {          maplayout = inflater.inflate (R.layout.fragment

_map, null);

         viewutils.inject (this, maplayout);

         mapview.oncreate (savedinstancestate);          DisplayMetrics dm = new 

Displaymetrics ();          getactivity (). Getwindowmanager (). GetDefaultDisplay ().

Getmetrics (DM);

         width = dm.widthPixels;

         height = dm.heightPixels;               if  (amap == null)  {                   amap = mapview.getmap (

);                    Amap.setlocationsource (this);//  Set positioning monitor                    amap.getuisettings (). Setmylocationbuttonenabled (True);//  Set whether the default positioning button displays                 

  amap.setmylocationenabled (True);//  set to True to display the positioning layer and trigger positioning, false indicates that the hidden anchor layer does not trigger the location, the default is False                }           } else {                if  (Maplayout.getparent ()  != null)  {                    ((ViewGroup)  maplayout.getparent ()).

Removeview (maplayout);                 }            }            

Amap.setoncamerachangelistener (this);

      return mapLayout;  /**  *  capturing the marker  from the field of vision marker  */<strong>  in the visual field of marker  display based on aggregation algorithm Private void resetmarks ()  { //  start Refresh interface      Projection 

Projection = amap.getprojection ();

     Point p = null;

     markeroptionslistinviewyellow.clear ();  //  gain marker in current field of view;Efficiency      for  (Markeroptions mp : markeroptionslistyellow)  {

     p = projection.toscreenlocation (Mp.getposition ());      if  (p.x &lt; 0 | |  p.y &lt; 0 | |  p.x &gt; width | |  p.y &gt; height)  { //  not added to the list of calculations       } 

else {         markeroptionslistinviewyellow.add (MP); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} &nbsp}    //  Custom aggregation class Markercluster     arraylist&lt; markerclusteryellow&gt; clustersmarkeryellow = new arraylist&lt;

Markerclusteryellow&gt; ();    for  (markeroptions mp : markeroptionslistinviewyellow)  {           if  (ClusTersmarkeryellow.size ()  == 0)  {               clustersmarkeryellow.add (New markerclusteryellow getActivity (), &NBSP;MP,                  projection,  GridSize);//gridsize  according to their own needs to adjust           } else  {               boolean 

isin = false;                for  ( Markerclusteryellow cluster : clustersmarkeryellow)  {                if  (Cluster.getbounds (). Contains (Mp.getposition ()))  {                    cluster.addmarker (MP);                   

 isIn = true;                   

 break;                  }   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}       if  (!isin)  {            clustersmarkeryellow.add (new

 markerclusteryellow (Getactivity (),  mp, projection, gridsize));                  }   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} &nbsp}    //  first clear all overlays on map    

  amap.clear ();      for (markerclusteryellow markerclusteryellow : clustersmarkeryellow)  {             markerclusteryellow.setpositionandicon (yellow);//  Sets the location of the aggregation point and icon             amap.addmarker (

Markerclusteryellow.getoptions ());//  add          &nbsp again;    &nbsp}  private void initview ()  { for  (int i = 0;  i < positioneneitylist.size ();  i++)  {       if   (Positioneneitylist.get (i). GetType (). Equals ("2"))  {        

     yellow=positioneneitylist.get (i). GetPrice ();              View view01 =  View.inflate (Getactivity (), R.LAYOUT.VIEW_EVERYDAY,&NBSp;null);              textview tv_price =

  (TextView)  view01.findviewbyid (R.id.tv_price);              textview tv_price_status

 =  (TextView)  view01.findviewbyid (r.id.tv_price_status);              tv_price.settext (

Positioneneitylist.get (i). GetPrice ());

             tv_price_status.settext ("Yuan/day");              Bitmap bitmap = 

Commentactivity.convertviewtobitmap (VIEW01);            <strong>   Markeroptionslistyellow.add (New markeroptions ()  .position (NEW&NBSP;LATLNG (Double.parseDouble ( Positioneneitylist.get (i). Getlatitude ())  ,  double.parsedouble (Positioneneitylist.get (i). Getlongitude ())). Icon (bitmapdescriptorfactory.frombitmap

(bitmap))

 .title (Positioneneitylist.get (i). GetId ()));

           }        } &NBSP}       @Override  public void oncamerachange (cameraposition  cameraposition)  {  &nbsp     @Override  public void oncamerachangefinish ( cameraposition cameraposition)  {        handler.sendemptymessage (0 ;//  update interface Marker &NBSP}}


For the location and map Display section Please refer to the previous blog:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.