package com.qiyou.mb.android.ui.fragments;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapLoadedCallback;
import com.baidu.mapapi.map.BaiduMap.OnMapTouchListener;
import com.baidu.mapapi.map.BaiduMap.SnapshotReadyCallback;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.DotOptions;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MarkerOptions.MarkerAnimateType;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.overlayutil.OverlayManager;
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.R;
import com.qiyou.mb.android.R.color;
import com.qiyou.mb.android.beans.Track;
import com.qiyou.mb.android.beans.basic.GPItem;
import com.qiyou.mb.android.beans.basic.Media;
import com.qiyou.mb.android.beans.basic.Track_bean;
import com.qiyou.mb.android.beans.basic.Waypoint;
import com.qiyou.mb.android.beans.basic.Waypoint_bean;
import com.qiyou.mb.android.utils.BMapUtil;
import com.qiyou.mb.android.utils.CompositDrawableView;
import com.qiyou.mb.android.utils.TextDrawableView;
import com.qiyou.mb.android.utils.TextDrawableViewKm;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.base.IlocationFragment;
import com.qiyou.mb.android.utils.bmap.ZoomControlView;
import com.qiyou.mb.android.utils.enums.TrackStatus;
import com.qiyou.mb.android.utils.enums.TrackType;
import com.qiyou.mb.android.utils.enums.WorkingTrackType;
import com.qiyou.mb.android.utils.enums.mediaType;
import com.qiyou.mb.android.utils.enums.wpFlag;
import com.qiyou.mb.android.utils.log.QLog;
import com.qiyou.mb.android.utils.server.SharedLocation;
//import com.baidu.mapapi.model.inner.LatLng;
//import com.baidu.mapapi.map.OverlayOptions;
//import com.baidu.mapapi.map.TextOptions;
//import com.baidu.mapapi.model.LatLng;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class TrackMap_fragment extends TrackingBasic_fragment   implements IlocationFragment  {
//public static final String popupRight = null;

	//	public static final String TAG ="com.qiyou.TrackMap_fragment";
//	public static final String dTAG ="com.qiyou";
	@Override
	public void setFTag(){
		TAG="com.qiyou.TrackMap_fragment";
	}
//    View vContainer;
	/**
	 * MapView 是地图主控件
	 */ 
	
//	int screenShotDist=0;
//	Waypoint mdWp;
//	protected MapController mMapController = null;
	// 定位相关
	//LocationClient mLocClient;
	//public MyLocationListenner myListener = new MyLocationListenner();
	
//	protected LineOverlay gpxOverlay = null;
//	protected GraphicsOverlay gpRecordingOverlay = null;
//	protected GraphicsOverlay gpNaviOverlay = null;
//	protected GraphicsOverlay gpPlaybackOverlay = null;	
////	protected GraphicsOverlay gpKMpointsOverlay = null;
//	protected GraphicsOverlay gpTurnPointsOverlay = null;
//	protected LineOverlay gpBearLinesOverlay = null;
//	protected GraphicsOverlay gpFmPointsOverlay = null;
//	protected /*ItemizedOverlay<OverlayItem>*/ Marker startOverlay =null; 
//	protected /*ItemizedOverlay<OverlayItem>*/ Marker endOverlay =null; 
	protected /*ItemizedOverlay<OverlayItem> */Marker bearStartMarker =null; 
	protected /*ItemizedOverlay<OverlayItem>*/Marker bearEndMarker =null; 
//	protected /*ItemizedOverlay<OverlayItem>*/TrackOverlay gpxStartOverlay =null;
//	protected /*ItemizedOverlay<OverlayItem>*/TrackOverlay gpxEndOverlay =null;
//	protected /*ItemizedOverlay<OverlayItem>*/MarkerOptions kmOverlay =null;
	
	protected List<Polyline> shortLines =new ArrayList<Polyline>();
	protected LineOverlay gpBearLinesOverlay = null;
	
	
 	private MdOverlay mPhotoOverlay = null; 
 	private RoadOverlay mRdOverlay = null;
 	protected TrackOverlay recordingOverlay;
 	private TrackOverlay gpxOverlay;
  	private TrackOverlay recordingStartOvelay;
 	private TrackOverlay recordingEndOvelay;
 	private MdOverlay kmOverlay = null; 
	private RoadOverlay mShareOverlay = null;
//	private RdOverlay mRdOverlay = null;
//	private PopupOverlay   popMd  = null;
//	private PopupOverlay   popRd  = null;
//	private OverlayItem mCurItem = null;
	  
	protected TextView popupText;
	protected View popupInfo = null; 
	private TextView wpNumText; 
	protected String[] ValidUrls;
	protected String[] ValidThumbUrls;
	private Handler handler ;
	private HashMap<String,String> picUrlMap;//<原图url，缩略图url>

	protected BaiduMap mBaiduMap;
	protected InfoWindow mInfoWindow;
//	private RdOverlay mShareOverlay = null; 
//	protected boolean isShowRestCheckOnly = false;
	protected Boolean canAutoZoomMap =false;//true;
	  protected boolean canDrawTrack;
	  boolean isDrawingTrack =false; //flag that the track is in the process of drawing to avoid duplicated call to the drawTrack(..)
	  boolean isPlaybackTrackDrawed =false;
	 
	  
	  
//	  private  ScaleView mScaleView;
	  private  ZoomControlView mZoomControlView;
		
	public TrackMap_fragment() {
		// TODO Auto-generated constructor stub
	}
 	/*public static TrackMap_fragment newInstance(int trackId)
	{
		QLog.getLogger().d(dTAG,TAG+" "+ "newInstance(), trackId " +trackId);
		TrackMap_fragment f = new TrackMap_fragment();
		if( trackId<=0) return f;//TODO: check why the 'if' exists
		Bundle args = new Bundle(); 
	    args.putInt(QiYouConstant.EXTRA_KEY_ID, trackId);
	    f.setArguments(args);
	    return f;
	}*/
 
	 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		 if(activity.app!=null) activity.app.currentActiveFragment =TAG;
//		 currentLayout =R.layout.trackingmap_fragment;
//		QLog.getLogger().d(dTAG,TAG+" "+ "onCreate");
		canDrawTrack=true;
		 
	}
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) { 
	 
		super.onCreateView(inflater, container, savedInstanceState);  
		return vContainer;
		
		}

	@Override
	protected void initialViews(){
		super.initialViews();
		initViewMap(); 
		
//		    locationInMap();
		 
	}
	
	 
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
//		 myLocationOverlay = new MyLocationOverlay(mMapView);
		
		initialMarkLayers();
		LocationMode mCurrentMode = LocationMode.NORMAL;
		 BitmapDescriptor mCurrentMarker=null;
		 if(activity.app.playBack){
			 mCurrentMode= LocationMode.FOLLOWING;
			  mCurrentMarker = BitmapDescriptorFactory
                     .fromResource(R.drawable.icon_geo); 
           
		 } 
		 if(mBaiduMap!=null){
			 
			  mBaiduMap
	           .setMyLocationConfigeration(new MyLocationConfiguration(
	                   mCurrentMode, true, mCurrentMarker));
			  
			  mBaiduMap.setOnMapLoadedCallback(new OnMapLoadedCallback() {

				@Override
				public void onMapLoaded() {
					// TODO Auto-generated method stub
					zoomToSpan();
					loadPOIs();
					 mBaiduMap.setCompassPosition(new android.graphics.Point(55, 55));
				}
                  
                   
          });
			  
			  mBaiduMap.setOnMapTouchListener(new   OnMapTouchListener(){

				@Override
				public void onTouch(MotionEvent arg0) {
					 Utils.hideSoftKeyboard(activity);
//					mBaiduMap.hideInfoWindow();
					 if(!isShowingPicMark && mInfoWindow!=null){
						mBaiduMap.hideInfoWindow();
						isShowingPicMark =false;
					} 
				}
				  
			  });
		 }
		
		 super.onActivityCreated(savedInstanceState); 
		 
		 mapViewOnActivityCreated();
 			
	
 	 } 
	
 
	void locateBaiduMapCenter(double bdlat, double bdlng){
		 if(bdlat>0 && bdlat>0 ){
		      
				 locData = new MyLocationData.Builder()  
			     .latitude(bdlat)
			     .longitude( bdlng).build();
			     
				mBaiduMap.setMyLocationData(locData);
				MapStatus.Builder builder = new MapStatus.Builder();
	            builder.target(new LatLng(locData.latitude,locData.longitude)) .zoom(18.0f);
				 mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
	        }
	}
	
	void locateMapCenter(double lat, double lng){
		if (mBaiduMap == null) {return;}
		 if(lat>0 && lng>0 ){
		      
				 locData = new MyLocationData.Builder()  
			     .latitude(Utils.getbdLat(lat,lng))
			     .longitude( Utils.getbdLon(lat,lng)).build();
			     
				mBaiduMap.setMyLocationData(locData);
				MapStatus.Builder builder = new MapStatus.Builder();
	            builder.target(new LatLng(locData.latitude,locData.longitude)) .zoom(18.0f);
				 mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
	        }
		 
		 /*  mMapView.getOverlays().remove(myLocationOverlay); 
	       myLocationOverlay.setData(locData);
           mMapView.getOverlays().add(myLocationOverlay);
	       myLocationOverlay.enableCompass();
	       mMapController.animateTo(new LatLng(
					(int) (locData.latitude * 1e6),
					(int) (locData.longitude * 1e6))); 
	       mMapView.refresh();
	       
	       locData = new MyLocationData.Builder() 
		     .latitude( location.getLatitude() )
		     .longitude(location.getLongitude()).build(); */
		 
	       
	}
	
	
	void mapViewOnActivityCreated(){
 
		if(QiYouConstant.PV_LAST_LAT>0 ){
			locateMapCenter(QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON);
		}
		
	      if(!isPlaying){
	    	  showMapViews();
	      }
	     /* if(isPlayback)
		   	{
		   		this.drawTrack(activity.app.currentTrack.getTrackBean());
		   		playbackTrackDrawed =true;
		   	}*/
	     
	      
	     if(isPlaying){ 					 
			 setSelectedTrackType();
		}
		else
			QiYouConstant.MAX_GEO_TIME =QiYouConstant.PLAYBACK_TIME_INTERVAL*60;

	    gpxDrawd = new ArrayList<Integer>();
	   
//	    if(!activity.app.playBack)
//	    	 drawGpx();
	    
	    
	     
	}
	
	
  @Override  
  protected void locationInMap(Location loc){
//	  takeMapScreenshot();
	    canLocationMap =!canLocationMap;
	    
	  if(canLocationMap){
 
		  if(activity.app.isRouting /*||activity.app.currentActiveFragment.equalsIgnoreCase(LocationPickerFragment.getFTag() )*/){
			  if(!Utils.isNetworkConnected(activity) && !Utils.isGpsEnabled(activity)){
				  Toast.makeText(activity, "地图定位需要开启GPS或网络连接", Toast.LENGTH_SHORT).show();  
				  canLocationMap=false;
				  return;
			  }
			  /*activity.app.isLocationFinding =activity.app.currentActiveFragment.equalsIgnoreCase(LocationPickerFragment.getFTag() );*/
			  activity.app.startAndroidGPSRequest();
			  activity.app.startNetworkLocationRequest(false);
		  }
		  btnLocation.setImageResource(R.drawable.location);
		 	if(workingTrackType==WorkingTrackType.RECORDING||activity.app.isRouting)
		 		Toast.makeText(activity, "地图已切换到自动定位模式", Toast.LENGTH_SHORT).show();
	  }else{
		  if(activity.app.isRouting &&!activity.app.isLastTrackExist()
				  /*||activity.app.currentActiveFragment.equalsIgnoreCase(LocationPickerFragment.getFTag())*/ ){
			  activity.app.stopAndroidGPSRequest();
			  activity.app.stopNetworkLocationRequest();
		  }
		  if(loc!=null){
			  canLocationMap=true;
//			  updateUI(loc,false ) ;
//			  updateGraphics(loc,false);
			  updateMapView(loc);
			  canLocationMap=false;
		
		  }
		  if(btnLocation!=null) 
			  btnLocation.setImageResource(R.drawable.nolocation);
		  if(workingTrackType==WorkingTrackType.RECORDING ||activity.app.isRouting) Toast.makeText(activity, "地图已切换到自由浏览模式", Toast.LENGTH_SHORT).show();
//		   Toast.makeText(activity, "地图进入自由浏览模式", Toast.LENGTH_SHORT).show();
	  }  
	
	  
  }
  
  @Override  
  protected void showMapViews(){
		if(vContainer.findViewById(R.id.ll_liveshareMsg)==null){
    		return;
    	}
		
		QiYouConstant.PV_BL_SHARE_LOCATION = QiYouConstant.PV_BL_SHARE_LOCATION &&  activity.app.user.getUserbean().getId()  > 0;
   	
		((TextView)vContainer.findViewById(R.id.txt_livesharemsg)).setText(QiYouConstant.PV_STR_SHARE_MSG);  
	 
		vContainer.findViewById(R.id.ll_liveshareMsg).setVisibility(QiYouConstant.PV_BL_SHARE_LOCATION?View.VISIBLE:View.GONE);
	
 	} 
 
  @Override
protected void showPoints(int which){  
 
	  if(which!=1 || kmOverlay==null){
		  return;
	  }
		if( kmOverlay.getOverlayMarkers().size()==0){
			
			kmOverlay.addToMap();
			btnKmpoints.setImageResource(R.drawable.icon_dist);
		}
		else{
			kmOverlay.removeFromMap();
			btnKmpoints.setImageResource(R.drawable.icon_dist_in);
		}
  }
   
  
  void initialMapview(){
	  mMapView = (MapView) vContainer.findViewById(R.id.tm_bmapView);  
	  mBaiduMap = mMapView.getMap();  
 
  		mZoomControlView = (ZoomControlView) vContainer.findViewById(R.id.ZoomControlView);
  		mZoomControlView.setMapView(mMapView);  
  		mMapView.showZoomControls(false);
  		
     refreshScaleAndZoomControl();	
     
     initialLiveViews();
	  
  }
 @TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void initialLiveViews(){
	
	 	
		 
	 liveLv = (ListView)vContainer.findViewById(R.id.act_live_list);  
	  if(liveLv!=null){ 
	     
		 /* View header = inflater.inflate(R.layout.header,
                  (ViewGroup) vContainer(R.id.LinearLayoutHeader));
          View search_box = inflater.inflate(R.layout.search_box,
                  (ViewGroup) vContainer(R.id.RelativeLayoutSearchBox));
          lv.addHeaderView(header, null, false);
          lv.addHeaderView(search_box, null, false);
		  */
		  
		  
		  
//		  liveLv.setLayoutParams(new RelativeLayout.LayoutParams(QiYouConstant.PV_INT_SCREEN_WIDTH/2,RelativeLayout.LayoutParams.WRAP_CONTENT/2)); //set the layout, or will not show out 
		  liveLv.setLayoutParams(new  LinearLayout.LayoutParams(QiYouConstant.PV_INT_SCREEN_WIDTH/2, 
				  LinearLayout.LayoutParams.WRAP_CONTENT /*QiYouConstant.PV_INT_SCREEN_WIDTH/3*/)); //set the layout, or will not show out 
 
		  liveLv.setOnItemClickListener(shareListItemListener);
		  liveLv.setOnTouchListener(new OnTouchListener() {
			  
				@Override
			    public boolean onTouch(View v, MotionEvent event) {
	 		        Utils.hideSoftKeyboard(activity);
			        return false;
			    }
			});
		  
		     btn_live_refresh =(Button)vContainer.findViewById(R.id.share_btn_refresh);
		     btn_live_list =(Button)vContainer.findViewById(R.id.share_btn_list);
		     btn_live_list.setAlpha(0.8f);
		     btn_live_refresh.setAlpha(0.8f);
//		     btn_live_query =(Button)vContainer.findViewById(R.id.share_btn_query);
		     btn_live_query =(ImageView)vContainer.findViewById(R.id.share_btn_query);
		     btn_live_refresh.setOnClickListener(ButtonOnClickListener);
			 btn_live_list.setOnClickListener(ButtonOnClickListener); 
			 btn_live_query.setOnClickListener(ButtonOnClickListener);		  
			 edit_act_query=(EditText)vContainer.findViewById(R.id.share_edit_username); 
//			  edit_act_query.addTextChangedListener(watcher);  
	  }
	  
	  // to initial map objects for sharelocation 
	  popupText=(TextView) vContainer.findViewById(R.id.textcache);
	  popupInfo = (View) vContainer.findViewById(R.id.popinfo);
	  
 
      
 }
 protected void initViewMap() {
	 alpha = 50;
	    initialMapview();
	    top_sptime = (TextView) vContainer.findViewById(R.id.tm_textView_top_sptime);
		top_dist = (TextView) vContainer.findViewById(R.id.tm_textView_top_dist);
	    top_speed =(TextView) vContainer.findViewById(R.id.tm_textView_top_speed);
//	    popupText=(TextView) vContainer.findViewById(R.id.textcache);
//	    popupInfo = (View) vContainer.findViewById(R.id.popinfo);
	    wpNumText=(TextView) vContainer.findViewById(R.id.txt_custWpNum); 
	  
	    btnAutoZoom=(ImageButton) vContainer.findViewById(R.id.tm_btnAutozoom);
	    btnAutoZoom.setVisibility(View.GONE);
//	    btnAutoZoom.setOnClickListener(ButtonOnClickListener);
	    
	    
	    btnRotation=(ImageButton) vContainer.findViewById(R.id.tm_btnRotaiton); 
	    btnRotation.setOnClickListener(ButtonOnClickListener);
	    if(!isPlaying){	
			btnLocation  =(ImageButton) vContainer.findViewById(R.id.tm_btnLocaiton); 
			if(this.btnLocation!=null) btnLocation.setOnClickListener(ButtonOnClickListener);
	    }
		btnKmpoints=(ImageButton) vContainer.findViewById(R.id.tbs_btnKMpoints); 
//	    btnTurnPoints=(Button) vContainer.findViewById(R.id.tbs_btnTurnPoints);	 
	    btnSaveScreen=(ImageButton) vContainer.findViewById(R.id.tm_btnSaveScreen);	
	    btnSataliteMap=(ImageButton) vContainer.findViewById(R.id.tm_btnSatalite);//
	    btnMapWayinstruction=(ImageButton) vContainer.findViewById(R.id.tbs_btnwayinstruction);//
	    btnMapWayinstruction.getBackground().setAlpha(alpha);
	    btnMapPicture=(ImageButton) vContainer.findViewById(R.id.tbs_btnpicture);//
	    btnMapPicture.getBackground().setAlpha(alpha);
	    btnMapLoadRoadbook =(ImageButton) vContainer.findViewById(R.id.map_btnLoadRoadbook);
	    btnMapLive =(ImageButton) vContainer.findViewById(R.id.map_btnLive);	    
	    btnMapLive.getBackground().setAlpha(alpha); 
	    
	    btnLiveList = (ImageButton) vContainer.findViewById(R.id.map_btnSharelist);	  
	    btnLiveList.getBackground().setAlpha(alpha); 
	    
	    btnMapLoadRoadbook.getBackground().setAlpha(alpha);
	    if(this.btnMapLive!=null){
	    	btnMapLive.setOnClickListener( ButtonOnClickListener);
	    	btnMapLoadRoadbook.setOnClickListener( ButtonOnClickListener);
	    	btnLiveList.setOnClickListener( ButtonOnClickListener);
	    }
	     
	    if(this.btnMapWayinstruction!=null){
 
	    	btnMapWayinstruction.setOnClickListener( ButtonOnClickListener);	
	    	btnMapPicture.setOnClickListener( ButtonOnClickListener);
	  } 
		  if(this.btnSaveScreen!=null){
//				btnSaveScreen.setVisibility(View.VISIBLE);
				btnSaveScreen.setOnClickListener( ButtonOnClickListener);	 
		  } 
		  if(this.btnSataliteMap!=null){
			  btnSataliteMap.setOnClickListener( ButtonOnClickListener);		
				
		  } 
		  
		  if(this.btnKmpoints!=null)
			  btnKmpoints.setOnClickListener( ButtonOnClickListener);
//		  if(this.btnTurnPoints!=null)
//			  btnTurnPoints.setOnClickListener( ButtonOnClickListener); 
		  
	//	  activity.app.getmBMapManager().start();
//		  mMapView = (MapView) vContainer.findViewById(R.id.tm_bmapView);
			
//		  gpKMpointsOverlay = new GraphicsOverlay(mMapView);	 
	    /*  
		  gpTurnPointsOverlay =new GraphicsOverlay(mMapView);	
	     
	      endOverlay=getItemizedOverlay(R.drawable.icon_send); 
		  startOverlay=getItemizedOverlay(R.drawable.icon_sstart);
		  bearStartOverlay =getItemizedOverlay(R.drawable.icon_bstart);
		  bearEndOverlay   =getItemizedOverlay(R.drawable.icon_bend); 
		  gpxStartOverlay =getItemizedOverlay(R.drawable.icon_bstart);
		  gpxEndOverlay=getItemizedOverlay(R.drawable.icon_bend); 
		  kmOverlay=getItemizedOverlay(R.drawable.icon_bend); 
		  if( isPlayback){
			  gpPlaybackOverlay  = new GraphicsOverlay(mMapView);	  
			  mMapView.getOverlays().add(gpPlaybackOverlay);
		  } 
		  
		  if( activity.app.isNaving){
			  gpNaviOverlay  = new GraphicsOverlay(mMapView);	  
			  mMapView.getOverlays().add(gpNaviOverlay);
		  } 
		  
			  gpRecordingOverlay = new GraphicsOverlay(mMapView);
			  
			  
			  
			  mMapView.getOverlays().add(gpRecordingOverlay);
			  gpxOverlay =new GraphicsOverlay(mMapView);
			  mMapView.getOverlays().add(gpxOverlay);*/
			  
			    
	        
	    
	         handler = new Handler(){ 
	 			@Override
	 			public void handleMessage(Message msg) { 
	 				if(msg.what==1){  						 
	 					 btnMapWayinstruction.setVisibility(View.VISIBLE); 
	 					if(mTrack_bean.getType()==TrackType.GPX)
	 		 				showWayinstructions();
	 				}else if(msg.what==0){  						 
	 					 btnMapPicture.setVisibility(View.VISIBLE);
	 				} else if(msg.what==3){  						 
					
 				}
	 			}};
	 			
	 			 
//	 			 showMapPicture();
	 			
	 			
//	 			if(mTrack_bean.getType()==TrackType.GPX)
//	 				showWayinstructions();
	  } 
      
 /*PopupClickListener popMdListener2 = new PopupClickListener(){
		@Override
		public void onClickedPopup(int index) {   
 
		activity.showImagePagerFragment(index,	mCurItem.getTitle().split(QiYouConstant.SPLITOR_KEY));	    
 
		}
  };
  */
  private void refreshScaleAndZoomControl(){
      //更新缩放按钮的状态  
	  
//	  QLog.getLogger().d(dTAG, String.format("...........map zoom level is %s", mMapView.getZoomLevel()));
//      mZoomControlView.refreshZoomButtonStatus(Math.round(mMapView.getZoomLevel()));
//      mScaleView.refreshScaleView(Math.round(mMapView.getZoomLevel()));
	  mZoomControlView.refreshZoomButtonStatus(Math.round(mBaiduMap.getMapStatus().zoom));
//      mScaleView.refreshScaleView(Math.round(mBaiduMap.getMapStatus().zoom));
    
	}
  /*
   * load mksearch to find  nearby pois
   */
  void loadPOIs(){
	  
  }
  
	@Override
   protected void saveScreen(){
	    	if(mMapView==null)return;
//	    	 mMapView.getMap().getCurrentMap();	
	    	 
	    	 mMapView.getMap().snapshot(new SnapshotReadyCallback() {
					public void onSnapshotReady(Bitmap snapshot) {
						onGetCurrentMap(snapshot) ;
					}
				});
	    	 
	    	 btnSaveScreen.setEnabled(false);
		     Toast.makeText(activity, "正在截取当前地图...请稍候...",	 Toast.LENGTH_LONG ).show();
	    } 
	    
	      
	    void onGetCurrentMap(Bitmap b) {
			/**
			 *  当调用过 mMapView.getCurrentMap()后，此回调会被触发
			 *  可在此保存截图至存储设备
			 */
			b= watermarkBitmap(b,null,QiYouConstant.MAP_PIC_WATER_MARK_WORDS);
			String filePath =mTrack.getMediaPah(mediaType.MAP);
			File PHOTO_DIR = new File(filePath);
			
			if(!PHOTO_DIR.exists()) PHOTO_DIR.mkdirs();// 创建文件夹		
//			screenShotDist=screenShotDist<=0?System.currentTimeMillis():screenShotDist;
			camPicName =filePath + String.format("%s.png", System.currentTimeMillis() );  
			File file = new File(camPicName);
      FileOutputStream out;
      try{
          out = new FileOutputStream(file);
          if(b.compress(Bitmap.CompressFormat.PNG, 70, out)) 
          {
              out.flush();
              out.close();
          }
          setMD(camPicName,System.currentTimeMillis(),mdWp,mediaType.MAP );
         
//          Toast.makeText( activity,  "屏幕截图成功，图片存在: "+file.toString(), Toast.LENGTH_SHORT).show();
          Toast.makeText( activity,  "屏幕截图成功，您可以在足迹找到截图。", Toast.LENGTH_SHORT).show();
        /*  if(btnSataliteMap!=null){
	             btnSaveScreen.setWidth(btnSataliteMap.getWidth());
	         	 btnSaveScreen.setHeight(btnSataliteMap.getHeight());
          }*/
          btnSaveScreen.setEnabled(true);
          if(mTrack_bean.getType()==TrackType.GPX){
	             
	             btnSaveScreen.setVisibility(View.GONE);
          }
          
      } 
      catch (FileNotFoundException e) 
      {
          e.printStackTrace();
      } 
      catch (IOException e) 
      {
          e.printStackTrace(); 
      }
      
		}
	 
	  
		 int bearCnt=2;
//		 float lastLocAccuracy =0; 
		@Override
		protected void updateMapView(Location location){
			
 
			
//			QLog.getLogger().d(dTAG, String.format("%s, location has hasAltitude :%s,location provider is %s", TAG, hasA,location.getProvider()));
			
			
 
			
			if(activity.app.isNetworkLocationRequestStarted &&  Utils.isLocOfBD(location) 
					|| Utils.isLocOfRD(location)){
//				QLog.getLogger().d(dTAG, String.format("%s, BDloc service location." ,TAG));
				 
				 locData = new MyLocationData.Builder() 
			     .latitude( location.getLatitude() )
			     .longitude(location.getLongitude()).build(); 
				 
 
			    
			}else if(Utils.isLocOfGPS(location)){
 
				 locData = new MyLocationData.Builder()  
			     .latitude( Utils.getbdLat(location.getLatitude(), location.getLongitude()))
			     .longitude(Utils.getbdLon(location.getLatitude(), location.getLongitude()))
			     .accuracy(location.getAccuracy())
			     .direction(location.getBearing())
			     .build();
				 
			}else
				return;
			
		    int limit=5;
		    limit=isPlaying?(QiYouConstant.MAX_GPS_SPAN/QiYouConstant.PLAYBACK_TIME_INTERVAL)*limit:limit;
		    limit=limit<3?3:limit;
		    limit=limit>10?10:limit;
//		    
//		    QLog.getLogger().d(dTAG, String.format("%s,%s limit----------------------------->:" ,TAG,limit));
		    /*if(mTrack_bean==null || mTrack_bean.getType()!=TrackType.GPX){
				locData.accuracy = location.getAccuracy();
				locData.direction = location.getBearing();
			 
		    }*/
			 
//			myLocationOverlay.setData(locData);
		
			if(canLocationMap ||activity.app.isLocationFinding){
				mBaiduMap.setMyLocationData(locData);
				MapStatus.Builder builder = new MapStatus.Builder();
	            builder.target(new LatLng(locData.latitude,locData.longitude));//.zoom(18.0f);
				mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
			 
 				if(location.hasBearing()&&  bearCnt>= limit){			
					if(canRotationMap){
						int ang = (int) (location.getBearing() > 180 ? location.getBearing() - 360:location.getBearing()); 
					
 						perfomRotate(ang);
					}
 
				  	bearCnt=0;
				}else{ //zoom span and animate to current location.
					if(location.getSpeed()>0  ){			
//					if(location.getSpeed()>0 || lastLocation!=null  && lastLocation.getAccuracy()>=location.getAccuracy()){
					
						bearCnt++;
						
 //					
						if( bearCnt>=4 && canAutoZoomMap){
 
							if(location!=null && location.getSpeed()!=0) {
								 QLog.getLogger().d(dTAG, String.format("%s updateMapView  zoomtospan:" ,TAG ));
								zoomToSpan(location);
							}
						}   
 					}
 
				}
 
			}
			 
//			 QLog.getLogger().d(dTAG, String.format("target lat%s,lng%s " ,locData.latitude,locData.longitude));
//			mapviewInitialized =true; 
		}
		
		
		/**
		 * 处理旋转 旋转角范围： -180 ~ 180 , 单位：度 逆时针旋转
		 */
		protected void perfomRotate(int rotateAngle ) {
 			  
				MapStatus ms = new MapStatus.Builder(mBaiduMap.getMapStatus()).rotate(rotateAngle).build();
				MapStatusUpdate u = MapStatusUpdateFactory.newMapStatus(ms);
				mBaiduMap.animateMapStatus(u);
			 
		}
		
		 
		
		public void zoomToSpan(Location location) {
	        if (mBaiduMap == null) {
	            return;
	        }
	         LatLngBounds.Builder builder = new LatLngBounds.Builder();
	    	if(mTrack_bean!=null  &&  mTrack_bean.getStartWp()!=null/* && mMapController!=null*/){  
	    	 
				float nwLat = mTrack_bean.getStartWp().getWb().getLatitude();
				if(nwLat==0f)return;
				float seLat =mTrack_bean.getMaxDistWp().getWb().getLatitude();
				if(seLat==0f)return;
				float seLng = mTrack_bean.getMaxDistWp().getWb().getLongitude();
				if(seLng==0f)return;
				float nwLng = mTrack_bean.getStartWp().getWb().getLongitude();
				if(nwLng==0f)return;
				if(mTrack_bean.getLastWp().getWb().getLongitude()==0)return; 
			      builder.include(  this.getLatLng(mTrack_bean.getStartWp().getWb()) ) 
 			     .include(  this.getLatLng(mTrack_bean.getMaxDistWp().getWb()) )   
 			     .include(  this.getLatLng(mTrack_bean.getLastWp().getWb()) );   
	    	}
			      
			      
			      if(location!=null){
				        float nwLat2 =(float) location.getLatitude();
					
						float nwLng2 = mTrack_bean.getStartWp().getWb().getLongitude();
						if(nwLng2!=0f && nwLat2!=0f){ 
							 builder.include(  new LatLng(nwLat2,nwLng2 ) );  
						} 
			      } 
			     
	            
	             mBaiduMap.setMapStatus(MapStatusUpdateFactory
	                    .newLatLngBounds(builder.build())); 
	        
	            
	    	}
	    
		
		void initialMarkLayers(){

		 	 if(mBaiduMap==null)return;
		 	 
		 		recordingOverlay= new TrackOverlay(mBaiduMap);  
		 		gpxOverlay= new TrackOverlay(mBaiduMap); 
		 		recordingEndOvelay= new TrackOverlay(mBaiduMap); 
		 		recordingStartOvelay= new TrackOverlay(mBaiduMap);
		 		mRdOverlay = new RoadOverlay(mBaiduMap);
		 		kmOverlay = new MdOverlay(mBaiduMap);
		 		mPhotoOverlay  = new MdOverlay(mBaiduMap);
		 	 
		 	 
		}
		
    @Override
	protected void updateGraphics(Location location, Boolean isOnPause){ 
		try{
//			 QLog.getLogger().d(dTAG, TAG+ "................drawTrack............ :"+  "updateGraphics()"  );
//			
//			 QLog.getLogger().dLog(dTAG, TAG+ " !isPlayback && drawTrack && !isDrawingTrack:"
//					 				+(!isPlayback && canDrawTrack && !isDrawingTrack ));

			  /*QLog.getLogger().dLog(dTAG,String.format("begin to draw track," +
			 		"isPlaying: %s,isPlayback :%s， canDrawTrack:%s，isDrawingTrack:%s, isNaving: %s",
					 isPlaying, isPlayback , canDrawTrack,isDrawingTrack,activity.app.isNaving));*/
			 
			 lastLocation = currentLocation==null?location:currentLocation;
			
			currentLocation= location;
	 
		 	if(recordingOverlay==null){
		 		recordingOverlay= new TrackOverlay(mBaiduMap);
		 	}
		 	if(gpxOverlay==null){
		 		gpxOverlay= new TrackOverlay(mBaiduMap);
		 	}
		 	if(recordingEndOvelay==null){
		 		recordingEndOvelay= new TrackOverlay(mBaiduMap);
		 	}
		 	if(recordingStartOvelay==null){
		 		recordingStartOvelay= new TrackOverlay(mBaiduMap);
		 	}
		 	
			
			if(isPlaying && !isPlaybackTrackDrawed && !isDrawingTrack){
// 				QLog.getLogger().dLog(TAG, "begin to draw track, draw playback track."  );
//				gpPlaybackOverlay.removeAll();
				drawTrack(activity.app.getCurrentTrack().getTrackBean(),gpxOverlay,true);	
			
			}else
			if(!isPlaying && canDrawTrack && !isDrawingTrack)
		   	{ 
// 				QLog.getLogger().dLog(dTAG,TAG+" begin to draw track updateGraphics(),to draw all the track."  );
	//			if(isPlayback)
	//				drawTrack(activity.app.currentTrack.getTrackBean(), gpPlaybackOverlay);	
	//			else
//					gpRecordingOverlay.removeAll();
 				    recordingOverlay.removeFromMap();
					drawTrack(mTrack_bean,/*gpRecordingOverlay,*/recordingOverlay,false);	
					
		   	}else if(lastLocation!=null 
		   			&& currentLocation !=null 
		   			&& location!=null 
		   			&& !isOnPause
		   		    && Utils.isLocOfGPS(currentLocation)
		   		    &&  Utils.isLocOfGPS(lastLocation)  
		   			) {
// 			   		QLog.getLogger().dLog(TAG, "begin to draw track,   drawShortLine()"  );
			   		drawShortLine();
			   		
//			   		if(lastLocation!=null &&lastLocation.getSpeed()==0)
//			   		{
//			   			drawNaviLine();
//			   		}
		   		}
			   
		     drawNaviLine();
		   	 
			
		}catch(NullPointerException er){
			QLog.getLogger().dLog(  TAG," while draw graphic on the map, nullPoint Exception:" +er.getStackTrace());
		    Utils.logStackTrace(er, dTAG);
		}catch(Exception er){
			QLog.getLogger().dLog( TAG," while draw graphic on the map,  Exception:" +er.getStackTrace());
		    Utils.logStackTrace(er, dTAG);
		}
		
		
 
		
	}
		
	
	/*
	 * draw a line between last location and current location
	 */
	public void drawShortLine(){
//		QLog.getLogger().d(dTAG,String.format("%s, currentlocation's provider: %s,lastLocation's provider%s", 
//				TAG,currentLocation.getProvider(),lastLocation.getProvider()));
 
		if( currentLocation==null ||currentLocation.distanceTo(lastLocation)>1000)return;//the distance between two wp should not far than 200
		
 
		 
		new Thread(){
	        @Override
			public void run() {
//			LatLng[] linePoints = new LatLng[2];
			 ArrayList <LatLng> points= new  ArrayList <LatLng>();
			 
			if(currentLocation==null) return; 
		 	double mLat =  Utils.getbdLat(currentLocation.getLatitude(),currentLocation.getLongitude());
			double mLon =  Utils.getbdLon(currentLocation.getLatitude(),currentLocation.getLongitude()); 
//			int lat = (int) (mLat*1E6);
//		   	int lon = (int) (mLon*1E6);   
//			linePoints[i-1] = new LatLng(lat, lon); 
//			linePoints[0] = new LatLng(lat, lon);
			points.add( new LatLng(mLat, mLon));
			mLat =  Utils.getbdLat(lastLocation.getLatitude(),lastLocation.getLongitude());
		    mLon =  Utils.getbdLon(lastLocation.getLatitude(),lastLocation.getLongitude()); 
//		    lat = (int) (mLat*1E6);
//		    lon = (int) (mLon*1E6);   
//		    linePoints[1] = new LatLng(lat, lon); 
		    points.add( new LatLng(mLat, mLon));
//			QLog.getLogger().d(TAG,String.format("shortline from %d,%d to %d,%d",
//					 linePoints[0].getLatitudeE6(),linePoints[0].getLongitudeE6()
//					,linePoints[1].getLatitudeE6(),linePoints[1].getLongitudeE6()));
//		    gpRecordingOverlay.setData(drawLine(linePoints,false));
		  /*  if(isPlaying){
//		    	gpPlaybackverlay.setData(drawColorsShortLine(currentLocation.getSpeed(),points));
//		    	mBaiduMap.addOverlay(drawColorsShortLine(currentLocation.getSpeed(),points));
		    	mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline); 
		    	shortLines.add((Polyline)mBaiduMap.addOverlay(drawColorsShortLine(currentLocation.getSpeed(),points)) );
		    }
		    else{
//		    	gpRecordingOverlay.setData(drawColorsShortLine(currentLocation.getSpeed(),points));
		    	mBaiduMap.addOverlay(drawColorsShortLine(currentLocation.getSpeed(),points)); 
		    }
		    */
		   
		    
		    if(currentLocation==null || currentLocation.getSpeed()==0){
		    	QLog.getLogger().dLog(dTAG, TAG+" drawShortLine --> draw  track end icon");
		    	
 		    	setEndIcon(/*linePoints[0]*/points.get(0)); 
		    	 
		    	
		    }else{
		    	
		    	if(recordingEndOvelay !=null) {
		    		recordingEndOvelay.removeFromMap();
		    	}
 
		    }
		    
		    shortLines.add((Polyline)mBaiduMap.addOverlay(drawColorsShortLine(currentLocation.getSpeed(),points)) );
 		    
	        }}.start();
		
	}
	
	
	 public void drawNaviLine(){
//		QLog.getLogger().d(dTAG,String.format("%s, currentlocation's provider: %s,lastLocation's provider%s", 
//				TAG,currentLocation.getProvider(),lastLocation.getProvider()));
//		if(currentLocation ==null || !currentLocation.hasSpeed() || !currentLocation.getProvider().equalsIgnoreCase(LocationManager.GPS_PROVIDER))return; 
//		if(lastLocation ==null || !currentLocation.hasSpeed() || !lastLocation.getProvider().equalsIgnoreCase(LocationManager.GPS_PROVIDER))return;
//		if(currentLocation==null || lastLocation==null  ) return;
		// QLog.getLogger().d(dTAG,"activity.app.playBack||activity.app.isNaving:  "+(activity.app.playBack||activity.app.isNaving));
//	 if( !(activity.app.playBack||activity.app.isNaving) )return;
	
		if( activity.app.naviTrackId<0 ||activity.app.playBack||!activity.app.isNaving)return; 
		
 
		 
	  if( Utils.isLocOfGPS(currentLocation) )
		new Thread(){
 	        @Override
 			public void run() {  
			 
			 Track  tr =activity.app.getTrackCache().get(Integer.valueOf(activity.app.naviTrackId));
			 
			 if( tr==null ||tr.getTrackBean().getLastWp().getWb().getLatitude()==0)return;
 	        	
			LatLng[] linePoints = new LatLng[2];
			if(currentLocation==null) return; 
		 	double mLat =  Utils.getbdLat(currentLocation.getLatitude(),currentLocation.getLongitude());
			double mLon =  Utils.getbdLon(currentLocation.getLatitude(),currentLocation.getLongitude()); 
			int lat = (int) (mLat*1E6);
		   	int lon = (int) (mLon*1E6);   
//			linePoints[i-1] = new LatLng(lat, lon); 
			linePoints[0] = new LatLng(lat, lon);
			
//			mLat =  Utils.getbdLat(lastLocation.getLatitude(),lastLocation.getLongitude());
//		    mLon =  Utils.getbdLon(lastLocation.getLatitude(),lastLocation.getLongitude()); 
//		    lat = (int) (mLat*1E6);
//		    lon = (int) (mLon*1E6);   
//		    linePoints[1] = new LatLng(lat, lon);
		    linePoints[1] =getLatLng(tr.getTrackBean().getLastWp().getWb());
		    
//			QLog.getLogger().d(TAG,String.format("shortline from %d,%d to %d,%d",
 
		    try{ 
			      mBaiduMap.addOverlay(drawNaviLine(linePoints));
			  
		    }catch(Exception e){
		    	QLog.getLogger().d(dTAG,e.getMessage());
		    }
 	        }}.start();
		
	} 
	
	public /*Graphic*/ PolylineOptions drawNaviLine(LatLng[] linePoints)
	{
//		  QLog.getLogger().d(dTAG, TAG+" begin draw the tracke line: drawLine start.");
		   //构建线
  	/*	Geometry lineGeometry = new Geometry(); 
  		lineGeometry.setPolyLine(linePoints);
  		//设定样式
  		Symbol lineSymbol = new Symbol();
  		Symbol.Color lineColor = lineSymbol.new Color();
//  		if(isPlayback &&drawTrack){ //draw playback track
  		int tsize =1;
  		 
   		{
  			lineColor.red = 200;
	  		lineColor.green = 0;
	  		lineColor.blue = 0;
	  		lineColor.alpha =70;
  			
  		}
  		lineSymbol.setLineSymbol(lineColor, tsize);
  		//生成Graphic对象
  		Graphic lineGraphic = new Graphic(lineGeometry, lineSymbol);
//  		 QLog.getLogger().d(dTAG, TAG+" end draw the tracke line: drawLine end.");
  		return lineGraphic;
  		*/
		 ArrayList<LatLng>  ps= new  ArrayList<LatLng> ();
		 ps.add(linePoints[0]);
		 ps.add(linePoints[1]);
  		int tsize =1;
  		
		PolylineOptions ooPolyline = new PolylineOptions().width(tsize)
              .points(ps).color(Color.argb(70, 200, 0, 0)).dottedLine(true) ;
		
		return ooPolyline;
	}
	
	
	 
	public void drawTrack( final Track_bean	tb ,/* final GraphicsOverlay graphicsOverlay,*/ final TrackOverlay trackOverly, final Boolean isDrawAsistTrack )
	{ 
		QLog.getLogger().dLog(dTAG,TAG+" begin to draw track "+ tb.getTrackId()+ ",isDrawAsistTrack ?  " + isDrawAsistTrack); 

		 if(tb==null|| tb.getTrkseg().size()==0|| tb.getLastWp() ==null || tb.getLastWp().getWb()==null 
				 ||tb.getStartWp() ==null||tb.getStartWp().getWb() ==null
//				 ||graphicsOverlay==null
				 ||!isAdded()) return;
		 
 		 removeShortLines();
 
//		isDrawingTrack =true;
//									QLog.getLogger().dLog(dTAG,TAG+" begin to draw track "+ tb.getTrackId()+ ",isDrawAsistTrack ?  " + isDrawAsistTrack); 
	  
		LatLng startPt =getLatLng(tb.getStartWp().getWb());//new LatLng(lat, lon);
				    
								    // QLog.getLogger().d(dTAG, " calculate lat lon of track startIcon............................");
									 // QLog.getLogger().d(dTAG, "  lat is: "+tb.getStartWp().getWb().getLatitude() +", lon is: "+tb.getStartWp().getWb().getLongitude());
								 	
	   	
	   	if(isDrawAsistTrack){
 	   		trackOverly.getOverlayOptions().add(setGeoIcon(startPt,R.drawable.icon_bstart));
	   	}else{
//	   		trackOverly.getOverlayOptions().add(setStartIcon(startPt)); 
	   		this.setStartIcon(startPt); 
	   	}
	   		 
	   
		//draw line for the whole track
		new Thread(){
	        @Override
			public void run() {
	        	
	        	if(isDrawingTrack){
	        		QLog.getLogger().d(dTAG, String.format("new thread to draw track....isDrawingTrack? %s",isDrawingTrack));
	        		return;        	
	        	}else{
	        		isDrawingTrack =true;
	        	}
	        	
 	        	 ArrayList<Waypoint_bean> al =tb.getTrkseg();   
		 		 if(al.size()<=2) {
		 			 isDrawingTrack=false;
		 			 return; 
		 		 }
				 ArrayList<LatLng> gpal= new ArrayList<LatLng>();	
				 long lastTime =0;
//				 float colorFactor=0; 
				 LatLng gp = null ;
//				 Waypoint_bean lastWb=null;
//				 LatLng lastGp=null;
				 float dist=0f;
				 final int colorCnt=2+(int)(tb.getDistance()/20000);//each 20 km add 1 more gp for color track.
				 long time=0;
				 int kmDist=(int)(tb.getDistance()/1000/50);//show 10 dist overlay item for a track.
				 kmDist=kmDist>0?kmDist:1;
				 kmDist=kmDist>1?kmDist:1;
//				 kmDist=1;
				 ArrayList<LatLng> kmgp= new ArrayList<LatLng>();	
				 float nextKm=0f;
				 int lastKm=0;
				 boolean hasKmflag=false;
				 boolean islushu = tb.getCreator()!=null &&tb.getCreator().startsWith("爱骑驴路书");
 		    	
				 try{ 
				   synchronized(al) {
							   	//draw points in cache
							   	if(tb.getStatus()==TrackStatus.RECORDING 
							   			&& activity.app.getRecordingTrack().getTrackBean().getTrackId() ==tb.getTrackId()
							   			&& activity.app.getRecordingTrack().getTrackBean().getStartTime() ==tb.getStartTime()
							   			){
							   		Location loc;
							   		Waypoint_bean wb;
							   		for (int i = 0; i <= activity.app.getLocationCached().size()-1; i++) {					   			
							   			loc = activity.app.getLocationCached().get(i);
							   			if(loc==null)continue;
							   			wb =new Waypoint_bean();
							   			wb.setLatitude((float) loc.getLatitude());
							   			wb.setLongitude((float) loc.getLongitude());
							   			wb.setSpeed(loc.getSpeed()* 3.6f);
							   			wb.setTime(loc.getTime());	 
							   			if(loc.getExtras().containsKey("dist")){
							   				wb.setDistance((float) loc.getExtras().getDouble("dist"));
							   			}
							   			al.add(wb);			
							   		}
							   		 
							   	}
							   	
					    	 for(Waypoint_bean wb:al){  //java.util.ConcurrentModificationException @Synchronized//	there is lock conflict with playback service.	use clone and resolve.
					    		 
						       	if(wb ==null ||wb.getLatitude()==0 ||wb.getLongitude()==0)continue; 
						       	    if(wb.getTime()<lastTime){
						        		QLog.getLogger().d(dTAG, String.format("duplicated wp detected... wb.getTime() %s,lastTime",wb.getTime(),lastTime));

						       	    	Log.e(dTAG,TAG +" duplicated wp dropped in drawring track.");
						       	    	continue;
						       	    } 
										//				       	   QLog.getLogger().d(dTAG, " calculate lat lon of track content............................");
										//				  		   QLog.getLogger().d(dTAG, "  lat is: "+wb.getLatitude() +", lon is: "+wb.getLongitude());
								    gp =getLatLng(wb); 	
								    
								   if( !activity.app.playBack &&  isDrawAsistTrack && QiYouConstant.DEVELOPER_MODE){
// 								    	mBaiduMap.addOverlay( drawFootPoint(new GPItem(50,wb.getLatitude(),wb.getLongitude(),100),100)); 
 								    	mBaiduMap.addOverlay( drawFootPoint(new GPItem(50,Math.round(wb.getLatitude()*activity.app.rd)/activity.app.rd,Math.round(wb.getLongitude()*activity.app.rd)/activity.app.rd  ,50),50));
								    }  
								    
								   /*	if(wb.getKmflag()>0){
								   		gpKMpointsOverlay.setData(drawKMPoint(gp));
								   		 
								   	} */
								    
								    if(!hasKmflag &&wb.getKmflag()>0){
								    	hasKmflag=true;
								    }
								    if((int)(wb.getKmflag()/kmDist)>lastKm ||!hasKmflag && (int) (wb.getSumDist()/1000/kmDist)>lastKm){
								    	lastKm++;
								    	kmgp.add(gp);
								    }
								    
								    nextKm+=wb.getDistance()/1000;
									if(kmDist>0&& nextKm>=kmDist){
		//								kmgp.add(gp);
								   		nextKm=0;
								   	} 
									if(lastTime ==0|| wb.getTime() -lastTime <= QiYouConstant.TIME_FOR_LIGHT_LINE)
										gpal.add(gp);
								   	
						 		    if(lastTime >0 && wb.getTime() -lastTime > QiYouConstant.TIME_FOR_LIGHT_LINE){	 
						 		    	if(gpal.size()>0 && ( isDrawAsistTrack ||islushu )){
						 		    		
 						 		    		mBaiduMap.addOverlay(drawLine( gpal ,isDrawAsistTrack ||islushu));
//						 		    		trackOverly.getPolylineOptions().add(drawLine( gpal ,isDrawAsistTrack)) ;
						 		    		gpal.clear();
						 		    	} else{ 
						 		    		
 						 		    		mBaiduMap.addOverlay(drawColorsShortLine((dist/time)*1000,  gpal));
//						 		    		trackOverly.getPolylineOptions().add(drawColorsShortLine((dist/time)*1000,  gpal));
						 		    		if( gpal.size()>=2 ||al.indexOf(wb)==al.size()-1){
						 		    			if(al.indexOf(wb)==al.size()-1)
						 		    				gpal.add(gp);
						 		    			
 						 		    			mBaiduMap.addOverlay(drawColorsShortLine((dist/time)*1000,  gpal));
//						 		    			trackOverly.getPolylineOptions().add(drawColorsShortLine((dist/time)*1000,  gpal));
						 		    		}
						 		    		if( gpal.size()>0 ){
							 		    		LatLng[] gps= { gpal.get(gpal.size()-1),gp};	
							 		    		 			 		    		 
 							 		    		mBaiduMap.addOverlay(drawNaviLine(gps));
//							 		    		trackOverly.getPolylineOptions().add(drawNaviLine(gps));
						 		    		}
										 	 
						 		    		gpal.clear();
								    		dist=0;
								    		time=0;
						 		    	}
		//				 		    	gpal.clear();
								    	gpal.add(gp);
						 		    	
		 
								    } else if(isDrawAsistTrack ||islushu){
								    		gpal.add(gp);						    	
								    	}
								    else if(lastTime>0){
		//						    	gpal.add(gp); 
								    	  dist +=wb.getDistance();
								    	  time +=wb.getTime()-lastTime;
								    	  
								    	if(gpal.size()>colorCnt ||al.indexOf(wb)==al.size()-1){
								    		
 		//						    	    gpal.toArray(new LatLng[2] );
 								    		mBaiduMap.addOverlay(drawColorsShortLine((dist/time)*1000,  gpal ));
//								    		trackOverly.getPolylineOptions().add(drawColorsShortLine((dist/time)*1000,  gpal ));
								    		gpal.clear();
								    		gpal.add(gp);
								    		dist=0;
								    		time=0;
								    	}
 								    }
								   	
								   lastTime =wb.getTime();  
 
									
							} 
				    	   }
 						 if((isDrawAsistTrack ||islushu) && gpal.size()>0 ){
 					        mBaiduMap.addOverlay(drawLine( gpal,isDrawAsistTrack ||islushu));
//							 trackOverly.getPolylineOptions().add(drawLine( gpal,isDrawAsistTrack));

						 }
						 else if(gpal.size()>0){
 							  mBaiduMap.addOverlay(drawColorsShortLine((dist/time)*1000,  gpal  ));
//							 trackOverly.getPolylineOptions().add(drawColorsShortLine((dist/time)*1000,  gpal  ));
						 }
		 		    	
 						 			QLog.getLogger().d(dTAG,TAG+" Draw track finished, it is isDrawAsistTrack track?  " + isDrawAsistTrack);
				    	  
						 	if(gp!=null){
					    	 	if(isDrawAsistTrack){  
 					    	   		trackOverly.getOverlayOptions().add(setGeoIcon(gp,R.drawable.icon_bend));
					    	 	}else{
					    	 		setEndIcon(gp); 
					    	 	}
						 	}
				    	 	
				    	   if(!isDrawAsistTrack) { 
				    		  QLog.getLogger().d(dTAG, String.format(" set candrawtrack  %s", false));

				    		  	canDrawTrack=false;
				    		  
				    	  } else{
				    		  
				    			isPlaybackTrackDrawed =true;
				    			
				    	  } 
				       
				    	 
				    	  
 					    	  showPicsOnMap(tb);
					    	  
//					    	  if( tb.getStatus()!=TrackStatus.RECORDING || tb.getType()==TrackType.COPY){
//					    		  showRoutePointsOnMap(tb);
//					    	  }			    		   
					    	  showRoutePointsOnMap(tb);  
					    	  showKMonMap(kmgp,kmDist); 
					    	  
//					    			  QLog.getLogger().dLog(dTAG, "   drawing track done, id is "+tb.getTrackId()+",track status is "+tb.getStatus()); 


							  isDrawingTrack =false;
							  
							  trackOverly.addToMap(); //for gpx 
						/*	  QLog.getLogger().dLog(dTAG, String.format("   drawing track done, id is %s," +
							  		"trackOverly.getOverlayOptions().size() %s, trackOverly.getOverlayMarkers().size() %s \n" +
							  		", trackOverly.getOverlayOptions().size() %s , trackOverly.getOverlayOptions().size() %s" ,
							  		tb.getTrackId(), trackOverly.getPolylineOptions().size(),trackOverly.getShortLines().size() 
							  		,trackOverly.getPolylineOptions().size(),trackOverly.getShortLines().size()
									  )); */
							  
 							  
		    	  }catch(Exception e){
		    		Utils.logStackTrace(e, TAG); 
		    		isDrawingTrack =false;
			        QLog.getLogger().dLog(dTAG, " draw track throws exception......  "); 

		    	} finally{
		    		isDrawingTrack =false;
		    	}
		 	     //finished the track line, set the flag to true;
				
	    }}.start(); 
	    
		   /* if(!isDrawAsistTrack) { 
	  		  QLog.getLogger().d(dTAG, String.format(" set candrawtrack  %s", false));
	
	  		  	canDrawTrack=false;
	  		  
		    } else{
	  		  
	  			isPlaybackTrackDrawed =true;
	  			
		    }*/
		    
 
		 
	}
	private /*Graphic*/ PolylineOptions drawColorsShortLine(float speed, ArrayList<LatLng>  linePoints) {
		
		/*
		Geometry lineGeometry = new Geometry(); 
//		LatLng[] linePoints = { fg,tg};
		 
  		lineGeometry.setPolyLine(linePoints);
  		//设定样式
  		Symbol lineSymbol = new Symbol();
  		Symbol.Color lineColor = lineSymbol.new Color();
//  		if(isPlayback &&drawTrack){ //draw playback track
  		int tsize =4;
  			
  		float factor =mTrack_bean.getAvs()/speed;
  	    int red =  200;
  		int green= 200;
  		red =(int) (factor==0?0:(red -factor*40));
//  		green =(int) (factor==0?255:(factor*100));
  		red=red<0?0:red;  		
  		green=255-red;
  		float avs =activity.app.playBack?activity.app.getCurrentTrack().getTrackBean().getAvs():mTrack_bean.getAvs();
  		float factor =avs==0?0:(speed/(avs/3.6f));
  		int green = (int) (150 -30*factor);
   		green=green>0?green:0;
  		int red = (int) (180*factor); 
  		red=red>255?255:red;
  		
		lineColor.red = red;
  		lineColor.green = green;
  		lineColor.blue = 255;
  		lineColor.alpha = 255;
  			
  		 
  		lineSymbol.setLineSymbol(lineColor, tsize);
  		//生成Graphic对象
  		Graphic lineGraphic = new Graphic(lineGeometry, lineSymbol);
//  		 QLog.getLogger().d(dTAG, TAG+String.format(" speed %s, avs %s, factor:%s, red %s, green %s",speed,mTrack_bean.getAvs()/3.6f,  factor,red,green));
  		return lineGraphic; */
		
		
		float avs =activity.app.playBack?activity.app.getCurrentTrack().getTrackBean().getAvs():mTrack_bean.getAvs();
  		float factor =avs==0?0:(speed/(avs/3.6f));
  		int green = (int) (150 -30*factor);
   		green=green>0?green:0;
  		int red = (int) (180*factor); 
  		red=red>255?255:red;
		
		
		PolylineOptions ooPolyline =null;
		int tsize =activity.app.playBack?6:8;
		tsize = tsize *2;
		if(linePoints.size()>1)  {
			ooPolyline = new PolylineOptions().width(tsize)
	              .points(linePoints).color(Color.argb(255, red, green, 255)) ;
		}
//		 QLog.getLogger().d(dTAG, TAG+String.format(" linePoints.size() %s" ,linePoints.size()));
		return ooPolyline;
		
	}
	protected void zoomToSpan(){
	 
		if( mTrack_bean==null || mTrack_bean.getRoadWps()==null || mTrack_bean.getRoadWps().isEmpty())return;
		
//		if(!canAutoZoomMap)return;
		
//		if( activity.app.getRecordingTrack().getTrackBean().getTrackId() ==mTrack_bean.getTrackId() &&mTrack_bean.getStatus()==TrackStatus.RECORDING )return;
		
	    double nwLat = -90 * 1000000;
	    double nwLng = 180 * 1000000;
	    double seLat = 90 * 1000000;
	    double seLng = -180 * 1000000;
	    // find bounding lats and lngs
	    LatLng point;
	    for(Waypoint_bean wb:mTrack_bean.getRoadWps()){
//	    for (LatLng point : points) {
	    	if(wb==null)continue;
	    	point=getLatLng(wb);
			nwLat = Math.max(nwLat, point.latitude); 
			nwLng = Math.min(nwLng, point.longitude );
			seLat = Math.min(seLat, point.latitude);
	        seLng = Math.max(seLng, point.longitude );
	    }
	    LatLngBounds.Builder builder = new LatLngBounds.Builder();
		 
	      builder.include(  new LatLng(nwLat,nwLng) );
	      builder.include(  new LatLng(seLat,seLng) );
	      
	      mBaiduMap.setMapStatus(MapStatusUpdateFactory
                  .newLatLngBounds(builder.build()));
	       
 
}
	
	protected LatLng[] getGPs( ArrayList<LatLng> D ){
 
		return D.toArray(new LatLng[1]);
	    		 
	}
	
 
	
	
	public /*Graphic*/ PolylineOptions drawLine(List<LatLng> linePoints,Boolean isDrawAsistTrack)
	{
//		  QLog.getLogger().d(dTAG, TAG+" begin draw the tracke line: drawLine start.");
		   //构建线
  	/*	Geometry lineGeometry = new Geometry(); 
  		lineGeometry.setPolyLine(linePoints);
  		//设定样式
  		Symbol lineSymbol = new Symbol();
  		Symbol.Color lineColor = lineSymbol.new Color();
//  		if(isPlayback &&drawTrack){ //draw playback track
  		int tsize =activity.app.playBack?2:4;
  		 if( isDrawAsistTrack){  
  			lineColor.red = 0;
	  		lineColor.green = 255;
	  		lineColor.blue = 0;
	  		lineColor.alpha = 255;
//	  		tsize=2;
  		}else //draw current Track
   		{
  			lineColor.red = 255;
	  		lineColor.green = 0;
	  		lineColor.blue = 0;
	  		lineColor.alpha = 255;
  			
  		}
  		lineSymbol.setLineSymbol(lineColor, tsize);
  	 */
		
//		Color color =new Color(Color.GREEN);
		
		if(linePoints==null || linePoints.size()<2){
			return null;
		}
		
		int tsize =activity.app.playBack?4:8;
		tsize = tsize *2;
		PolylineOptions ooPolyline = new PolylineOptions().width(tsize)
              .points(linePoints).color(isDrawAsistTrack?Color.GREEN:Color.RED) ;
  	  
  	  return ooPolyline;


	}
	
 
 
 
    /**
     * km point
     * @return 点对象
     */
     public /*Graphic*/  DotOptions drawFootPoint(GPItem gp ,int mAlpha){
    	
    	 if(gp==null  )return null;
    	 
    	 LatLng gpt = Utils.getLatLng(gp.getLat(),gp.getLng());
     
    	 if( gpt==null)return null;
    	 
//    	Geometry pointGeometry = new Geometry();
     
    	
    	int cnt=gp.getCnt();
    	int size= 10+cnt/5 ;
//    	int alpha=mAlpha>0?mAlpha:(100-cnt*2);
    	
    
    	size=size>30?30:size;
    	int alpha=mAlpha>0?mAlpha:(100-3*size);
    	alpha=alpha<10?10:alpha;
    	 
    	//pink
    	int red=250 ;
    	int green=150;
    	int blue=250;
     
    	green=green-cnt*5;
    	green=green<0?0:green; 
    	
//      QLog.getLogger().d(dTAG, String.format("cnt: %s rgb:%s,%s,%s  alpha:%s",cnt,red,green,blue,alpha));
    	
  		//设置坐标
//  		pointGeometry.setPoint(gp.getGp(), size);
    	
//    	pointGeometry.setPoint(gpt , size);
    	
     
/*    	  OverlayOptions ooDot = new DotOptions().center(gpt).radius(size)
                  .color(0xFF0000FF);
    	  
		symbol pointSymbol = new Symbol();
		Symbol.Color pointColor = pointSymbol.new Color();
		pointColor.red = red;
		pointColor.green = green;
		pointColor.blue = blue;
		pointColor.alpha = alpha; 
		pointSymbol.setPointSymbol(pointColor);
		Graphic pointGraphic = new Graphic(pointGeometry, pointSymbol);
  		return pointGraphic;*/ 
   		size= 20+cnt ;
   		size=size>30?30:size;
   		
   		float zoom = mBaiduMap.getMapStatus().zoom; 
   		
   		size = (int)(zoom/18f)*size;
   		
   		mAlpha =(int)( (cnt/4+0.5)*mAlpha);
   		mAlpha =mAlpha>255?255:mAlpha;
	
   		 

  	  return	 new DotOptions().center(gpt).radius(size )
         .color(Color.argb(mAlpha, red, green, blue));
    }	 
    
     
		 public  Bitmap getBitmapFromView(View view) {
		        //Define a bitmap with the same size as the view
		        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
		        return returnedBitmap;
		     
		    }
		    
		 
 
		 /**
		  * remove existed drawed shortlines
		  */
	  void removeShortLines(){
			 for(Polyline pl :shortLines){   
 	    		pl.remove();
 	    	}
		 } 
		 
		 protected void setStartIcon(LatLng gp){ 
  
			 // QLog.getLogger().d(dTAG, " to draw track startIcon............................");
			 // QLog.getLogger().d(dTAG, " gp.lat is: "+gp.getLatitudeE6() +", gp.lon is: "+gp.getLongitudeE6());
		 	
//			 setGeoIcon(gp,startOverlay);
 
//				setGeoIcon(gp,startOverlay,R.drawable.icon_sstart);
			 recordingStartOvelay.getOverlayOptions().add( setGeoIcon(gp,R.drawable.icon_sstart ));
		     recordingStartOvelay.addToMap();
			 
		 }
		 
		 protected void setEndIcon(LatLng gp){
			 
//			 if(mTrack_bean.getDistance()==0)return;   
//			 setGeoIcon(gp,endOverlay,R.drawable.icon_send);
			 
				recordingEndOvelay.getOverlayOptions().clear(); //endpoint is only one.
		    	recordingEndOvelay.getOverlayOptions().add( setGeoIcon(gp,R.drawable.icon_send ) );
		    	recordingEndOvelay.addToMap();
		    	
//			 return setGeoIcon(gp,R.drawable.icon_send );
		 }
		 
		 protected void removeMark(Marker mark){
			if(mark!=null){
				mark.remove();
			}
		 }
		 
		 protected void setGeoIcon(LatLng gp, Marker mark,int resid){ 
			 removeMark(mark);
			 setGeoIcon(gp,mark,resid,true);
		 }
		 
		 protected  MarkerOptions setGeoIcon(LatLng gp, int resid ){
			return new MarkerOptions().position(gp).icon(BitmapDescriptorFactory
						.fromResource(resid) ); 
		 }
		 
		 protected void setGeoIcon(LatLng gp,/*ItemizedOverlay<OverlayItem>*/ Marker mark,int resid,Boolean isClean){ 
			 
			 MarkerOptions ooB = new MarkerOptions().position(gp).icon(BitmapDescriptorFactory
						.fromResource(resid) ) /*.zIndex(5)*/;
				 
			 mark = (Marker) (mBaiduMap.addOverlay(ooB)); 
			 
			 
		 
//			 	markerOptions.position(gp);
//						.zIndex(9)
//						.draggable(true);
			 
//				  (Marker) (mBaiduMap.addOverlay(markerOptions.position(gp)));
//			 mBaiduMap. markerOptions.position(gp)
//				  mBaiduMap.addOverlay(markerOptions.position(gp));
				 
			 
			 
				
		 }
		 
		  
		 
		 
		 ArrayList<Integer> getGpxTracks(){
			   ArrayList<Integer> ids;
				 if(activity.app.naviTrackId>0 &&activity.app.isNaving){
					 ids =new ArrayList<Integer>();
					 ids.add(activity.app.naviTrackId);
				 }else{
					
					 ids =activity.app.getGpxShowingTracks();
				 }
				 return ids;
		 }
		 
		ArrayList<Integer> gpxDrawd ;//= new ArrayList<Integer>();
		 protected void drawGpx(){ 
 
				 new Thread(){ 
					 
						@Override
						public void run() {
							
					 
							 ArrayList<Integer> ids =getGpxTracks();
							 
					 
							 for(int id:ids){
								  QLog.getLogger().d(dTAG, " begin to draw track, "+" check if gpx id is drawed or not: " +id);
								 
								 if(gpxDrawd.contains(Integer.valueOf(id))) { 
									 	continue;
									 }else{
									 }
								 
								 if(mTrack_bean!=null && id==mTrack_bean.getTrackId()) continue;
//								 if( id==mTrack_bean.getTrackId()) continue;
								 Track  tr = activity.app.getCurrentTrack().getTrackBean().getTrackId() ==id?
										      activity.app.getCurrentTrack() 
										     :activity.app.getTrackCache().get(Integer.valueOf(id));
								 if(tr==null)continue;
								 
									while( 	 isDrawingTrack   ){
		//				        	  
			 			        	 try {
						 				Thread.sleep(100); 
			 			        	 }   catch (InterruptedException e) {
			 			 				// TODO Auto-generated catch block
			 			 				Utils.logStackTrace(e, TAG);
			 			 				}
			 				    	}
									  QLog.getLogger().d(dTAG, " begin to draw track, "+" to draw gpx id is: " +id); 
									
									  if(gpxOverlay==null){
									 		gpxOverlay= new TrackOverlay(mBaiduMap);
									 	}
 									drawTrack( tr.getTrackBean(),gpxOverlay  ,true);	 
									
									gpxDrawd.add(id);								
							 }		
	 			         
	 						//向handler发消息
//	 						handler.sendEmptyMessage(0);
	 					}}.start(); 
				 
			  }
			  
		 
 
			
			protected LatLng getLatLng(Waypoint_bean wb){ 
				return Utils.getLatLng(wb.getLatitude(), wb.getLongitude());
			}
			
 
			
			protected Waypoint_bean getWb(LatLng pt){
//				double mLat =  Utils.getggLat(pt.getLatitudeE6()/1e6, pt.getLongitudeE6()/1e6 );
//				double mLon =  Utils.getggLon(pt.getLatitudeE6()/1e6, pt.getLongitudeE6()/1e6); 
				double mLat =  Utils.getggLat(pt.latitude, pt.longitude );
				double mLon =  Utils.getggLon(pt.latitude, pt.longitude ); 
				Waypoint_bean wb = new Waypoint_bean();
				wb.setLatitude((float) mLat);
				wb.setLongitude((float) mLon);
			  return wb;
			}
			
			 
			void showPicsOnMap(Track_bean	mTrack_bean){ 
//				 btnMapPicture.setVisibility(View.GONE);
				if(mTrack_bean.getMdWps().size()==0)return;
				if(IL==null)IL = new com.qiyou.mb.android.utils.ImageLoader(activity);
				try{
					LatLng lastGp = null;
//					ArrayList<String> Urls=new ArrayList<String>();
					String Urlstr =""; 
//					List<OverlayItem> items =new ArrayList<OverlayItem>();
//					List<Marker> markers =new ArrayList<Marker>();
					List<OverlayOptions> markerOs = new ArrayList<OverlayOptions>();
					ArrayList<Media> medias = new ArrayList<Media>();
					LatLng gp = null;
				   	LatLng newGp=null;	
				   	picUrlMap =new HashMap<String,String>();
				 for(Waypoint_bean mwb:mTrack_bean.getMdWps()){
	//						if(wb!=null && wb.getTime()>=start && wb.getTime()<=end){
					 
					if(mwb!=null ){ 
						  gp = getLatLng(mwb);
					   	  newGp=gp;					  
//					   	Urls.add(md.getUri());
				   	 	if(lastGp==null)lastGp=gp;
				   	 		
//				   	   if(lastGp!=null){ 
								
								 if(gp.latitude==lastGp.latitude 
										 && gp.longitude ==lastGp.longitude 
//										 
										 ){
//									 medias.addAll(mwb.getMedias());//
									 
									 for(Media md: mwb.getMedias()){
										 
												 if(md.getType()==mediaType.PIC  ){
//													 
													  QLog.getLogger().d(dTAG,TAG+" "+ "same location: to add new pic to urls: " +mTrack.getValidMdUrl(md,false));  
//													 Urls.add(md.getUri());  
													 medias.add(md);
													 String url =mTrack.getValidMdUrl(md,false);
													 if(!TextUtils.isEmpty(url)){
														 picUrlMap.put(url, mTrack.getValidMdUrl(md,true));
														 Urlstr+=url+QiYouConstant.SPLITOR;//取原图
													 }
												 } 
									 } 
									 lastGp=gp;
									 continue;
								 } 	 
							     else{
							    	 //get mds from cache to OverlayItem list .
									 int i=0; 
									 for(Media md: medias){
//										 newGp=new LatLng(lastGp.latitudeE6+50*(i++),lastGp.getLongitudeE6()+50*i);
										 newGp=new LatLng(lastGp.latitude ,lastGp.longitude);
										
										 Bundle bd = new Bundle();
										 bd.putInt("index", 1 );
										 bd.putString("urls", Urlstr );
											MarkerOptions ooA = new MarkerOptions().position(newGp).anchor( 5*(i++),  10*i)
													.extraInfo(bd) 
													.icon(
														BitmapDescriptorFactory.fromBitmap(
																IL.getBitmap(mTrack.getValidMdUrl(md,true), QiYouConstant.MAP_PIC_SIZE))) 
													/*.zIndex(9)*/.draggable(true);
										 	markerOs.add(ooA);
//											 Marker mark = (Marker) (mBaiduMap.addOverlay(ooA)); 
//											 markers.add(mark);
											  
									/*	 
//										 OverlayItem item = new OverlayItem(newGp,Urlstr,md.getComment());
										 try{
								         item.setMarker(new BitmapDrawable(IL.getBitmap(mTrack.getValidMdUrl(md,true), QiYouConstant.MAP_PIC_SIZE))); //取缩略图
										 }catch(IllegalStateException e){
											Utils.logStackTrace(e,dTAG);
											continue;
										 }
								         items.add(item); */
									 }
									 
//									 Urls =new ArrayList<String>();
									 Urlstr="";
									 medias = new ArrayList<Media>();
									 
									 //add current md to cache
//									 medias.addAll(mwb.getMedias());//
									 for(Media md: mwb.getMedias()){
												 if(md.getType()==mediaType.PIC){
													  QLog.getLogger().d(dTAG,TAG+" "+ " 1 to add new pic to urls: " +mTrack.getValidMdUrl(md,false));  
//													 Urls.add(md.getUri());  
													 medias.add(md);
													 String url =mTrack.getValidMdUrl(md,false);
													 if(!TextUtils.isEmpty(url)){
														 picUrlMap.put(url, mTrack.getValidMdUrl(md,true));
														 Urlstr+=url+QiYouConstant.SPLITOR;//取原图
													 }
													 
												 } 
									 } 
									 
							 }
							  
							 lastGp=gp; 
							 
						
//					}
					}	
					
				 }
				 //get mds from cach to OverlayItem list .
				 int i=0; 
				 for(Media md: medias){
					 Bitmap b =IL.getBitmap(mTrack.getValidMdUrl(md,true),QiYouConstant.MAP_PIC_SIZE);
					 if(b==null)continue;
					/* newGp=new LatLng(lastGp.getLatitudeE6()+50*(i++),lastGp.getLongitudeE6()+50*i);
					 OverlayItem item = new OverlayItem(newGp,Urlstr,md.getComment());
			         item.setMarker(new BitmapDrawable(b)); 
			         items.add(item); */
					 
					 newGp=new LatLng(lastGp.latitude ,lastGp.longitude);
					 
					 Bundle bd = new Bundle();
					 bd.putInt("index", 1 );
					 bd.putString("urls", Urlstr );
						MarkerOptions ooA = new MarkerOptions().position(newGp).anchor( 5*(i++),  10*i)
								.extraInfo(bd)
								.icon(
									BitmapDescriptorFactory.fromBitmap(
											IL.getBitmap(mTrack.getValidMdUrl(md,true), QiYouConstant.MAP_PIC_SIZE))) 
								/*.zIndex(9)*/.draggable(true);
						markerOs.add(ooA);
//						 Marker mark = (Marker) (mBaiduMap.addOverlay(ooA)); 
//						 markers.add(mark);
						 
				 }
				 if(markerOs.isEmpty()) return;
				 
			 
	 
				 if(mPhotoOverlay==null){
					 mPhotoOverlay = new MdOverlay (mBaiduMap);
					 QLog.getLogger().dLog(dTAG,TAG+" initial mPhotoOverlay ...................");
				 }
				 QLog.getLogger().dLog(dTAG,TAG+" before add, mPhotoOverlay.getOverlayOptions().size " + mPhotoOverlay.getOverlayOptions().size());
				 mPhotoOverlay.getOverlayOptions().clear();
				 mPhotoOverlay.getOverlayOptions().addAll(markerOs);
				 mPhotoOverlay.addToMap();
				 if(handler!=null) handler.sendEmptyMessage(0);
				 QLog.getLogger().dLog(dTAG,TAG+" after add, mPhotoOverlay.getOverlayOptions().size " + mPhotoOverlay.getOverlayOptions().size());

	 
				 
				}catch(Exception er){
					Utils.logStackTrace(er, dTAG);
				} 
			}
			 
			 
		
			class RoadOverlay extends MdOverlay{

				public RoadOverlay(BaiduMap baiduMap) {
					super(baiduMap);
 				}  
				
				public static final String EXTR_KEY ="INFO";  
				public static final String EXTR_KEY_NAME ="NAME";
				public static final String EXTR_KEY_INDEX ="INDEX";
				public static final String EXTR_KEY_FLAG ="FLAG";
				@Override
				public boolean onMarkerClick(Marker marker) {
					OnInfoWindowClickListener listener = null;
					QLog.getLogger().d(dTAG,TAG+" pic icon on tap ..................to show road info window"); 
					for (Overlay mMarker : mOverlayList) {
			            if (mMarker instanceof Marker && mMarker.equals(marker)) { 
			            	
			            	 if (marker.getExtraInfo() != null) {
			            		 
			            		 isShowingPicMark =false;
			            		 return showInfoWindow( marker.getPosition(),marker.getExtraInfo().getString(EXTR_KEY),marker.getPosition());
//						            
						 				  /* popupText.setText(marker.getExtraInfo().getString(EXTR_KEY));  						  
										   
										   if(TextUtils.isEmpty(popupText.getText()))return true;
										    Bitmap[] bitMaps={ 
										    		 BMapUtil.getBitmapFromView(popupInfo)  
											    };
										     
						 						listener = new OnInfoWindowClickListener() {
						 							public void onInfoWindowClick() {
			// 
						 								mBaiduMap.hideInfoWindow();	
						 							}
						 								 
						 						};
						 						
			 			 				    LatLng ll = marker.getPosition() ;
											mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromBitmap(bitMaps[0]), ll, -47, listener);
											mBaiduMap.showInfoWindow(mInfoWindow); */
						 				   
 						 				 }
			            	 return true;
			            }
			            
					}
					return false;
					
				}				 
				
			}
			
			
			
			boolean showInfoWindow(LatLng ll ,String text,LatLng center){
				if(popupText==null){
					return false;
				}
				popupText.setText(text);  						  
				 OnInfoWindowClickListener listener = null;
				   if(TextUtils.isEmpty(popupText.getText()))return false;
				    Bitmap[] bitMaps={ 
				    		 BMapUtil.getBitmapFromView(popupInfo)  
					    };
				     
						listener = new OnInfoWindowClickListener() {
							public void onInfoWindowClick() {
// 
								mBaiduMap.hideInfoWindow();	
							}
								 
						};
						
						if(center!=null){ 
							locateBaiduMapCenter( center.latitude,center.longitude);
						}
					mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromBitmap(bitMaps[0]), ll, -47, listener);
					mBaiduMap.showInfoWindow(mInfoWindow);
					return true;
			}
			
			class LineOverlay extends OverlayManager{

//				private List<LatLng> latlngs = new ArrayList<LatLng>();
				private List<OverlayOptions> overlayList = new ArrayList<OverlayOptions>();
				public LineOverlay(BaiduMap baiduMap) {
					super(baiduMap);
					// TODO Auto-generated constructor stub
				}

				@Override
				public boolean onMarkerClick(Marker arg0) {
					// TODO Auto-generated method stub
					return false;
				}

				@Override
				public boolean onPolylineClick(Polyline arg0) {
					// TODO Auto-generated method stub
					return false;
				}
				
				/*public void setLatLngs(List<LatLng> lls){
					latlngs =lls;
				}*/
				

				@Override
				public List<OverlayOptions> getOverlayOptions() {
					 
					/*List<OverlayOptions> overlayList = new ArrayList<OverlayOptions>(); 
					  
		              overlayList.add(new PolylineOptions().points(latlngs).width(10)
		                      .color(  Color.argb(178, 0, 78, 255)).zIndex(0));  
					*/
					return overlayList;
				}
 
				public void setOverlayList(List<OverlayOptions> overlayList) {
					this.overlayList = overlayList;
				}
				  
			  }
			
			class TrackOverlay extends MdOverlay{
//				private  List<PolylineOptions> mPolylineOptionLists;
//				private List<Polyline> mShortLines =new ArrayList<Polyline>();
				public TrackOverlay(BaiduMap baiduMap) {
					super(baiduMap);
 				}  
				 
				 
				@Override
				public boolean onMarkerClick(Marker marker) { 
					return false; 
				}
				 
				@Override
				public List<OverlayOptions> getOverlayOptions() {
					// TODO Auto-generated method stub
					 if (mOverlayOptionList == null) {
				            mOverlayOptionList = new ArrayList<OverlayOptions>();
				        }
					return mOverlayOptionList;
				}
				
			 

			/*	public List<PolylineOptions> getPolylineOptions() {
					if (mPolylineOptionLists == null) {
						mPolylineOptionLists = new ArrayList<PolylineOptions>();
			        }
					return mPolylineOptionLists;
				}

	 
				
				*//**
			     * 将所有Overlay 从 地图上消除
			     *//*
			    public  void removeLinesFromMap() {
			        if (mBaiduMap == null) {
			            return;
			        }
			        for (Polyline line : mShortLines) {
			            line.remove();
			        }
			       
			        mShortLines.clear();

			    }


				public List<Polyline> getShortLines() {
					return mShortLines;
				}*/

 
			}
			
			boolean isShowingPicMark=false;
			
			class MdOverlay extends OverlayManager{ 
				protected  List<OverlayOptions> mOverlayOptionList;
				public MdOverlay(BaiduMap baiduMap) {
					super(baiduMap);
 				}
				void init(){
					 
				}
				@Override
				public boolean onMarkerClick(Marker marker) {
					OnInfoWindowClickListener listener = null;
					QLog.getLogger().d(dTAG,TAG+" pic icon on tap ..................to show popMd"); 
					for (Overlay mMarker : mOverlayList) {
			            if (mMarker instanceof Marker && mMarker.equals(marker)) { 
			            	
			                if (marker.getExtraInfo() != null) {
//			                    onRouteNodeClick(marker.getExtraInfo().getInt("index"));
			                    final String[]  urls =marker.getExtraInfo().getString("urls").split(QiYouConstant.SPLITOR_KEY);
			                    final int index  =marker.getExtraInfo().getInt("index");
			 				   Bitmap[] bitMaps={  
			 					  IL.getBitmap(picUrlMap.get(urls[urls.length-1]) , QiYouConstant.SUBNAIL_PIC_SIZE)     		
			 				      };
//			 				   popMd.showPopup(bitMaps,item.getPoint(),32);
			 				
//			 					if (marker == mMarkerA || marker == mMarkerD) {
//			 						button.setText("更改位置");
			 				   		
			 						listener = new OnInfoWindowClickListener() {
			 							public void onInfoWindowClick() {
//				 							   if(mCurItem==null|| TextUtils.isEmpty(mCurItem.getTitle()))return;
//				 								String[] urls=mCurItem.getTitle().split(QiYouConstant.SPLITOR_KEY);
			 								mBaiduMap.hideInfoWindow();	
			 								 if(urls.length>0){
				 									activity.showImagePagerFragment(index,	urls);
				 								 }	
				 								   
				 			 				}
			 						};
			 						
//			 						BitmapDescriptorFactory.fromBitmap(bitMaps[0]);		
			 				    LatLng ll = marker.getPosition();
								mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromBitmap(bitMaps[0]), ll, -47, listener);
								mBaiduMap.showInfoWindow(mInfoWindow);
								isShowingPicMark =true;
			 				   Toast.makeText(activity,  "点击缩略图可以浏览原图", 2).show(); 
//			                }
			                }
			                return true;
			            }
			            
					}
					return false;
					
				}
				
				@Override
				public boolean onPolylineClick(Polyline arg0) {
					// TODO Auto-generated method stub
					return false;
				}
				@Override
				public List<OverlayOptions> getOverlayOptions() {
					// TODO Auto-generated method stub
					 if (mOverlayOptionList == null) {
				            mOverlayOptionList = new ArrayList<OverlayOptions>();
				        }
					return mOverlayOptionList;
				}
			}
			
			
			   
			 @Override 
			protected  void showNaviPaoPao(Location location){
				 LatLng ll = Utils.getLatLng(location.getLatitude(), location.getLongitude());
			 String msg=location.getExtras().getString( QiYouConstant.NEW_NAVIFO_MSG);	
			 msg=TextUtils.isEmpty(msg)?"":msg.trim(); 
			 
			 showInfoWindow(ll,msg,null);
			 
				/* if(popupText==null)return;
				  popupText.setText(location.getExtras().getString( QiYouConstant.NEW_NAVIFO_MSG));
				  if(TextUtils.isEmpty(popupText.getText()))return;
				  Bitmap[] bitMaps={ 
				    		 BMapUtil.getBitmapFromView(popupInfo), 		
						   	
					    };
//					      
//				  popRd.showPopup(bitMaps,getLatLng(activity.app.getRecordingTrack().getTrackBean().getLastWp().getWb()),32);
				  try{
				  popRd.showPopup(bitMaps,Utils.getLatLng(location.getLatitude(), location.getLongitude()),32);
				  }catch (Exception er){
					  Utils.logStackTrace(er, TAG);
				  }*/
			  }
			  
			 @Override 
				protected  void showSharePaoPao(Map<String, String> location){
				 
				 float lat=Float.valueOf( location.get("lat"));
				 float lng=Float.valueOf( location.get("lon"));
				 LatLng ll = new LatLng( Utils.getbdLat( lat,lng) ,Utils.getbdLon(lat,lng) );
				 String msg=location.get("msg");	
				 msg=TextUtils.isEmpty(msg)?"":msg.trim(); 
				
//				 LatLng center =  new LatLng(Utils.getbdLat( ll.latitude,ll.longitude), Utils.getbdLon(ll.latitude,ll.longitude));
					    
//   			    locateMapCenter( ll.latitude,ll.longitude);
				
				 showInfoWindow(ll,msg,ll);
				 
					 /*if(popupText==null)return;
					 locateMapCenter(Float.valueOf( location.get("lat"))
							  ,Float.valueOf( location.get("lon")));
					 String msg=location.get("msg");					 
//					 if(TextUtils.isEmpty(popupText.getText()))return;
					 msg=TextUtils.isEmpty(msg)?"":msg.trim(); 
					  popupText.setText(msg);
					  if(TextUtils.isEmpty(popupText.getText()))return;
					  Bitmap[] bitMaps={ 
					    		 BMapUtil.getBitmapFromView(popupInfo), 		
							   	
						    };
//						      
//					  popRd.showPopup(bitMaps,getLatLng(activity.app.getRecordingTrack().getTrackBean().getLastWp().getWb()),32);
					  try{
					  popRd.showPopup(bitMaps,Utils.getLatLng(Float.valueOf( location.get("lat"))
							  ,Float.valueOf( location.get("lon"))),32);
					  }catch (Exception er){
						  Utils.logStackTrace(er, TAG);
					  } */
				  }
			 
			 
			 private void showKMonMap( ArrayList<LatLng>	kmgp,int kmDist){
				 
				  if(kmOverlay==null){
					  kmOverlay = new MdOverlay(mBaiduMap);
				  }
				 
				 for(LatLng gp:kmgp){
 					 kmOverlay.getOverlayOptions().add(getCustKmWpNum(gp,(kmgp.indexOf(gp)+1)*kmDist));
				 }
				 
			 }
			 
			  
			 MarkerOptions getCustKmWpNum( LatLng mGp,int i){ 
				   
 
				 
				  TextDrawableViewKm view = new TextDrawableViewKm(activity, "");
				  
				  MarkerOptions custWpNo =new MarkerOptions().position(mGp);
				  
				  
				  int size=i<100?40:i>999?80:60;
//				  QLog.getLogger().d(dTAG,TAG+" cust view size .................."+size); 
				  size =(int)(size*QiYouConstant.PV_INT_SCREEN_WIDTH/720f);
//				  QLog.getLogger().d(dTAG,TAG+" cust view new size .................."+size);
				  view.measure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY));
				  view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
				  view.destroyDrawingCache();
				  view.reWriteText((i)+"");
//				  view.setBackGround(i<100?R.drawable.icon_km:R.drawable.icon_km_big);
				  view.setBackGround( R.drawable.icon_km );
				  view.setAlpha(1); 
				  view.setTextColor(Color.BLACK); 
				  
				  view.buildDrawingCache();
 
				  custWpNo.icon(BitmapDescriptorFactory.fromBitmap( view.getDrawingCache() )) .anchor(0.5f, 0.5f);

				  
				  return custWpNo;
			  } 
			 
			 
			 @SuppressLint("NewApi")
			@TargetApi(Build.VERSION_CODES.HONEYCOMB)
			private void showRoutePointsOnMap(Track_bean	mTrack_bean){ 
//				 this.btnMapWayinstruction.setVisibility(View.GONE);
//				  List<OverlayItem> items =new ArrayList<OverlayItem>();
				  
				  List<OverlayOptions> markerOs = new ArrayList<OverlayOptions>();
				 
		          QLog.getLogger().dLog(dTAG, "TrackMap_fragment begin draw road points.............. ");

				  int i=0;
 				  int j=0;
//				  Waypoint_bean nextWb;
				  String title="";		
				  int drawIcon=0;
				  BitmapDescriptor bitDesc=null;
				  BitmapDescriptor bitDescPass=BitmapDescriptorFactory.fromResource(R.drawable.icon_pass);
				  BitmapDescriptor bitDescTent=BitmapDescriptorFactory.fromResource(R.drawable.icon_tent);;
				  BitmapDescriptor bitDescRest=BitmapDescriptorFactory.fromResource(R.drawable.icon_rest);;
				  BitmapDescriptor bitDescHand=BitmapDescriptorFactory.fromResource(R.drawable.icon_edit);;
 				  BitmapDescriptor bitDescDefault  = BitmapDescriptorFactory.fromResource(R.drawable.icon_waypoint);;
				  for(Waypoint_bean mwb:mTrack_bean.getRoadWps()){
 					  j++;
					  if(mwb==null)continue;
					  drawIcon=0;
					  title =mwb.getRoadBook();//+";"+mwb.getComment();
				 
					  if(QiYouConstant.DEVELOPER_MODE){
						  title =String.format(" roadbook %s, \n turn %s,beardist %s,dist %s",
								  title,mwb.getTurnFlag().toCHString(),mwb.getBearDist(),mwb.getDistance());
					  }
					  LatLng lg= getLatLng(mwb);
//					  OverlayItem   custWp  = new OverlayItem(,"",title);
//					  title="";
					  Bundle bd = new Bundle(); 
					  
					  bd.putString(RoadOverlay.EXTR_KEY, title ); 
						
					  MarkerOptions ooA = new MarkerOptions().position(lg).extraInfo(bd) ; 
						 
 						  if(isCustWaypoint(mwb)){
 							  
  							  QLog.getLogger().dLog(dTAG,TAG+" building custom roadinfo markoptions...."+j +", mwb.getTurnFlag() "+mwb.getTurnFlag().toCHString());
 							  
 							  
 							 if(mwb.getTurnFlag()==wpFlag.CUST && !isLiveQuery){
 								drawIcon =R.drawable.icon_pass;
 								bitDesc =bitDescPass;
 							 }
 							 else  if(mwb.getTurnFlag()==wpFlag.TENT){
 								drawIcon =R.drawable.icon_tent; 
 								bitDesc =bitDescTent;
 							 }
 							 else  if(mwb.getTurnFlag()==wpFlag.REST){
 								drawIcon =R.drawable.icon_rest;
 								bitDesc =bitDescRest;
 							 } else  if(mwb.getTurnFlag()==wpFlag.CHECK){
  								drawIcon =R.drawable.icon_check;
   							 } else  if(mwb.getTurnFlag()==wpFlag.HAND && !isLiveQuery){
  								drawIcon =R.drawable.icon_edit;
  								bitDesc = bitDescHand;
   							 }
 							
 							
  						 
// 							 ooA.anchor(0.5f, 1.0f);
						    if (drawIcon !=0){
						      try{ 
 						    	  markerOs.add( getCustWpNum(getLatLng(mwb),Integer.valueOf(mwb.getName()),mwb.getTurnFlag()));
 						    	 QLog.getLogger().dLog(dTAG,TAG+" 1 add customer wp number ..................." +Integer.valueOf(mwb.getName()));
//						    	  markerOs.add(ooA);
							  }catch(NumberFormatException er){
								  try{
									  markerOs.add( getCustWpNum(getLatLng(mwb),++i,mwb.getTurnFlag()));
		 						    	 QLog.getLogger().dLog(dTAG,TAG+" 2 add customer wp number ..................." +i);
								  }catch(Exception e){
									  Utils.logStackTrace(e, dTAG);
								  }
//								  markerOs.add(ooA);
							  }  
						    }
						     
						      
					  }else if (!isLiveQuery){  
						  
						  
//							drawIcon =R.drawable.icon_waypoint;  
							drawIcon = mwb.getBearing() > 0 ? R.drawable.icon_direction_small :R.drawable.icon_waypoint ;  
 				 
						    ooA.anchor(0.5f, 0.5f);
						    if ( mwb.getBearing()> 0){
						    	ooA.rotate(360 - mwb.getBearing() ); //逆时针旋转
						    }
					 	 
					  	}
 						  if(drawIcon!=0){
							 
 							  ooA .icon(BitmapDescriptorFactory.fromResource(drawIcon)).draggable(true);
							
 							  markerOs.add(ooA); 
 						  }
				  }
				   
				  
				  if(markerOs.isEmpty()) return;
				 
//				 
				
  				  
				 
				 if(mRdOverlay==null){
					 mRdOverlay = new RoadOverlay (mBaiduMap);
					 QLog.getLogger().dLog(dTAG,TAG+" initial RoadOverlay ...................");
				 }
				 QLog.getLogger().dLog(dTAG,TAG+" before add, mRdOverlay.getOverlayOptions().size " + mRdOverlay.getOverlayOptions().size());
				 mRdOverlay.getOverlayOptions().clear();
				 mRdOverlay.getOverlayOptions().addAll(markerOs);
 				 mRdOverlay.addToMap();	
				 if(handler!=null) handler.sendEmptyMessage(1);
			  }
			
			 
			 
			 MarkerOptions getCustWpNum( LatLng mGp,int i,wpFlag flag){
				   
				  MarkerOptions custWpNo =new MarkerOptions().position(mGp);
				  int width=i<10?20:i>=100?40:30;	
				  int height =i<10?25:i>=100?35:30;
//				  QLog.getLogger().d(dTAG,TAG+" cust view size .................."+width);
//				  QLog.getLogger().d(dTAG,TAG+" cust view size .................."+width*QiYouConstant.PV_INT_SCREEN_WIDTH/720f);
				  width =(int)(width*QiYouConstant.PV_INT_SCREEN_WIDTH/720f);
				  height =(int)(height*QiYouConstant.PV_INT_SCREEN_WIDTH/720f);
				  // QLog.getLogger().d(dTAG,TAG+" cust view new size .................."+width);
				  
				  TextDrawableView view = new TextDrawableView(activity,i+"", width,height); 
				  
				  view.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
				  view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
				  view.destroyDrawingCache();
//				  view.reWriteText(String.valueOf(i));
				  
				  view.buildDrawingCache();
 
				  Bundle bd = new Bundle(); 
				    
				  bd.putInt(RoadOverlay.EXTR_KEY_INDEX, i); 
				  bd.putInt(RoadOverlay.EXTR_KEY_FLAG , flag.toInt());
				  custWpNo.icon(BitmapDescriptorFactory.fromBitmap( view.getDrawingCache() )/*.fromView(wpNumText)*/).extraInfo(bd).anchor(0.5f, 0.5f);
				  
			 
				  
				  return custWpNo;
			  } 
			   
			  
			  @Override
			  void clearLiveItems(){
				  reNewShareOverflay();
			    }
			  
			 void reNewShareOverflay(){
				 if(mShareOverlay==null){
					  mShareOverlay= new RoadOverlay(mBaiduMap);
				 }
				 mShareOverlay.removeFromMap();
				 mBaiduMap.hideInfoWindow();	
				}
			
			 
			 Map<Integer,MarkerOptions> items =new HashMap<Integer,MarkerOptions>();
			
			 @Override
			  void showLiveMap(ArrayList<SharedLocation> deltaList) { 
				
 		    	QLog.getLogger().d(dTAG, "begin to paint live locations..............");
	
		            reNewShareOverflay();
//					 this.btnMapWayinstruction.setVisibility(View.GONE);
//					  List<OverlayItem> items =new ArrayList<OverlayItem>();
					  String title="";		
//					  int drawIcon=0;
 
					  
 					  QLog.getLogger().d(dTAG, String.format("----------deltaList.size %s", deltaList.size()));
					  
					  for(SharedLocation mwb:deltaList){
						 
						  if(mwb==null)continue;
						  
						  title =mwb.getMsg();
				 
						  Bundle bd = new Bundle(); 
						  
						  bd.putString(RoadOverlay.EXTR_KEY, title ); 
						  bd.putString(RoadOverlay.EXTR_KEY_NAME,   mwb.getName() ); 
						
							
//						  MarkerOptions ooA = items.get(Integer.valueOf(mwb.getId()))  ; 
//						  MarkerOptions   ooA = new MarkerOptions().position(Utils.getLatLng(mwb.getLat(), mwb.getLon())).extraInfo(bd);
//						  OverlayItem   custWp =items.get(Integer.valueOf(mwb.getId()));
						  
					/*	  if(ooA==null){
//							  custWp= new OverlayItem(  Utils.getLatLng(mwb.getLat(), mwb.getLon()),"",title); 
							  ooA = new MarkerOptions().position(Utils.getLatLng(mwb.getLat(), mwb.getLon())).extraInfo(bd);
						  }else{
							  custWp.setLatLng(Utils.getLatLng(mwb.getLat(), mwb.getLon()));
							  custWp.setSnippet(title); 
						  }
						   */
						  
						  
						  String nm=mwb.getName();
					      QLog.getLogger().d(dTAG, String.format("building name %s", mwb.getName() ));

						  nm=TextUtils.isEmpty(nm)?"unknown":nm;
 
							  int width=mwb.getName().length()*25;	
							  int height =35;
							  width =(int)(width*QiYouConstant.PV_INT_SCREEN_WIDTH/720f);
							  height =(int)(height*QiYouConstant.PV_INT_SCREEN_WIDTH/720f);
							  CompositDrawableView view = new CompositDrawableView(activity, mwb.getName(),10,
									  TextUtils.isEmpty(title),mwb.getBear(),width,height); 
							  view.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
							  view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
							  view.destroyDrawingCache();
//							  view.reWriteText(String.valueOf(i));
//							  view.setAlpha(alpha);
							  view.buildDrawingCache(); 
//							  custWp.setMarker( new BitmapDrawable(view.getDrawingCache()) );		
							  
							 
//							    custWp.setAnchor(OverlayItem.ALIGN_TOP);
//							    custWp.setTitle(mwb.getName());
							    
//							    items.add(custWp);
							    
							    MarkerOptions   ooA = new MarkerOptions().position(Utils.getLatLng(mwb.getLat(), mwb.getLon())).extraInfo(bd)
							    						.icon(BitmapDescriptorFactory.fromBitmap( view.getDrawingCache() )).anchor(0.5f, 0.1f);
							    
							    items.put(mwb.getId(), ooA);
							  
						   
						  
						
 						  QLog.getLogger().d(dTAG, "begin to paint live locations..............x");
					  }
					  
				/*	  for(  MarkerOptions   custWp : items.values()){
						  if(mShareOverlay.getAllItem().contains(custWp)){ 
//						    	boolean b=mShareOverlay.removeItem(custWp);
//						    	 QLog.getLogger().d(dTAG, String.format("removing sharpoints,name :%s msg: %s,succeed?%s", mwb.getName(),mwb.getMsg(),b));
//						    	 QLog.getLogger().d(dTAG, String.format("existed sharpoints,name :%s msg: %s  ", mwb.getName(),mwb.getMsg() ));
							  QLog.getLogger().d(dTAG, String.format("existed sharpoints,name :%s msg: %s  ",custWp.getSnippet(),custWp.getTitle()));

						    } else{
						    	mShareOverlay.addItem(custWp); 
						    	QLog.getLogger().d(dTAG, String.format("adding sharpoints,name :%s msg: %s",custWp.getSnippet(),custWp.getTitle()));
						    }
					  }*/
					  
 						QLog.getLogger().d(dTAG, "begin to paint live locations..............1");
					  
					  if(items.isEmpty()) return;
 						QLog.getLogger().d(dTAG, "begin to paint live locations..............2");
//					 
					 if(handler!=null) handler.sendEmptyMessage(3); 
					 
					if(mShareOverlay==null){
						  mShareOverlay= new RoadOverlay(mBaiduMap);
					}
					 mShareOverlay.getOverlayOptions().clear();
					 mShareOverlay.getOverlayOptions().addAll(items.values());
					 mShareOverlay.addToMap();
					 
					 
					 mShareOverlay.zoomToSpan();
 
				  }
			  
			    
			  
			  @Override
			  protected void showWayinstructions(){
				  
				  
				  if(mRdOverlay==null)return;
				  
					 QLog.getLogger().dLog(dTAG,TAG+" mRdOverlay.getOverlayOptions().size " + mRdOverlay.getOverlayOptions().size());
					 QLog.getLogger().dLog(dTAG,TAG+" mRdOverlay.getOverlayMarkers().size " + mRdOverlay.getOverlayMarkers().size());

				  if(mRdOverlay.getOverlayMarkers().size()>0){
					  QLog.getLogger().d(dTAG, " begin to hide wayinstructions");
					  mRdOverlay.removeFromMap();
					  this.btnMapWayinstruction.setImageResource(R.drawable.wayinstructions_inactive);
				  }else{
					  QLog.getLogger().d(dTAG, " begin to show wayinstructions");
					  perfomRotate(360);
					  mRdOverlay.addToMap();
 					  this.btnMapWayinstruction.setImageResource(R.drawable.wayinstructions4);
				  }
				  
				   
			  }
			  
//			  boolean 
			  
			  @Override
			  protected void showMapPicture(){
				  
				  if(mPhotoOverlay==null)return;
				  
					 QLog.getLogger().dLog(dTAG,TAG+" mPhotoOverlay.getOverlayOptions().size " + mPhotoOverlay.getOverlayOptions().size());
					 QLog.getLogger().dLog(dTAG,TAG+" mPhotoOverlay.getOverlayMarkers().size " + mPhotoOverlay.getOverlayMarkers().size());

				  if(mPhotoOverlay.getOverlayMarkers().size()>0){
					  QLog.getLogger().d(dTAG, "begin to hide pics");
					  mPhotoOverlay.removeFromMap();
					  this.btnMapPicture.setImageResource(R.drawable.picture_inactive);
				  }else{
					  QLog.getLogger().d(dTAG, "begin to show pics");
					  mPhotoOverlay.addToMap();
 					  btnMapPicture.setImageResource(R.drawable.picture); 
				  }
				   
			  }
	 
			  @Override
			  protected void roationMap(){ 
				   canRotationMap=!canRotationMap; 
				   
					handler = new Handler(){ 
						@Override
						public void handleMessage(Message msg) {  
							if (msg.what==1 && !canRotationMap) {  
//								  mMapController.setRotation(360);
//									mMapController.setOverlooking(-5);
								   perfomRotate(361);
								  btnRotation.setImageResource(R.drawable.icon_rotation_inactive);
							}
						}};
				   
						
				 
				  String msg="地图已切换到随动旋转模式";
				  if(!canRotationMap){
					   new Thread() {

							public void run() {

							try {

							Thread.sleep(500);

							} catch (Exception e) {

							}  
						 	   
						 	 handler.sendEmptyMessage(1);    
							};

							}.start();  
					  
 
					  msg="地图已退出随动旋转模式";
				  }else
					  btnRotation.setImageResource(R.drawable.icon_rotation);
				  
				  Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show(); 
			  }
			  
			   
			  @Override
			  protected void autoZoomMap(){
				  canAutoZoomMap=!canAutoZoomMap;
				  String msg="地图已切换到随动缩放模式";
				  if(!canAutoZoomMap){ 
					  btnAutoZoom.setImageResource(R.drawable.icon_auto_zoom_inactive);
					  msg="地图已退出随动缩放模式";
				  }else
					  btnAutoZoom.setImageResource(R.drawable.icon_auto_zoom);
				  
				  Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
			  }
			  
			  
			  
				 @Override
					public void onResume() {
						/**
						 * MapView的生命周期与Activity同步，当activity恢复时需调用MapView.onResume()
						 */	
// 
					 if(mMapView!=null){
						 mMapView.onResume();
//						 mMapView.refresh();
					 }
					 super.onResume(); 
					 updateFinshButonText();		
					 isShowingPicMark =false;
					}
					
					@Override
					public void onPause() {
						/**
						 * MapView的生命周期与Activity同步，当activity挂起时需调用MapView.onPause()
						 */
						 
					 
						if(mMapView!=null)
							try{
//								mMapView.setVisibility(View.INVISIBLE); 
								mMapView.onPause();
							}catch(Exception e){
								Utils.logStackTrace(e, TAG);
							}
						 
			 
						super.onPause();
					}


					@Override
					public void onDestroy() { 
						if(mMapView!=null) 
				  
							try{
								mMapView.onDestroy();
							}catch(Exception e){
								Utils.logStackTrace(e, TAG);
							}
						 
						// QLog.getLogger().d(dTAG,TAG+" "+"onDestroy" );
						super.onDestroy();
					}

					@Override
					public void onSaveInstanceState(Bundle outState) {
						super.onSaveInstanceState(outState);
						if(mMapView!=null)mMapView.onSaveInstanceState(outState); 
					}		
					
					
					/**
					 * load track and to start navi
					 */
					@Override
					 void  showWebTrack(Track tr){ 
						  if(tr==null)return;
						    this.activity.app.setCurrentTrack(tr,true);
 
						    activity.startNaviService(tr.getTrackBean().getSvrNumber(), false);
						    ll_navi_progress.setVisibility(View.VISIBLE);
					  }
					 
					 
				 
}


		    
