package com.smart.gtstrvl;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract.Document;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.esri.android.map.Callout;
import com.esri.android.map.FeatureLayer;
import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.LocationDisplayManager;
import com.esri.android.map.MapView;
import com.esri.android.map.ags.ArcGISLocalTiledLayer;
import com.esri.android.map.ags.ArcGISTiledMapServiceLayer;
import com.esri.android.map.event.OnLongPressListener;
import com.esri.android.map.event.OnSingleTapListener;
import com.esri.android.map.event.OnStatusChangedListener;
import com.esri.android.map.event.OnZoomListener;
import com.esri.core.geodatabase.ShapefileFeatureTable;
import com.esri.core.geometry.Geometry;
import com.esri.core.geometry.GeometryEngine;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.Polygon;
import com.esri.core.geometry.SpatialReference;
import com.esri.core.map.Graphic;
import com.esri.core.renderer.Renderer;
import com.esri.core.renderer.SimpleRenderer;
import com.esri.core.symbol.SimpleLineSymbol;
import com.esri.core.symbol.SimpleMarkerSymbol;
import com.esri.core.symbol.Symbol;
import com.esri.core.symbol.SimpleMarkerSymbol.STYLE;
import com.esri.core.tasks.na.NAFeaturesAsFeature;
import com.esri.core.tasks.na.Route;
import com.esri.core.tasks.na.RouteParameters;
import com.esri.core.tasks.na.RouteResult;
import com.esri.core.tasks.na.RouteTask;
import com.esri.core.tasks.na.StopGraphic;
import com.example.mountaintravel.adapter.ClassifyMainAdapter;
import com.example.mountaintravel.adapter.ClassifyMoreAdapter;
import com.example.mountaintravel.adapter.SearchAdapter;
import com.example.mountaintravel.base.BaseActivity;
import com.example.mountaintravel.kind.AddGraphic;
import com.example.mountaintravel.kind.DownLoaderTask;
import com.example.mountaintravel.kind.FindDbData;
import com.example.mountaintravel.kind.ZipExtractorTask;
import com.example.mountaintravel.util.AppJsonFileReader;
import com.example.mountaintravel.util.ArcgisUtil;
import com.example.mountaintravel.util.FileSizeUtil;
import com.example.mountaintravel.util.ListenerOnMapPinch;
import com.example.mountaintravel.util.Player;
import com.example.mountaintravel.util.StringChangeUtils;
import com.example.mountaintravel.util.StringUtils;
import com.example.mountaintravel.util.ToastUtil;
import com.example.mountaintravel.util.WebUtil;
import com.example.mountaintravel.variable.Variable;
import com.example.mountaintravel.view.Compass;
import com.google.code.microlog4android.config.PropertyConfigurator;

@SuppressLint({ "SdCardPath", "InflateParams", "HandlerLeak" })
public class BrowseMapActivity extends BaseActivity implements OnClickListener,
		RoutingDialogFragment.onGetRoute {
	final String extern = Environment.getExternalStorageDirectory().getPath();
	private LocationDisplayManager ldm;
	private static final String TAG = "BrowseMapActivity";
	private ClassifyMainAdapter classifyMainAdapter;
	private ClassifyMoreAdapter classifyMoreAdapter;
	private AddGraphic addgraphic;
	private MapView mapView;
	private ListView mainlist;
	private ListView morelist;
	private EditText searchText;// 搜索输入框
	private ListView searchList;// 搜索列表
	private ImageView searchImg;// 搜索按钮
	private ImageView searchClear;// 清除搜索按钮
	private ImageView eguide_tv3;// 标签按钮
	private ImageView position;// 定位按钮
	private CheckedTextView route;// 定位按钮
	private LinearLayout biaoji;//
	private ImageView Download;// 下载
	private LinearLayout dialog_mark;// 标签图标
	private ImageView eguide_tv2;// 线路按钮
	private int[] mark_text;// mark item id
	private boolean ifIntroduce = false;// 是否点击简介图标
	private boolean ifRoad = false;// 是否点击线路图标
	private boolean ifTag = false;// 是否点击标签图标
	private boolean isVoice = false;
	private ImageView big, small;// 放大缩小按钮
	private Callout callout;
	private View callout_view;
	private TextView callout_name;
	private ImageView togo;
	private ImageView voice;
	private LinearLayout LineVoice;
	private ImageView introduce;
	private LayoutInflater inflater;
	private Location loca;// 当前定位（gps）
	private double location_lat;// 当前位置的纬度
	private double location_lon;// 当前位置的经度
	private List<List<String>> Scenic;
	private String showCode = null;
	private String keyword = null;
	private String showName = null;
	private String x_togo = null;
	private String y_togo = null;
	private String imageUrl;
	private String audioPath;
	private List<Drawable> draw_pic;
	private LinearLayout startPoint;
	private CheckedTextView[] mark_lists;
	private ImageView calloutImg;
	private Drawable drawWithCallout;
	private Compass mCompass;
	private FindDbData dbData;
	private int count = 0;
	private int count_road = 0;
	private String download_url;
	private String zip_path;
	private String out_path;
	private String extractor_path;
	private SensorManager sm = null;// 创建一个SensorManager来获取系统的传感器服务
	private Sensor aSensor = null;// 加速度感应器
	private Sensor mSensor = null;// 磁力传感器
	private float[] accelerometerValues = new float[3];
	private float[] magneticFieldValues = new float[3];
	private float[] R2 = new float[9];
	private float[] values = new float[3];
	private GraphicsLayer start_layer;
	private GraphicsLayer search_layer;// 搜索结果图层
	private GraphicsLayer graphicsLayer = null;// 绘制线路图层
	private List<Map<String, String>> roadcount;
	private File oflineMapFile;
	private SearchAdapter searchAdapter;
	private ListenerOnMapPinch listenerOnMapPinch;
	private List<String> searchNameList;
	private List<Map<String, Double>> listPointXY = new ArrayList<Map<String, Double>>();
	private Map<String, Double> mapPointXY;
	private Player player;
	private GraphicsLayer testLayer = null;
	private Boolean isNavigation = false;
	private Map<String, Object> attributes;// 要素 属性
	private String parkCountUrl;
	private GraphicsLayer defaultMapPointLayer;
	private FeatureLayer featureLayertrail;
	private FeatureLayer featureLayerCycle;
	private RouteTask mRouteTask = null;
	private NAFeaturesAsFeature mStops = new NAFeaturesAsFeature();
	private String attractionName = "";// 景点详情页跳转地图
	private String attractionCode = "";
	private SharedPreferences sp;
	public String nameString = "";
	private Map<String, Object> parameterMap;// 网络请求需传递的键/值
	private ArcgisUtil gisUtil;
	private List<String> searchArray;// 搜索获取的结果集
	private boolean ismapFileDown = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		PropertyConfigurator.getConfigurator(this).configure();// 脱机日志
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.activity_eguide);
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		if (sp.getBoolean("getcode", false)) {
			Intent intent = getIntent();
			attractionName = intent.getStringExtra("name").trim();
			attractionCode = intent.getStringExtra("code").trim();
			// Log.d("TAG",
			// "attractionName ="+attractionName+"attractionCode　＝"+attractionCode);
			sp.edit().putBoolean("getcode", false).commit();
		}
		openGPSSettings();
		// ArcGISRuntime.setClientId("JbZMqzRbvsVtjOBW");// 去除水印
		initializeRoutingAndGeocoding();// 网络数据集
		initTitleBar(getResources().getString(R.string.gts_map_title));
		initdata();
		findMapView();
		findView();
		initLister();
		ifIntroduce = false;
		ifRoad = false;
		ifTag = false;
		ifclick();
		initView();
		location();
	}

	private void findView() {
		route = (CheckedTextView) findViewById(R.id.route);
		route.setOnClickListener(this);
		Download = (ImageView) findViewById(R.id.map_down);
		Download.setOnClickListener(this);
		searchText = (EditText) findViewById(R.id.search_text);
		searchText.setOnClickListener(this);
		// searchText.addTextChangedListener(watcher); // 添加按键捕捉
		searchImg = (ImageView) findViewById(R.id.search_img);
		searchImg.setOnClickListener(this);
		searchClear = (ImageView) findViewById(R.id.search_clear);
		searchClear.setOnClickListener(this);
		biaoji = (LinearLayout) findViewById(R.id.qiandyou);

		searchList = (ListView) findViewById(R.id.search_list);
		searchList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (testLayer != null) {
					testLayer.setVisible(false);
				}
				search_layer.removeAll();
				String name = searchNameList.get(arg2);
				/*
				 * if (name.contains("(")) { name = name.split("\\(")[0]; }
				 */
				searchText.setText(name);
				searchText.setSelection(searchText.getText().toString().trim()
						.length());
				searchList.setVisibility(View.GONE);
				// System.out.println(arg2+"sds"+searchArray.size());

				ItemSearch(arg2);
			}
		});
		dbData = new FindDbData(getApplicationContext());
		addgraphic = new AddGraphic(mapView, this);
		startPoint = (LinearLayout) findViewById(R.id.starting);
		dialog_mark = (LinearLayout) findViewById(R.id.dialog_mark);// 标签图标
		position = (ImageView) findViewById(R.id.map_nowGPS);
		position.setOnClickListener(this);
		eguide_tv3 = (ImageView) findViewById(R.id.eguide_tv3);
		eguide_tv3.setOnClickListener(this);
		eguide_tv2 = (ImageView) findViewById(R.id.eguide_tv2);
		eguide_tv2.setOnClickListener(this);
		dialog_mark.setVisibility(View.GONE);
		position.setVisibility(View.VISIBLE);
	}

	@SuppressWarnings("serial")
	private void initLister() {
		mapView.setOnLongPressListener(new OnLongPressListener() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean onLongPress(float x, float y) { // 滚动到指定位置
				mapView.centerAt(30.38389164, 120.218636746, true);
				if (graphicsLayer != null) {
					start_layer.removeAll();
					graphicsLayer.removeAll();
				}
				for (int i = 0; i < draw_pic.size(); i++) {
					if (mark_lists[i].isChecked() && testLayer != null) {
						mark_lists[i].setChecked(false);
						testLayer.setVisible(false);
					}
				}
				return true;
			}
		});
		mapView.setOnSingleTapListener(new OnSingleTapListener() {

			private static final long serialVersionUID = 1L;

			@Override
			public void onSingleTap(float x, float y) {
				if (callout.isShowing()) {
					callout.hide();
					if (player != null) {
						player.stop();
						player = null;
					}
					isVoice = false;
					ifclick();
				}
				if (isNavigation) {
					if (loca != null) {// 当前坐标不为null
						Point mapPoint = new Point(location_lon, location_lat);
						if (isInTheScenicArea(mapPoint)) {// 在景区内
							// if (true) {// 在景区内
							start_layer.removeAll();
							Graphic graphic2 = new Graphic(mapPoint,
									new SimpleMarkerSymbol(Color.BLUE, 15,
											SimpleMarkerSymbol.STYLE.CIRCLE));
							StopGraphic stop1 = new StopGraphic(graphic2);
							mStops.addFeature(stop1);
							Point map = mapView.toMapPoint(x, y);
							Point map2 = gisUtil.latAndlonTo(map.getX(),
									map.getY());
							Graphic graphic3 = addgraphic.addPoint2(
									map2.getX(), map2.getY(), getResources()
											.getDrawable(R.drawable.tp_2));
							Graphic graphic4 = new Graphic(map2,
									new SimpleMarkerSymbol(Color.BLUE, 15,
											STYLE.CIRCLE));
							start_layer.addGraphic(graphic3);
							StopGraphic stop2 = new StopGraphic(graphic4);
							mStops.addFeature(stop2);
							if (mStops.getFeatures().size() > 1) {
								screenClickRoute();
								isNavigation = false;
								mStops.clearFeatures();
							}
						} else {
							ToastUtil
									.show(getBaseContext(),
											getResources()
													.getString(
															R.string.gts_not_in_scenic_area));
							isNavigation = false;
						}
					} else {
						ToastUtil.show(
								getBaseContext(),
								getResources().getString(
										R.string.gts_not_get_current_location));
						isNavigation = false;
					}
				}
				hideKey();
				searchText.setCursorVisible(false);
				searchList.setVisibility(View.GONE);// 点击地图隐藏搜索列表
				if (testLayer != null && testLayer.isVisible()) {
					show(x, y, testLayer);
				} else if (search_layer != null && search_layer.isVisible()) {
					show(x, y, search_layer);
				}
				dialog_mark.setVisibility(View.GONE);
				startPoint.setVisibility(View.GONE);
				ifRoad = false;
				ifTag = false;
				ifclick();
			}
		});
		mapView.setOnStatusChangedListener(new OnStatusChangedListener() {
			private static final long serialVersionUID = 1L;

			public void onStatusChanged(Object source, STATUS status) {
				if ((status == STATUS.INITIALIZED) && (source == mapView)) {
					Point mapPoint = gisUtil.latAndlonToMapPoint(120.219899285,
							30.3832642960001);// 农耕文化园
					DefaultTrailShapefile();
					TrailShapefile();
					CycleShapefile();
					featureLayertrail.setVisible(false);
					featureLayerCycle.setVisible(false);
					mapView.zoomToScale(mapPoint, 10080.9);
					json("MapDefaultPoint2.json");
					AddMapDefaultPoint();
					if (!attractionName.equals("")
							&& !attractionCode.equals("")) {
						if ((attractionName.equals("登山游步道") && attractionCode
								.equals("2b2d7fe7-1822-4c31-a670-627936b49e9e"))
								|| (attractionName.equals("骑行赛道") && attractionCode
										.equals("3799c650-7382-4ce1-840a-07c87bb90115"))) {
							if (featureLayerCycle == null) {
								TrailShapefile();
								CycleShapefile();
							} else {
								featureLayerCycle.setVisible(true);
								featureLayertrail.setVisible(true);
							}
							biaoji.setVisibility(View.VISIBLE);
						} else {
							biaoji.setVisibility(View.INVISIBLE);
						}
						parameterMap = new HashMap<String, Object>();
						parameterMap.put("name", attractionName);
						parameterMap.put("code", attractionCode);
						sendRequestWithHttpClientMark(Variable.URL_GTS,
								parameterMap);
					}
				}
			}
		});
		mapView.setOnZoomListener(new OnZoomListener() {

			@Override
			public void preAction(float arg0, float arg1, double arg2) {

			}

			@Override
			public void postAction(float arg0, float arg1, double arg2) {
				double postScanle = mapView.getScale();
				if (postScanle >= 50000.0) {
					json("MapDefaultPoint1.json");
					AddMapDefaultPoint();
				} else if (postScanle < 50000.0 && postScanle >= 10000.0) {
					System.out.println("22 postScanle=: " + postScanle);
					json("MapDefaultPoint2.json");
					AddMapDefaultPoint();
				} else if (postScanle <= 6660.0) {
					json("MapDefaultPoint.json");
					AddMapDefaultPoint();
				}
			}
		});
	}

	public void AddMapDefaultPoint() {
		if (defaultMapPointLayer != null) {
			defaultMapPointLayer.removeAll();
		}
		for (int i = 0; i < Scenic.size(); i++) {
			String name = Scenic.get(i).get(2);
			/*
			 * if (name.contains("(")) { name = name.split("\\(")[0]; }
			 */
			double x = Double.parseDouble(Scenic.get(i).get(0));
			double y = Double.parseDouble(Scenic.get(i).get(1));
			defaultMapPointLayer.addGraphic(addgraphic.addText(x, y, name));
		}
	}

	@SuppressWarnings("deprecation")
	private void openGPSSettings() {
		LocationManager alm = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);
		if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {

		} else {
			AlertDialog isExit = new AlertDialog.Builder(this).create();
			// 设置对话框标题
			// 设置对话框消息
			isExit.setMessage("暂未开启GPS,去设置GPS");
			// 添加选择按钮并注册监听
			isExit.setButton("确定", listener);
			isExit.setButton2("取消", listener);
			// 显示对话框
			isExit.show();

		}
	}

	DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
		@SuppressLint("NewApi")
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				Intent myIntent = new Intent(
						Settings.ACTION_LOCATION_SOURCE_SETTINGS);
				startActivityForResult(myIntent, 0);
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
				break;
			}
		}
	};

	public void json(String name) {
		String jsonStr = AppJsonFileReader.getJson(getBaseContext(), name);
		Scenic = AppJsonFileReader.getjson(jsonStr);
	}

	public void show(float x, float y, GraphicsLayer layer) {
		if (!mapView.isLoaded()) {
			return;
		}
		if (callout.isShowing()) {
			callout.hide();
		}
		int tolerance = 2;
		Point point = mapView.toMapPoint(x, y);
		int[] IDS = layer.getGraphicIDs(x, y, tolerance);
		if (IDS != null && IDS.length > 0) {
			int id = IDS[0];
			x_togo = (String) layer.getGraphic(id).getAttributeValue("x");
			y_togo = (String) layer.getGraphic(id).getAttributeValue("y");
			showName = (String) layer.getGraphic(id).getAttributeValue("name");
			showCode = (String) layer.getGraphic(id).getAttributeValue("code");
			keyword = (String) layer.getGraphic(id)
					.getAttributeValue("keyword");
			imageUrl = (String) layer.getGraphic(id).getAttributeValue(
					"imagePath");
			audioPath = (String) layer.getGraphic(id).getAttributeValue(
					"audioPath");
			final int attributesType = Integer.parseInt((String) layer
					.getGraphic(id).getAttributeValue("type"));
			/*
			 * if (showName.contains("(")) {
			 * callout_name.setText(showName.split("\\(")[0]); } else {
			 * callout_name.setText(showName); }
			 */
			callout_name.setText(showName);
			// callout.setOffset(0, 0);//偏移量 x , y
			callout.setStyle(R.xml.calloutstyle);
			if (attributesType == 1 || attributesType == 2
					|| attributesType == 3 || attributesType == 4) {// 游、玩、吃、住，可弹出窗口
				if (imageUrl != null && imageUrl.contains(".jpg")) {
					Glide.with(getBaseContext()).load(imageUrl)
							.into(calloutImg);
				} else {
					calloutImg.setImageDrawable(drawWithCallout);
					// Glide.with(getBaseContext()).load().into(calloutImg);
				}
				if (!audioPath.contains(".mp3") || audioPath == null) {
					LineVoice.setVisibility(View.GONE);
				} else {
					LineVoice.setVisibility(View.VISIBLE);
				}
				callout.show(point, callout_view);
				togo.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (player != null) {
							player.pause();
						}
						Point togoStartPoint = gisUtil.latAndlonToPoint(
								location_lon, location_lat);
						Point togoEndPoint = gisUtil.latAndlonToPoint(
								Double.parseDouble(x_togo),
								Double.parseDouble(y_togo));
						// RouteClicked(togoEndPoint, togoStartPoint);
						if (isInTheScenicArea(togoStartPoint)) {
							RouteClicked(togoEndPoint, togoStartPoint);
						} else {
							ToastUtil
									.show(getBaseContext(),
											getResources()
													.getString(
															R.string.gts_not_in_scenic_area));
						}
					}
				});
				introduce.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {// 景点详情
						Intent intent = new Intent(BrowseMapActivity.this,
								TextActivity.class);

						if (keyword == null || keyword.equals("")) {
							intent.putExtra("name", showName);
						} else {
							intent.putExtra("name", showName + "(" + keyword
									+ ")");
						}
						intent.putExtra("code", showCode);
						// intent.putExtra("name", showName);
						startActivity(intent);
					}
				});

				voice.setOnClickListener(new ButtonClickListener());
			}
		}
	}

	private void initdata() {
		double[] point_x = new double[] { 120.21135165600003,
				120.21292190500003, 120.21560865100003, 120.21899675000009,
				120.23082345100011, 120.22834998300004, 120.23176593300002 };
		double[] point_y = new double[] { 30.372420485000077,
				30.374837409000065, 30.381783136000024, 30.383145310000032,
				30.390086887000052, 30.390791830000069, 30.391480468000054 };
		for (int i = 0; i < point_x.length; i++) {
			mapPointXY = new HashMap<String, Double>();
			mapPointXY.put("point_x", point_x[i]);
			mapPointXY.put("point_y", point_y[i]);
			listPointXY.add(mapPointXY);
		}
		parkCountUrl = "http://218.108.4.35:8080/CarInfoService.asmx/GetCarInfoList";
		download_url = "http://gwms.517gts.com/upload/create_scenic_area_info.zip";
		zip_path = Environment.getExternalStorageDirectory().getPath() + "/";
		out_path = zip_path + "gts/";
		extractor_path = zip_path + "create_scenic_area_info.zip";
		drawWithCallout = getResources().getDrawable(R.drawable.callout_image);
		mark_text = new int[] { R.id.mark_traveling, R.id.mark_play,
				R.id.mark_food, R.id.mark_farmhouse, R.id.mark_placeToPark,
				R.id.mark_wc, R.id.mark_customer, R.id.mark_problem };
		mark_lists = new CheckedTextView[mark_text.length];
		for (int i = 0; i < mark_text.length; i++) {
			mark_lists[i] = (CheckedTextView) findViewById(mark_text[i]);
			mark_lists[i].setOnClickListener(this);
		}
		draw_pic = new ArrayList<Drawable>();
		draw_pic.add(getResources().getDrawable(R.drawable.point_travel));// 游在皋亭
		draw_pic.add(getResources().getDrawable(R.drawable.point_play));// 娱在皋亭
		draw_pic.add(getResources().getDrawable(R.drawable.point_food));// 吃在皋亭
		draw_pic.add(getResources().getDrawable(R.drawable.point_hotel));// 住在皋亭
		draw_pic.add(getResources().getDrawable(R.drawable.point_parking));// 停车场
		draw_pic.add(getResources().getDrawable(R.drawable.point_wc));// 厕所
		draw_pic.add(getResources().getDrawable(R.drawable.point_customer));// 游客中心
	}

	@SuppressLint({ "WrongCall", "NewApi" })
	private void findMapView() {
		mapView = (MapView) findViewById(R.id.map);
		gisUtil = new ArcgisUtil(mapView);
		oflineMapFile = new File(out_path + "create_scenic_area_info/Basic.tpk");
		if (oflineMapFile.exists()) {
			ArcGISLocalTiledLayer tileLayer = new ArcGISLocalTiledLayer(
					"file:///sdcard/gts/create_scenic_area_info/Basic.tpk");
			mapView.addLayer(tileLayer);

		} else {
			ArcGISTiledMapServiceLayer tileLayer = new ArcGISTiledMapServiceLayer(
					"http://218.108.4.35:6080/arcgis/rest/services/Basic/MapServer");
			mapView.addLayer(tileLayer);
		}

		mapView.setAllowRotationByPinch(true);
		mapView.enableWrapAround(true);
		mapView.setEsriLogoVisible(false);// 去除logo
		mapView.setMinScale(60000.0);
		// mapView.setMapBackground(Color.WHITE, 0, 0, 0);
		listenerOnMapPinch = new ListenerOnMapPinch(this, mapView,
				R.id.button_compass);
		mapView.setOnPinchListener(listenerOnMapPinch);
		mCompass = (Compass) findViewById(R.id.button_compass);
		mCompass.setOnClickListener(new OnClickListener() {
			@SuppressLint("NewApi")
			@Override
			public void onClick(View v) {
				if (!mCompass.isSelected()) {
					initCompass();
					mCompass.setSelected(true);
					mCompass.bitmap = (BitmapFactory.decodeResource(
							getResources(), R.drawable.compass_selected));
				} else {
					mCompass.setSelected(false);
					mCompass.bitmap = (BitmapFactory.decodeResource(
							getResources(), R.drawable.compass));
				}
				callout.hide();
			}
		});
		mapView.setMapBackground(Color.WHITE, 0, 0, 0);
		big = (ImageView) findViewById(R.id.big);
		small = (ImageView) findViewById(R.id.small);
		big.setOnClickListener(this);
		small.setOnClickListener(this);
		callout = mapView.getCallout();
		inflater = LayoutInflater.from(BrowseMapActivity.this);
		callout_view = inflater.inflate(R.layout.calloutdialog_layout, null);
		calloutImg = (ImageView) callout_view.findViewById(R.id.callout_image);
		callout_name = (TextView) callout_view.findViewById(R.id.callout_name);
		callout_name.getBackground().setAlpha(120);// 0--255为透明度值
		togo = (ImageView) callout_view.findViewById(R.id.togo);
		introduce = (ImageView) callout_view.findViewById(R.id.introduce);
		voice = (ImageView) callout_view.findViewById(R.id.voice);
		LineVoice = (LinearLayout) callout_view.findViewById(R.id.lineVoice);
		graphicsLayer = new GraphicsLayer();
		search_layer = new GraphicsLayer();
		defaultMapPointLayer = new GraphicsLayer();
		// testLayer = new GraphicsLayer();
		mapView.addLayer(defaultMapPointLayer);
		mapView.addLayer(graphicsLayer);
		mapView.addLayer(search_layer);// 添加搜索结果图层
		// mapView.addLayer(testLayer);
		search_layer.setVisible(false);
		start_layer = new GraphicsLayer();
		mapView.addLayer(start_layer);
	}

	@SuppressWarnings("static-access")
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.route:
			startPoint.setVisibility(View.GONE);
			dialog_mark.setVisibility(View.GONE);
			biaoji.setVisibility(View.INVISIBLE);
			start_layer.removeAll();
			mStops.clearFeatures();
			File routeFile = new File(extern + "/shapfile/routedata");
			if (routeFile.exists()) {
				showNavigationDialog();
			} else {
				Toast.makeText(this, R.string.gts_file_deleted,
						Toast.LENGTH_SHORT).show();

			}
			break;
		case R.id.map_down:
			ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
			State mobile = cwjManager.getNetworkInfo(
					ConnectivityManager.TYPE_MOBILE).getState();
			State wifi = cwjManager.getNetworkInfo(
					ConnectivityManager.TYPE_WIFI).getState();
			if (mobile == State.CONNECTED || mobile == State.CONNECTING
					|| wifi == State.CONNECTED || wifi == State.CONNECTING) {
				new Thread(new Runnable() {
					@Override
					public void run() {
						URL mUrl = null;
						URLConnection connection = null;
						try {
							mUrl = new URL(download_url);
							connection = mUrl.openConnection();
							int length = connection.getContentLength();
							Message msg = new Message();
							msg.what = 3;
							Bundle bundle = new Bundle();
							bundle.putInt("length", length);
							msg.setData(bundle);
							handler.sendMessage(msg);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}).start();
			} else {
				ToastUtil.show(BrowseMapActivity.this, getResources()
						.getString(R.string.no_network));
			}

			break;
		case R.id.search_img:
			hideKey();
			String name = searchText.getText().toString().trim();// 获取要搜索的内容
			if (name != null && !name.equals("")) {
				parameterMap = new HashMap<String, Object>();
				parameterMap.put("name", name);
				sendRequestWithHttpSearch(Variable.URL_GTS, parameterMap);
			} else {
				ToastUtil.show(BrowseMapActivity.this, getResources()
						.getString(R.string.input_search_content));
			}
			biaoji.setVisibility(View.INVISIBLE);
			break;
		case R.id.search_text:
			if (searchAdapter == null) {
				searchList.setVisibility(View.GONE);
			}
			searchText.setCursorVisible(true);
			searchText.requestFocus();
			startPoint.setVisibility(View.GONE);
			dialog_mark.setVisibility(View.GONE);
			searchClear.setVisibility(View.VISIBLE);
			break;
		case R.id.search_clear:
			searchText.setText("");
			hideKey();
			searchText.setCursorVisible(false);
			searchClear.setVisibility(View.INVISIBLE);
			dialog_mark.setVisibility(View.GONE);
			startPoint.setVisibility(View.GONE);
			searchList.setVisibility(View.GONE);
			break;
		case R.id.big:
			mapView.zoomin();
			hideKey();
			break;
		case R.id.small:
			mapView.zoomout();
			hideKey();
			break;

		case R.id.eguide_tv2:// 线路
			road();
			break;
		case R.id.eguide_tv3:// 标签
			hideKey();
			if (!ifIntroduce) {
				count_road++;
				if (count_road % 2 != 0 || !ifTag) {
					ifTag = true;
					dialog_mark.setVisibility(View.VISIBLE);
					if (graphicsLayer != null) {
						start_layer.removeAll();
						graphicsLayer.removeAll();
					}
				} else {
					ifTag = false;
					dialog_mark.setVisibility(View.GONE);
				}
			}
			ifIntroduce = false;
			ifRoad = false;
			ifclick();
			startPoint.setVisibility(View.GONE);
			searchList.setVisibility(View.GONE);
			break;

		case R.id.map_nowGPS:// 点击定位，滚动到当前位置
			if (loca != null) {
				if (isInTheScenicArea(gisUtil.latAndlonToPoint(location_lon,
						location_lat))) {
					mapView.setScale(8000.8);
					mark_lists[0].setChecked(true);
					Point point = gisUtil.latAndlonToMapPoint(location_lon,
							location_lat);
					mapView.centerAt(point, false);
				} else {
					ToastUtil.show(BrowseMapActivity.this, getResources()
							.getString(R.string.gts_not_in_scenic_area));
				}
			} else {
				ToastUtil.show(BrowseMapActivity.this, getResources()
						.getString(R.string.gts_not_get_current_location));
			}

			break;
		}

		if (ifTag) {
			for (int i = 0; i < mark_lists.length; i++) {
				if (mark_text[i] == v.getId()) {
					if (mark_lists[i].isChecked()) {// 选中状态
						if (testLayer != null) {
							testLayer.setVisible(false);
							testLayer.removeAll();
						}
						if (featureLayerCycle != null) {
							featureLayerCycle.setVisible(false);// 隐藏地图上骑行道和游步道线路
							featureLayertrail.setVisible(false);
						}
						mark_lists[i].setChecked(false);
						biaoji.setVisibility(View.GONE);
					} else {// 未选中状态
						search_layer.setVisible(false);
						search_layer.removeAll();
						if (testLayer != null) {
							testLayer.removeAll();
						}
						if (i == 0) {
							if (!oflineMapFile.exists()) {// 如果地图底图离线文件存在，添加游步道和骑行道
								if (featureLayerCycle == null) {
									TrailShapefile();
									CycleShapefile();
								} else {
									featureLayerCycle.setVisible(true);
									featureLayertrail.setVisible(true);
								}
								biaoji.setVisibility(View.VISIBLE);
							}
							parameterMap = new HashMap<String, Object>();
							parameterMap.put("type", (i + 1));
							sendRequestWithHttpClientMark(Variable.URL_GTS,
									parameterMap);
							mark_lists[i].setChecked(true);
						} else if (i == 4) {
							mark_lists[i].setChecked(true);
							sendRequestWithHttpClient();// 请求剩余车位
							if (featureLayerCycle != null) {
								featureLayerCycle.setVisible(false);// 隐藏地图上骑行道和游步道线路
								featureLayertrail.setVisible(false);
							}
							biaoji.setVisibility(View.GONE);// 隐藏隐藏骑行道和游步道图标
						} else {
							mark_lists[i].setChecked(true);
							parameterMap = new HashMap<String, Object>();
							parameterMap.put("type", (i + 1));
							sendRequestWithHttpClientMark(Variable.URL_GTS,
									parameterMap);
							if (featureLayerCycle != null) {
								featureLayerCycle.setVisible(false);// 隐藏地图上骑行道和游步道线路
								featureLayertrail.setVisible(false);
							}
							biaoji.setVisibility(View.GONE);// 隐藏隐藏骑行道和游步道图标
						}

						// Log.d(TAG, "点击选项：" +
						// mark_lists[i].getText().toString());
					}
				} else if (v.getId() != R.id.eguide_tv3) {
					mark_lists[i].setChecked(false);
				}
			}

		}

	}

	private void road() {
		if (!ifIntroduce) {
			count++;
			if (count % 2 != 0 || !ifRoad) {
				ifRoad = true;
				startPoint.setVisibility(View.VISIBLE);
				if (testLayer != null) {
					testLayer.setVisible(false);
				}
				if (featureLayerCycle != null) {
					featureLayerCycle.setVisible(false);// 隐藏地图上骑行道和游步道线路
					featureLayertrail.setVisible(false);
					biaoji.setVisibility(View.GONE);// 隐藏隐藏骑行道和游步道图标
				}

				for (int i = 0; i < mark_lists.length; i++) {
					if (mark_lists[i].isChecked()) {
						mark_lists[i].setChecked(false);
						break;
					}
				}
			} else {
				ifRoad = false;
				startPoint.setVisibility(View.GONE);
			}
		}
		ifIntroduce = false;
		ifTag = false;
		ifclick();
		dialog_mark.setVisibility(View.GONE);
	}

	/**
	 * 是否下载 dialog
	 */
	private void showDownLoadDialog() {
		ismapFileDown = true;
		new AlertDialog.Builder(this)
				.setTitle(R.string.confirm)
				.setMessage(R.string.Yes_or_no_download)
				.setCancelable(false)
				.setPositiveButton(R.string.YES,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// Log.d(TAG, "onClick 下载 = " + which);
								doDownLoadWork();
								ismapFileDown = false;
							}
						})
				.setNegativeButton(R.string.NO,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// Log.d(TAG, "onClick 2 = " + which);
								ismapFileDown = false;
							}
						}).show();
	}

	/**
	 * 下载zip文件
	 */
	private void doDownLoadWork() {
		DownLoaderTask task = new DownLoaderTask(download_url, zip_path, this);
		task.execute();
	}

	/**
	 * 解压zip文件
	 */
	public void doZipExtractorWork() {
		ZipExtractorTask task = new ZipExtractorTask(extractor_path, out_path,
				this, true);
		task.execute();
	}

	/**
	 * 指南针
	 */
	public void initCompass() {
		// 创建一个SensorManager来获取系统的传感器服务
		sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		// 获取手机所有传感器

		aSensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);// 线性加速度
		mSensor = sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);// 磁力传感器
		sm.registerListener(myListener, aSensor,
				SensorManager.SENSOR_DELAY_GAME);
		sm.registerListener(myListener, mSensor,
				SensorManager.SENSOR_DELAY_GAME);
	}

	final SensorEventListener myListener = new SensorEventListener() {
		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			// 当获得数据的精度发生变化的时候被调用，比如突然无法获得数据时
			// Log.i(TAG, "onAccuracyChanged");
		}

		@SuppressLint("NewApi")
		@Override
		public void onSensorChanged(SensorEvent event) {// 当数据变化的时候被触发调用
			if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
				accelerometerValues = event.values.clone();
			}
			if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
				magneticFieldValues = event.values.clone();
			}
			// 调用getRotaionMatrix获得变换矩阵R[]
			SensorManager.getRotationMatrix(R2, null, accelerometerValues,
					magneticFieldValues);
			SensorManager.getOrientation(R2, values);
			// 经过SensorManager.getOrientation(R, values);得到的values值为弧度
			// 转换为角度
			values[0] = (float) Math.toDegrees(values[0]);
			if (mCompass.isSelected()) {
				if (values[0] > 5 || values[0] < -5) {
					mapView.setRotationAngle((Math.round(values[0]) / 5 * 5));
					mCompass.setRotationAngle(mapView.getRotationAngle());
					mCompass.postInvalidate();
				}
			}
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		mapView.unpause();
		if (player != null) {
			player.play();
		}
		if (mCompass.isSelected()) {
			sm.registerListener(myListener, aSensor,
					SensorManager.SENSOR_DELAY_GAME);
			sm.registerListener(myListener, mSensor,
					SensorManager.SENSOR_DELAY_GAME);
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		if (player != null) {
			player.pause();
		}
		mapView.pause();
		if (mCompass.isSelected()) {
			sm.unregisterListener(myListener);// 关闭触发器
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (player != null) {
			player.stop();
			player = null;
		}
	}

	// 点击线路item，加载线路
	public void sqlLine(List<String> list) {
		if (graphicsLayer != null) {

			graphicsLayer.removeAll();
			mapView.addLayer(graphicsLayer);
		}
		for (int i = 0; i < list.size(); i++) {
			graphicsLayer.addGraphic(addgraphic.addLine(list.get(i)));
			graphicsLayer.setVisible(true);
		}
	}

	public List<String> getData() {
		List<String> data = new ArrayList<String>();
		data.add("王蒙山隐入口");
		data.add("点将台入口");
		data.add("友梅轩入口");
		data.add("茶祖峒入口");
		data.add("捍海石宕入口");
		data.add("龙居诗碑入口");
		data.add("钱王城寨入口");
		return data;
	}

	@SuppressLint("NewApi")
	private void ifclick() {
		if (ifRoad) {
			eguide_tv2.setImageDrawable(getResources().getDrawable(
					R.drawable.mark_road_check));
		} else {
			eguide_tv2.setImageDrawable(getResources().getDrawable(
					R.drawable.mark_road));
		}
		if (ifTag) {
			eguide_tv3.setImageDrawable(getResources().getDrawable(
					R.drawable.mark_mark_check));
		} else {
			eguide_tv3.setImageDrawable(getResources().getDrawable(
					R.drawable.mark_mark));
		}
		if (isVoice) {
			voice.setImageDrawable(getResources().getDrawable(
					R.drawable.yuying_stop));
		} else {
			voice.setImageDrawable(getResources()
					.getDrawable(R.drawable.yuying));
		}
	}

	// 显示视图
	private void initView() {
		mainlist = (ListView) findViewById(R.id.main_view);
		morelist = (ListView) findViewById(R.id.more_view);
		classifyMainAdapter = new ClassifyMainAdapter(this, getData());
		mainlist.setSelection(0);// 默认选中第一个选项
		mainlist.setAdapter(classifyMainAdapter);// 建立数据适配

		// 设置listView当中的每个单项点击的事件变化逻辑处理
		mainlist.setOnItemClickListener(new OnItemClickListener() {

			// 主目录的点击事件发生后，就要为侧目进行数据的交互
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// mainSelectPostion = position;
				// 主目录一位数组的大小和侧目录二维数组的行的数目是一致的
				// 点击传入二维数组的一行的数据
				inintAdapter((position + 1) + "");
				// 设置选中的选的id
				classifyMainAdapter.setSelectItem(position);
				// 更新数据的变更
				classifyMainAdapter.notifyDataSetChanged();
				new Thread(new Runnable() {
					@Override
					public void run() {
						Message msg = new Message();
						msg.what = 1;
						Bundle bundle = new Bundle();
						bundle.putStringArrayList(
								"list",
								dbData.duan(roadcount.get(0).get(
										"RuKouIdAllRoadIndex")));
						msg.setData(bundle);
						handler.sendMessage(msg);
					}
				}).start();
				Point point = gisUtil.latAndlonToMapPoint(
						listPointXY.get(position).get("point_x"), listPointXY
								.get(position).get("point_y"));
				if (start_layer != null) {
					start_layer.removeAll();
				}
				start_layer.addGraphic(addgraphic.addPoint(
						listPointXY.get(position).get("point_x"), listPointXY
								.get(position).get("point_y")));
				mapView.centerAt(point, false);
				mapView.setScale(10000.8);
			}

		});

		/**
		 * CHOICE_MODE_NONE是普通模式， CHOICE_MODE_SINGLE是单选模式，不常用，
		 * CHOICE_MODE_MULTIPLE和CHOICE_MODE_MULTIPLE_MODAL都是多选模式
		 * 
		 * 设置选着的模式
		 * */
		mainlist.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		inintAdapter(1 + "");// 设置还没有点击时默认的显示页面的内容
		morelist.setOnItemClickListener(new OnItemClickListener() {// 设置详细列表的点击事件处理逻辑
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				classifyMoreAdapter.setSelectItem(position);
				classifyMoreAdapter.notifyDataSetChanged();
				new Thread(new Runnable() {
					@Override
					public void run() {
						Message msg = new Message();
						msg.what = 1;
						Bundle bundle = new Bundle();
						bundle.putStringArrayList(
								"list",
								dbData.duan(roadcount.get(position).get(
										"RuKouIdAllRoadIndex")));
						msg.setData(bundle);
						handler.sendMessage(msg);
					}
				}).start();
				// sqlLine(dbData.duan(roadcount.get(position).get("RuKouIdAllRoadIndex")));

			}
		});
	}

	// 为侧目录(详细目录)进行数据的匹配处理
	private void inintAdapter(String str) {
		classifyMoreAdapter = new ClassifyMoreAdapter(this,
				dbData.findRoad(str));
		morelist.setAdapter(classifyMoreAdapter);
		classifyMoreAdapter.notifyDataSetChanged();
		roadcount = dbData.findRoad(str);
	}

	public void location() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				ldm = mapView.getLocationDisplayManager();
				ldm.setAllowNetworkLocation(true);
				ldm.setAutoPanMode(LocationDisplayManager.AutoPanMode.OFF);
				Message msg = new Message();
				msg.what = 2;
				handler.sendMessage(msg);
			}
		}).start();
	}

	// 获取位置
	private class MyLocationListener implements LocationListener {
		public MyLocationListener() {
			super();
		}

		public void onLocationChanged(Location loc) {
			loca = loc;
//			location_lat = loc.getLatitude();
//			location_lon = loc.getLongitude();
			location_lon = 120.21037950500011;
			location_lat = 30.376674960000059;
		}

		public void onProviderDisabled(String provider) {
		}

		public void onProviderEnabled(String provider) {
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}

	public String getSDPath() {
		File sdDir = null;
		// 判断SD卡是否存在
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取根目录
		}
		return sdDir.toString();
	}

	Handler handler = new Handler() {

		@SuppressWarnings({ "static-access", "unchecked" })
		public void handleMessage(Message msg) {
			Bundle bundle = msg.getData();
			switch (msg.what) {
			case 1:
				sqlLine(bundle.getStringArrayList("list"));
				break;

			case 2:// 位置
				ldm.setLocationListener(new MyLocationListener());
				ldm.start();
				break;
			case 3:
				dialog_mark.setVisibility(View.GONE);
				startPoint.setVisibility(View.GONE);
				File file = new File(out_path
						+ "create_scenic_area_info/Basic.tpk");
				FileSizeUtil filesize = new FileSizeUtil();
				double len = filesize.getFileOrFilesSize(extractor_path, 1);
				int length = bundle.getInt("length");
				if (ismapFileDown) {
					return;
				}
				if ((int) Math.round(len) != length) {

					showDownLoadDialog();
				} else if ((int) Math.round(len) == length && !file.exists()) {
					showDownLoadDialog();
				} else {
					Toast.makeText(getBaseContext(), R.string.Already_Download,
							Toast.LENGTH_SHORT).show();
				}
				break;
			case 4:// 车位
				String response = (String) msg.obj;
				// System.out.println("result=:" + response);
				List<List<String>> UnComeCount = getParkInfoHandle(response);
				json("parking.json");
				if (Scenic.size() > 0) {
					for (int i = 0; i < Scenic.size(); i++) {
						attributes = new HashMap<String, Object>();
						String x = Scenic.get(i).get(0);// x
						String y = Scenic.get(i).get(1);// y
						String name = Scenic.get(i).get(2);// name
						String unComeCount = 0 + "";
						if (UnComeCount.size() > 0) {// 获得车位信息
							for (int j = 0; j < UnComeCount.size(); j++) {
								if (name.equals(UnComeCount.get(j).get(0))) {
									unComeCount = UnComeCount.get(j).get(4);
								}
							}
						}

						attributes.put("x", x);
						attributes.put("y", y);
						attributes.put("name", name);
						attributes.put("code", null);
						attributes.put("type", "5");
						attributes.put("imagePath", null);
						attributes.put("audioPath", null);
						attributes.put("UnComeCount", unComeCount);
						if (testLayer == null) {
							testLayer = new GraphicsLayer();
							mapView.addLayer(testLayer);
						}
						testLayer.addGraphic(addgraphic.AddCompositeSymbol(
								attributes, draw_pic.get(4)));
						if (!testLayer.isVisible()) {
							testLayer.setVisible(true);
						}
					}
				}
				break;
			case 5:// 解析请求结果
					// Log.d("TAG", "解析请求结果");
				String result = (String) msg.obj;
				// Log.d("TAG","景点：result"+ result);
				analysisJson(result);
				break;
			case 6:// 解析请求结果
				String SearchResult = StringUtils.toString(msg.obj);
				HashMap<String, Object> sss = StringChangeUtils.toObject(
						SearchResult, HashMap.class);
				searchArray = (List<String>) sss.get("result");
				int searchResultCount = searchArray.size();
				if (searchResultCount > 1) {
					searchNameList = new ArrayList<String>();
					for (int i = 0; i < searchResultCount; i++) {
						HashMap<String, Object> ddd = StringChangeUtils
								.toObject(searchArray.get(i), HashMap.class);
						Object name = ddd.get("name");
						searchNameList.add(StringUtils.toString(name));
					}
					searchAdapter = new SearchAdapter(BrowseMapActivity.this,
							searchNameList);
					searchList.setAdapter(searchAdapter);
					searchList.setVisibility(View.VISIBLE);
				} else {
					searchList.setVisibility(View.GONE);
					analysisJson(SearchResult);
				}
				break;
			}
			super.handleMessage(msg);
		}
	};

	/**
	 * 隐藏键盘
	 */
	public void hideKey() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mapView.getWindowToken(), 0);
	}

	/**
	 * 以地图边界画多边形
	 * 
	 * @return
	 */
	public Polygon Drawpolygon() {
		Polygon poly = new Polygon();
		GraphicsLayer test = new GraphicsLayer();
		mapView.addLayer(test);
		Point point1 = new Point(120.21219412757301, 30.36401143321038);
		Point point2 = new Point(120.20128426169312, 30.38188222644989);
		Point point3 = new Point(120.22533270219984, 30.396097665260665);
		Point point4 = new Point(120.2390976409663, 30.387840531675938);
		poly.startPath(point1);
		poly.lineTo(point2);
		poly.lineTo(point3);
		poly.lineTo(point4);
		poly.lineTo(point1);
		return poly;
	}

	/**
	 * route 返回结果 point
	 */
	@SuppressLint("NewApi")
	public void onDialogRouteClicked(Point p1, Point p2) {
		FragmentManager fm = getFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		ft.remove(fm.findFragmentByTag("Dialog")).commit();
		// ldm.setAutoPanMode(LocationDisplayManager.AutoPanMode.NAVIGATION);//行驶状态，这将图标放置在屏幕底部，并将地图旋转至行驶的方向。
		if (graphicsLayer != null) {
			search_layer.removeAll();
			graphicsLayer.removeAll();
		}
		if (start_layer != null) {
			mStops.clearFeatures();
			start_layer.removeAll();

		}
		// Log.d(TAG, "p1=: " + p1 + "\t p2=: " + p2);
		mapView.centerAt(gisUtil.latAndlonToMapPoint(p1.getX(), p1.getY()),
				false);
		try {
			// Log.d(TAG, "p1.getX=: " + p1.getX() + "\t p1.getY=: " +
			// p1.getY());
			Graphic graphic1 = addgraphic.addPoint2(p1.getX(), p1.getY(),
					getResources().getDrawable(R.drawable.tp_1));
			Graphic graphic2 = addgraphic.addPoint2(p2.getX(), p2.getY(),
					getResources().getDrawable(R.drawable.tp_2));
			Graphic graphic3 = new Graphic(p1, new SimpleMarkerSymbol(
					Color.BLUE, 15, SimpleMarkerSymbol.STYLE.CIRCLE));
			Graphic graphic4 = new Graphic(p2, new SimpleMarkerSymbol(
					Color.BLUE, 15, SimpleMarkerSymbol.STYLE.CIRCLE));
			start_layer.addGraphic(graphic1);
			start_layer.addGraphic(graphic2);
			StopGraphic stop1 = new StopGraphic(graphic3);
			StopGraphic stop2 = new StopGraphic(graphic4);
			mStops.addFeature(stop1);
			mStops.addFeature(stop2);
			SpatialReference mapRef = mapView.getSpatialReference();
			RouteParameters params = mRouteTask
					.retrieveDefaultRouteTaskParameters();
			params.setOutSpatialReference(mapRef);
			SpatialReference cgsRef = SpatialReference
					.create(SpatialReference.WKID_WGS84);
			mStops.setSpatialReference(cgsRef);
			params.setStops(mStops);
			params.setReturnDirections(true);
			RouteResult results = mRouteTask.solve(params);
			Route result = results.getRoutes().get(0);
			// Log.d("TAG", "" + result);
			Geometry geom = result.getRouteGraphic().getGeometry();
			mapView.addLayer(start_layer);
			start_layer.addGraphic(new Graphic(geom, new SimpleLineSymbol(
					0x99990055, 3)));
			if (testLayer != null) {
				testLayer.setVisible(false);
			}
			if (featureLayerCycle != null) {
				featureLayerCycle.setVisible(false);// 隐藏地图上骑行道和游步道线路
				featureLayertrail.setVisible(false);
				biaoji.setVisibility(View.GONE);// 隐藏隐藏骑行道和游步道图标
			}
		} catch (Exception e) {
			// Log.e(TAG, "解析错误！");
			e.printStackTrace();
		}

	}

	public void screenClickRoute() {
		try {
			graphicsLayer.removeAll();
			search_layer.setVisible(false);
			search_layer.removeAll();
			SpatialReference mapRef = mapView.getSpatialReference();
			RouteParameters params = mRouteTask
					.retrieveDefaultRouteTaskParameters();
			params.setOutSpatialReference(mapRef);
			SpatialReference cgsRef = SpatialReference
					.create(SpatialReference.WKID_WGS84);
			mStops.setSpatialReference(cgsRef);
			params.setStops(mStops);
			params.setReturnDirections(true);
			RouteResult results = mRouteTask.solve(params);
			Route result = results.getRoutes().get(0);
			// Log.d("TAG", "" + result);
			Geometry geom = result.getRouteGraphic().getGeometry();
			mapView.addLayer(start_layer);
			start_layer.addGraphic(result.getRouteGraphic());
			start_layer.addGraphic(new Graphic(geom, new SimpleLineSymbol(
					0x99990055, 3)));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化网络数据集
	 */
	private void initializeRoutingAndGeocoding() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				String networkPath = "/shapfile/routedata/na.geodatabase";
				String networkName = "roads_ND";
				try {
					mRouteTask = RouteTask.createLocalRouteTask(extern
							+ networkPath, networkName);
				} catch (Exception e) {
					Log.d(TAG, "Error while initializing :" + e.getMessage());
					e.printStackTrace();
				}
			}
		}).start();
	}

	private void showNavigationDialog() {
		new AlertDialog.Builder(this)
				.setTitle(R.string.gts_route_change)
				.setMessage(R.string.gts_route_change_type)
				.setPositiveButton(R.string.gts_Manual_input,
						new DialogInterface.OnClickListener() {
							@SuppressLint("NewApi")
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								RoutingDialogFragment frag_dialog = null;
								FragmentManager fm = getFragmentManager();
								FragmentTransaction ft = fm.beginTransaction();
								if (loca != null) {
									// Point po = new
									// Point(loca.getLongitude(),loca.getLatitude());
									if (isInTheScenicArea(gisUtil
											.latAndlonToPoint(location_lon,
													location_lat))) {// 当前位置是否在景区内
										frag_dialog = new RoutingDialogFragment(
												loca);
									} else {
										frag_dialog = new RoutingDialogFragment(
												null);
									}
								} else {
									frag_dialog = new RoutingDialogFragment(
											null);
								}
								ft.add(frag_dialog, "Dialog");
								ft.commit();
							}
						})
				.setNegativeButton(R.string.gts_Click_screen,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								isNavigation = true;
								Toast.makeText(getBaseContext(),
										R.string.gts_Click_screen_Choice,
										Toast.LENGTH_SHORT).show();
							}
						}).show();
	}

	/**
	 * 加载shapefile文件
	 */
	public void TrailShapefile() {
		String shpPath = getSDPath() + "/shapfile/trailRoad/trail.shp";
		try {
			ShapefileFeatureTable shapefileFeatureTable = new ShapefileFeatureTable(
					shpPath);
			featureLayertrail = new FeatureLayer(shapefileFeatureTable);
			Symbol symbol = new SimpleLineSymbol(getResources().getColor(
					R.color.trailRoadColor), 3);
			// 骑行道颜色 #E69800
			Renderer renderer = new SimpleRenderer(symbol);
			featureLayertrail.setRenderer(renderer);
			mapView.addLayer(featureLayertrail);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void DefaultTrailShapefile() {
		String shpPath = getSDPath() + "/shapfile/trailRoad/trail.shp";
		try {
			ShapefileFeatureTable shapefileFeatureTable = new ShapefileFeatureTable(
					shpPath);
			FeatureLayer defaultfeatureLayertrail = new FeatureLayer(
					shapefileFeatureTable);
			Symbol symbol = new SimpleLineSymbol(getResources().getColor(
					R.color.trailRoadColor), 3);
			// 骑行道颜色 #E69800
			Renderer renderer = new SimpleRenderer(symbol);
			defaultfeatureLayertrail.setRenderer(renderer);
			mapView.addLayer(defaultfeatureLayertrail);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void CycleShapefile() {
		String shpPath = getSDPath() + "/shapfile/cycleRoad/cycle.shp";
		try {
			ShapefileFeatureTable shapefileFeatureTable = new ShapefileFeatureTable(
					shpPath);

			featureLayerCycle = new FeatureLayer(shapefileFeatureTable);
			Symbol symbol = new SimpleLineSymbol(getResources().getColor(
					R.color.cycleRoadColor), 3);
			// 骑行道颜色 #E69800
			Renderer renderer = new SimpleRenderer(symbol);
			featureLayerCycle.setRenderer(renderer);
			mapView.addLayer(featureLayerCycle);
		} catch (FileNotFoundException e) {
			e.printStackTrace();

		}
	}

	@SuppressWarnings({ "unchecked", "null" })
	public void ItemSearch(int index) {
		if (searchArray.size() > 0) {
			HashMap<String, Object> ddd = StringChangeUtils.toObject(
					searchArray.get(index), HashMap.class);
			String name = (String) ddd.get("name");
			Object code = ddd.get("code");
			Object keyword = ddd.get("keyword");
			Object type = ddd.get("type");
			Object potionX = ddd.get("potionX");
			Object potionY = ddd.get("potionY");
			String imagePath = (String) ddd.get("imagePath");
			if (imagePath != null && imagePath.contains(".jpg")) {
				imagePath = StringUtils.toString(imagePath).replace(".jpg",
						".mid.jpg");
			}
			Object audioPath = ddd.get("audioPath");
			// Log.d("TAG", "potionX =: " + potionX.toString() +
			// "\t  potionY = :"+ potionY.toString() + " \t imagePath : " +
			// imagePath);
			if (!potionX.equals("") && !potionY.equals("")) {
				attributes = new HashMap<String, Object>();
				attributes.put("x", potionX);
				attributes.put("y", potionY);
				attributes.put("type", type);
				attributes.put("name", name);
				attributes.put("code", code);
				attributes.put("keyword", keyword);
				attributes.put("imagePath", imagePath);
				attributes.put("audioPath", audioPath);
				int intType = Integer.parseInt((String) type);
				if (testLayer != null) {
					testLayer.removeAll();
				} else {
					testLayer = new GraphicsLayer();
					mapView.addLayer(testLayer);
				}
				testLayer.addGraphic(addgraphic.addPicture(
						draw_pic.get(intType - 1), attributes));
				testLayer.setVisible(true);
				double locationX = Double.parseDouble(StringUtils
						.toString(potionX));
				double locationY = Double.parseDouble(StringUtils
						.toString(potionY));
				Point point = gisUtil.latAndlonToMapPoint(locationX, locationY);
				mapView.centerAt(point, false);
				biaoji.setVisibility(View.INVISIBLE);
			} else if (name.equals("登山游步道") || name.equals("骑行赛道")) {
				if (featureLayerCycle == null) {
					TrailShapefile();
					CycleShapefile();
				} else {
					featureLayerCycle.setVisible(true);
					featureLayertrail.setVisible(true);
				}
				biaoji.setVisibility(View.VISIBLE);
			}

		}

	}

	private void sendRequestWithHttpClient() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					String result = WebUtil.get(parkCountUrl, null);
					if (result != null) {
						Message message = new Message();
						message.what = 4;
						message.obj = result.toString();
						handler.sendMessage(message);
					}

				} catch (Exception e) {
					System.out.println("请求失败 2");
					e.printStackTrace();
				}
			}
		}).start();// 这个start()方法不要忘记了
	}

	private void sendRequestWithHttpClientMark(final String url,
			final Map<String, Object> parameterMap) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					String result = WebUtil.post(url, parameterMap);
					if (result != null) {
						Message message = new Message();
						message.what = 5;
						message.obj = result;
						handler.sendMessage(message);
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();// 这个start()方法不要忘记了

	}

	private void sendRequestWithHttpSearch(final String url,
			final Map<String, Object> parameterMap) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					String result = WebUtil.post(url, parameterMap);
					// System.out.println(url + parameterMap.get("name"));
					if (result != null) {
						Message message = new Message();
						message.what = 6;
						message.obj = result;
						handler.sendMessage(message);
					}
					// System.out.println(result);

				} catch (Exception e) {
					System.out.println("请求失败 ");
					e.printStackTrace();
				}
			}
		}).start();// 这个start()方法不要忘记了

	}

	@SuppressWarnings("unchecked")
	public List<List<String>> getParkInfoHandle(String returnString) {
		List<List<String>> list = new ArrayList<List<String>>();
		try {
			org.dom4j.Document document = DocumentHelper
					.parseText(returnString);
			Element root = document.getRootElement();
			document = DocumentHelper.parseText(root.getText());
			root = document.getRootElement();
			// 获取所有子元素
			List<Element> childList = root.elements();
			List<String> paking;
			for (Element element : childList) {
				paking = new ArrayList<String>();
				paking.add(element.element("Name").getText());
				paking.add(element.element("Code").getText());
				paking.add(element.element("Total").getText());
				paking.add(element.element("ComeCount").getText());
				paking.add(element.element("UnComeCount").getText());
				list.add(paking);
			}
		} catch (DocumentException e) {
		}
		return list;
	}

	public void RouteClicked(Point p1, Point p2) {
		if (graphicsLayer != null) {
			search_layer.removeAll();
			graphicsLayer.removeAll();
		}
		if (start_layer != null) {
			mStops.clearFeatures();
			start_layer.removeAll();
		}
		// Log.d(TAG, "p1=: " + p1 + "\t p2=: " + p2);
		mapView.centerAt(gisUtil.latAndlonToMapPoint(p1.getX(), p1.getY()),
				false);
		try {
			Graphic graphic1 = addgraphic.addPoint(p1.getX(), p1.getY());
			Graphic graphic2 = addgraphic.addPoint(p2.getX(), p2.getY());
			Graphic graphic3 = new Graphic(p1, new SimpleMarkerSymbol(
					Color.BLUE, 15, SimpleMarkerSymbol.STYLE.CIRCLE));
			Graphic graphic4 = new Graphic(p2, new SimpleMarkerSymbol(
					Color.BLUE, 15, SimpleMarkerSymbol.STYLE.CIRCLE));
			start_layer.addGraphic(graphic1);
			start_layer.addGraphic(graphic2);
			StopGraphic stop1 = new StopGraphic(graphic3);
			StopGraphic stop2 = new StopGraphic(graphic4);
			mStops.addFeature(stop1);
			mStops.addFeature(stop2);
			SpatialReference mapRef = mapView.getSpatialReference();
			RouteParameters params = mRouteTask
					.retrieveDefaultRouteTaskParameters();
			params.setOutSpatialReference(mapRef);
			SpatialReference cgsRef = SpatialReference
					.create(SpatialReference.WKID_WGS84);
			mStops.setSpatialReference(cgsRef);
			params.setStops(mStops);
			params.setReturnDirections(true);
			RouteResult results = mRouteTask.solve(params);
			Route result = results.getRoutes().get(0);
			// Log.d("TAG", "" + result);
			Geometry geom = result.getRouteGraphic().getGeometry();
			start_layer.addGraphic(new Graphic(geom, new SimpleLineSymbol(
					0x99990055, 5)));
		} catch (Exception e) {
			Log.e(TAG, "解析错误！");
			e.printStackTrace();
		}

	}

	/**
	 * 当前点是否在景区内
	 * 
	 * @param point
	 * @return
	 */
	public boolean isInTheScenicArea(Point point) {
		return GeometryEngine.contains(Drawpolygon(), point,
				mapView.getSpatialReference());
	}

	private final class ButtonClickListener implements View.OnClickListener {
		@Override
		public void onClick(View v) {
			if (isVoice) {
				isVoice = false;
				if (player != null) {
					player.pause();
				}
			} else {
				isVoice = true;
				if (player != null) {
					player.play();
				} else {
					player = new Player();
					new Thread(new Runnable() {
						@Override
						public void run() {
							if (audioPath != null) {
								// player.playUrl("http://abv.cn/music/光辉岁月.mp3");
								player.playUrl(audioPath);
							}
						}
					}).start();
				}

			}
			ifRoad = false;
			ifTag = false;
			ifclick();
		}
	}

	@SuppressWarnings({ "unchecked", "null" })
	public void analysisJson(String result) {
		if (testLayer != null) {
			testLayer.removeAll();
		} else {
			testLayer = new GraphicsLayer();
			mapView.addLayer(testLayer);
		}
		HashMap<String, Object> sss = StringChangeUtils.toObject(result,
				HashMap.class);
		List<String> array = (List<String>) sss.get("result");
		// Log.i("TAG", "///////////********" + array.toString());
		for (int i = 0; i < array.size(); i++) {
			HashMap<String, Object> ddd = StringChangeUtils.toObject(
					array.get(i), HashMap.class);
			String name = (String) ddd.get("name");
			Object code = ddd.get("code");
			Object keyword = ddd.get("keyword");
			Object type = ddd.get("type");
			Object potionX = ddd.get("potionX");
			Object potionY = ddd.get("potionY");
			String imagePath = (String) ddd.get("imagePath");
			if (imagePath != null && imagePath.contains(".jpg")) {
				imagePath = StringUtils.toString(imagePath).replace(".jpg",
						".mid.jpg");
				// Log.i("TAG", "****imagePath!=null****");
			}
			Object audioPath = ddd.get("audioPath");
			// Log.d("TAG", "potionX =: " + potionX.toString() +
			// "\t  potionY = :"+ potionY.toString() + " \t imagePath : " +
			// imagePath);
			if (!potionX.equals("") && !potionY.equals("")) {
				attributes = new HashMap<String, Object>();
				attributes.put("x", potionX);
				attributes.put("y", potionY);
				attributes.put("type", type);
				attributes.put("name", name);
				attributes.put("code", code);
				attributes.put("keyword", keyword);
				attributes.put("imagePath", imagePath);
				attributes.put("audioPath", audioPath);
				int intType = Integer.parseInt((String) type);
				testLayer.addGraphic(addgraphic.addPicture(
						draw_pic.get(intType - 1), attributes));
				if (!testLayer.isVisible()) {
					testLayer.setVisible(true);
				}
				if (array.size() == 1) {
					double locationX = Double.parseDouble(StringUtils
							.toString(potionX));
					double locationY = Double.parseDouble(StringUtils
							.toString(potionY));
					Point point = gisUtil.latAndlonToMapPoint(locationX,
							locationY);
					mapView.centerAt(point, false);
				}
			} else if (name.equals("登山游步道") || name.equals("骑行赛道")) {
				if (featureLayerCycle == null) {
					TrailShapefile();
					CycleShapefile();
				} else {
					featureLayerCycle.setVisible(true);
					featureLayertrail.setVisible(true);
				}
				biaoji.setVisibility(View.VISIBLE);
			}

		}
	}

}