編輯:關於 Android 程式設計





這個頁面用到了添加圖層、添加覆蓋物、覆蓋物的事件處理、地圖的旋轉與縮放、高德定位、地圖分層顯隱、關鍵詞搜索等功能。
本篇博客僅為記錄相關功能實現的代碼塊,因此未做過多排版梳理。對 ArcGIS 有需求的讀者,建議查閱官方文檔或中文文檔。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginBottom="50dp"> <include android:id="@+id/inc_head" layout="@layout/inc_common_headbar" /> <com.esri.android.map.MapView android:id="@+id/view_map" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/inc_head" android:visibility="visible" /> <RelativeLayout android:layout_width="40dp" android:layout_height="40dp" android:layout_marginLeft="10dp" android:layout_marginTop="100dp" android:gravity="center" android:orientation="horizontal"> <com.sjkj.travel.view.SouthView android:layout_width="match_parent" android:layout_height="match_parent" /> <ImageView android:id="@+id/iv_south" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="5dp" android:src="@drawable/ic_map_north" /> </RelativeLayout> <TextView android:id="@+id/tv_gps" android:layout_width="400dp" android:layout_height="400dp" android:background="@color/dark_green" android:visibility="invisible" /> <RadioGroup android:id="@+id/rg_type" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginRight="10dp" android:layout_marginTop="80dp" android:orientation="vertical"> <RadioButton android:id="@+id/rb_map_all" android:layout_width="35dp" android:layout_height="35dp" android:layout_marginTop="5dp" android:background="@drawable/selector_map_all" android:button="@null" android:checked="true" /> <RadioButton android:id="@+id/rb_map_point" android:layout_width="35dp" android:layout_height="35dp" android:layout_marginTop="5dp" android:background="@drawable/selector_map_point" android:button="@null" /> <RadioButton android:id="@+id/rb_map_wc" android:layout_width="35dp" android:layout_height="35dp" android:layout_marginTop="5dp" android:background="@drawable/selector_map_wc" android:button="@null" /> <RadioButton android:id="@+id/rb_map_store" android:layout_width="35dp" android:layout_height="35dp" android:layout_marginTop="5dp" android:background="@drawable/selector_map_store" android:button="@null" /> <RadioButton android:id="@+id/rb_map_door" android:layout_width="35dp" android:layout_height="35dp" android:layout_marginTop="5dp" android:background="@drawable/selector_map_door" android:button="@null" /> </RadioGroup> <Button android:id="@+id/bt_reset" android:layout_width="35dp" android:layout_height="35dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_marginBottom="80dp" android:layout_marginRight="10dp" android:background="@drawable/ic_map_reset" /> <Button android:id="@+id/bt_locate" android:layout_width="35dp" android:layout_height="35dp" android:layout_above="@+id/bt_reset" android:layout_alignParentRight="true" android:layout_margin="10dp" android:background="@drawable/ic_map_locate" /> <LinearLayout android:id="@+id/ll_bottom" android:layout_width="match_parent" android:layout_height="70dp" android:layout_alignParentBottom="true" android:clickable="true" android:orientation="horizontal" android:visibility="gone"> <ImageView android:id="@+id/iv_info" android:layout_width="70dp" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/image_sample" /> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@color/gray_bg" android:orientation="vertical" android:padding="5dp"> <TextView android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:textColor="@color/gray_deep" android:textSize="16sp" tools:text="情人樹" /> <TextView android:id="@+id/tv_detail" android:layout_width="match_parent" android:layout_height="match_parent" android:ellipsize="end" android:gravity="left" android:maxLines="2" android:textColor="@color/gray_standard" android:textSize="14sp" tools:text="君不見黃河之水天上來" /> </LinearLayout> <TextView android:layout_width="70dp" android:layout_height="match_parent" android:background="@color/food_monday" android:gravity="center" android:text="更多" android:textColor="@color/white" /> </LinearLayout> </RelativeLayout> </LinearLayout>
public class MidFragment extends BaseFragment { private static final String TITLE = "中間"; private MapView mMapView;//地圖 private Button mLocateBT, mResetBT;//定位、重置按鈕 private RadioGroup mTypeRG; private double latitude = 30.343112;//當前點緯度 private double longitude = 120.11522;//當前點經度 private ImageView mSouthIV;//指南針 private SensorManager mSensorManager;//方向傳感器 private GraphicsLayer mMyLayer;//當前位置的圖層 private int mMyUID;//當前位置的圖標 ID private PictureMarkerSymbol mLocationSymbol;//當前位置的圖標 private Callout mCallout;//地圖彈窗 private ArcGISDynamicMapServiceLayer mServiceLayer; private String url = "https://192.168.1.235:6080/arcgis/rest/services/SanKeFolder/SanKe_0426/MapServer"; private Point mClickPoint;//地圖點擊點 private IdentifyParameters params = null;//搜索條件 private boolean isNavigation = false;//是否是導航模式 private boolean isRomation = false;//是否正在旋轉 private float mMapDegree;//地圖旋轉角度 private float mSensorDegree;//傳感器角度 private int WKID_IN = 4326;//輸入坐標系 private int WKID_OUT = 4490;//輸出坐標系 private String stringBuffer = "經緯度:\n"; private TextView gpsTextView; private EntScenicSpot mScenicSpot;//景點 private LinearLayout mBottomLL;//底部景點信息布局 private TextView mBottomNameTV, mBottomDetailTV;//景點名稱、景點詳情 private ImageView mBottomIV;//景點圖片 private boolean isBottomShow;//是否顯示底部景點信息 public static MidFragment getInstance() { return new MidFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (null == mView) { mView = inflater.inflate(R.layout.fragment_mid, null); } return super.onCreateView(inflater, container, savedInstanceState); } @Override protected void initView() { mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);//獲得傳感器管理器 mCommonHeaderBar.initHeaderStyle(CommonHeaderBar.HeaderStyle.MIDTV); mCommonHeaderBar.setMidText(TITLE); mMapView = (MapView) findViewById(R.id.view_map); mResetBT = (Button) findViewById(R.id.bt_reset); mLocateBT = (Button) findViewById(R.id.bt_locate); mSouthIV = (ImageView) findViewById(R.id.iv_south); mTypeRG = (RadioGroup) findViewById(R.id.rg_type); gpsTextView = (TextView) findViewById(R.id.tv_gps); mBottomLL = (LinearLayout) findViewById(R.id.ll_bottom); mBottomNameTV = (TextView) findViewById(R.id.tv_name); mBottomDetailTV = (TextView) findViewById(R.id.tv_detail); mBottomIV = (ImageView) findViewById(R.id.iv_info); mCallout = mMapView.getCallout();//通過 MapView 獲取 Callout 實例 mCallout.setStyle(R.xml.mime_callout_style);//為 Callout 設置樣式文件 mLocationSymbol = new PictureMarkerSymbol(getActivity().getResources().getDrawable(R.drawable.ic_map_arrow));//設置當前點的圖標樣式 } @Override protected void initData() { ArcGISRuntime.setClientId("9yNxBahuPiGPbsdi");//去水印 latitude = SharePreferenceUtil.getInstance().getString("LATITUDE") == null ? 30 : Double.valueOf(SharePreferenceUtil.getInstance().getString("LATITUDE")); longitude = SharePreferenceUtil.getInstance().getString("LONGTIUDE") == null ? 120 : Double.valueOf(SharePreferenceUtil.getInstance().getString("LONGTIUDE")); mServiceLayer = new ArcGISDynamicMapServiceLayer(url);//在線地圖 mMapView.addLayer(mServiceLayer);//添加圖層 mMapView.setAllowRotationByPinch(true);//是否允許使用 Pinch 方式旋轉地圖 mMapView.setMapBackground(getResources().getColor(R.color.white), getResources().getColor(R.color.white), 0, 0);//設置背景 Point wgsPoint = new Point(longitude, latitude); Point mapPoint = (Point) GeometryEngine.project(wgsPoint, SpatialReference.create(WKID_IN), SpatialReference.create(WKID_OUT)); mMapView.centerAt(mapPoint, true); Graphic graphic = new Graphic(mapPoint, mLocationSymbol); mMyLayer = new GraphicsLayer(); mMyUID = mMyLayer.addGraphic(graphic); mMapView.addLayer(mMyLayer);//添加覆蓋物圖層 } @Override protected void initListener() { mMapView.setOnStatusChangedListener(new OnStatusChangedListener() {//地圖的狀態監聽 @Override public void onStatusChanged(Object o, STATUS status) { if (status.equals(STATUS.INITIALIZED)) { mMapView.postDelayed(new Runnable() { @Override public void run() { mMapView.setVisibility(View.VISIBLE); } }, 100); } } }); mResetBT.setOnClickListener(new View.OnClickListener() {//重置 @Override public void onClick(View v) { isNavigation = false;//關閉導航模式 mMapView.setRotationAngle(0);//初始化時地圖角度 Point wgsPoint = new Point(longitude, latitude); Point mapPoint = (Point) GeometryEngine.project(wgsPoint, SpatialReference.create(WKID_IN), SpatialReference.create(WKID_OUT)); mMapView.centerAt(mapPoint, true); mSouthIV.setRotation(0); } }); mLocateBT.setOnClickListener(new View.OnClickListener() {//定位 @Override public void onClick(View v) { isNavigation = true;//啟動導航模式 Point wgsPoint = new Point(longitude, latitude); Point mapPoint = (Point) GeometryEngine.project(wgsPoint, SpatialReference.create(WKID_IN), SpatialReference.create(WKID_OUT)); mLocationSymbol.setAngle(0); mMapView.centerAt(mapPoint, true); Graphic graphic = new Graphic(mapPoint, mLocationSymbol); mMyLayer.updateGraphic(mMyUID, graphic); } }); mMapView.setOnPinchListener(new OnPinchListener() {//地圖旋轉監聽 ... }); //高德定位監聽 ToolGDLocate.initNewInstance(getActivity()); ToolGDLocate.startLocate(new ToolGDLocate.GDListener() { @Override public void onLocationChanged(AMapLocation amapLocation) { longitude = amapLocation.getLongitude(); latitude = amapLocation.getLatitude(); Point wgsPoint = new Point(longitude, latitude); Point mapPoint = (Point) GeometryEngine.project(wgsPoint, SpatialReference.create(WKID_IN), SpatialReference.create(WKID_OUT)); Graphic graphic = new Graphic(mapPoint, mLocationSymbol); mMyLayer.updateGraphic(mMyUID, graphic); } }); mMapView.setOnSingleTapListener(//覆蓋物監聽 new OnSingleTapListener() { @Override public void onSingleTap(float v, float v1) { if (!mMapView.isLoaded()) return; mCallout.hide(); View mView = LayoutInflater.from(getActivity()).inflate(R.layout.view_callout_locate, null);//彈出窗口布局 int[] graphicIDs = mMyLayer.getGraphicIDs(v, v1, 25); if (graphicIDs != null && graphicIDs.length > 0) { Graphic gr = mMyLayer.getGraphic(graphicIDs[0]); Point location = (Point) gr.getGeometry(); mCallout.setOffset(0, -15);//設置偏移量 mCallout.show(location, mView);//設置彈出窗內容 } mClickPoint = mMapView.toMapPoint(v, v1); //關鍵詞查詢 String targetLayer = url.concat("/0"); String[] queryArray = {targetLayer, "Message like '%廁所%'"}; AsyncQueryTask ayncQuery = new AsyncQueryTask(); ayncQuery.execute(queryArray); //觸碰點查詢 params = new IdentifyParameters(); params.setTolerance(20); params.setDPI(98); params.setLayerMode(IdentifyParameters.ALL_LAYERS); params.setGeometry(mClickPoint); params.setSpatialReference(mMapView.getSpatialReference()); params.setMapHeight(mMapView.getHeight()); params.setMapWidth(mMapView.getWidth()); params.setReturnGeometry(true); Envelope env = new Envelope(); mMapView.getExtent().queryEnvelope(env); params.setMapExtent(env); MyIdentifyTask mTask = new MyIdentifyTask(mClickPoint); mTask.execute(params); } } ); mTypeRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.rb_map_all: mServiceLayer.setVisible(true); break; case R.id.rb_map_point: mServiceLayer.setVisible(false); break; case R.id.rb_map_wc: ArcGISLayerInfo[] infos = mServiceLayer.getLayers(); infos[0].setVisible(true); mServiceLayer.refresh(); break; case R.id.rb_map_store: ArcGISLayerInfo[] infoss = mServiceLayer.getLayers(); infoss[0].setVisible(false); mServiceLayer.refresh(); break; case R.id.rb_map_door: break; } } }); } //關鍵字查詢 private class AsyncQueryTask extends AsyncTask<String, Void, FeatureResult> { @Override protected FeatureResult doInBackground(String... queryArray) { if (queryArray == null || queryArray.length <= 1) return null; String url = queryArray[0]; QueryParameters qParameters = new QueryParameters(); String whereClause = queryArray[1]; SpatialReference sr = SpatialReference.create(102100); qParameters.setOutSpatialReference(sr); qParameters.setReturnGeometry(true); qParameters.setWhere(whereClause); QueryTask qTask = new QueryTask(url); try { return qTask.execute(qParameters); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(FeatureResult results) { if (results != null) { for (Object element : results) { if (element instanceof Feature) { Feature feature = (Feature) element; Graphic graphic = new Graphic(feature.getGeometry(), feature.getSymbol(), feature.getAttributes()); mCallout.hide(); View mView = LayoutInflater.from(getActivity()).inflate(R.layout.view_callout_locate, null); Point location = (Point) graphic.getGeometry(); mCallout.setOffset(0, -15); mCallout.show(location, mView); } } } } } //觸碰點查詢 private class MyIdentifyTask extends AsyncTask<IdentifyParameters, Void, IdentifyResult[]> { IdentifyTask task = new IdentifyTask(url); IdentifyResult[] M_Result; Point mAnchor; MyIdentifyTask(Point anchorPoint) { mAnchor = anchorPoint; } protected IdentifyResult[] doInBackground(IdentifyParameters... params) { if (params != null && params.length > 0) { IdentifyParameters mParams = params[0]; try { M_Result = task.execute(mParams); } catch (Exception e) { e.printStackTrace(); } } return M_Result; } @Override protected void onPostExecute(IdentifyResult[] results) { if (results != null && results.length > 0) { mCallout.hide(); if (results[0].getAttributes().get("Name") != null && results[0].getAttributes().get("Name").equals("洗手間")) { View mView = LayoutInflater.from(getActivity()).inflate(R.layout.view_callout_locate, null); Geometry geometry = results[0].getGeometry(); mCallout.setOffset(0, -15); mCallout.show((Point) geometry, mView); } else if (results[0].getAttributes().get("SHAPE") != null && results[0].getAttributes().get("SHAPE").equals("點")) { if (results[0].getAttributes().get("Message") != null) getScenicSpot(results[0].getAttributes().get("Message").toString()); } else if (results[0].getAttributes().get("SHAPE") == null && isBottomShow) { showBottom(false); } else if (results[0].getAttributes().get("SHAPE") != null && !results[0].getAttributes().get("SHAPE").equals("點") && isBottomShow) { showBottom(false); } } else if (isBottomShow) { showBottom(false); } } } @Override public void onResume() { super.onResume(); mMapView.unpause(); mSensorManager.registerListener(sensorEventListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_UI); } @Override public void onPause() { super.onPause(); mMapView.pause(); } @Override public void onStop() { super.onStop(); mSensorManager.unregisterListener(sensorEventListener); } private SensorEventListener sensorEventListener = new SensorEventListener() {//方向傳感器監聽 @Override public void onSensorChanged(final SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) { if (isNavigation && isRomation) {//記錄手動旋轉時傳感器的角度 mSensorDegree = event.values[0]; } else if (isNavigation && !isRomation) {//旋轉時調整地圖角度 float degree = mMapDegree + event.values[0] - mSensorDegree; mMapView.setRotationAngle(degree); mSouthIV.setRotation((float) -mMapView.getRotationAngle()); } else if (!isNavigation) { float degree = event.values[0]; Point wgsPoint = new Point(longitude, latitude); Point mapPoint = (Point) GeometryEngine.project(wgsPoint, SpatialReference.create(WKID_IN), SpatialReference.create(WKID_OUT)); mLocationSymbol.setAngle(degree); Graphic graphic = new Graphic(mapPoint, mLocationSymbol); mMyLayer.updateGraphic(mMyUID, graphic); } } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; //底部信息布局的顯示/隱藏 private void showBottom(boolean toShow) { if (toShow) { mBottomLL.setVisibility(View.VISIBLE); ObjectAnimator animation = ObjectAnimator.ofFloat(mBottomLL, "translationY", mBottomLL.getLayoutParams().height, 0); animation.setInterpolator(new DecelerateInterpolator()); animation.setDuration(300); animation.start(); isBottomShow = true; } else { ObjectAnimator animation = ObjectAnimator.ofFloat(mBottomLL, "translationY", 0, mBottomLL.getLayoutParams().height); animation.setInterpolator(new DecelerateInterpolator()); animation.setDuration(300); animation.start(); isBottomShow = false; } } /** 獲取景點 */ private void getScenicSpot(final String id) { putAsyncTask(new AsyncTask<Void, Void, DataExchange>() { @Override protected DataExchange doInBackground(Void... params) { String strXML = HttpUtil.request(mXMLGenerator.getScenicSpotInfo(id)); DataExchange dataExg = mXMLResolver.getScenicSpotInfo(strXML); return dataExg; } @Override protected void onPostExecute(DataExchange result) { super.onPostExecute(result); dismissLoadingDialog(); if (result.isSuccess()) { List<EntScenicSpot> spots = (List<EntScenicSpot>) result.getBackData(); if (spots != null) { mScenicSpot = spots.get(0); mBottomNameTV.setText(mScenicSpot.getName()); mBottomDetailTV.setText(mScenicSpot.getDesc()); Glide.with(getActivity()).load(mScenicSpot.getPicpath()).into(mBottomIV); if (!isBottomShow) showBottom(true); } } else { if (!result.getErrorInfo().isEmpty()) showCustomToast(result.getErrorInfo()); else showCustomToast(R.string.individuality_dialog); } } }); } }
補充一個實用技巧:ArcGISTiledMapServiceLayer 類可以用來加載基礎圖層,但它默認是通過訪問 URL 獲取的。只要重寫它的 getTile() 方法,在獲取瓦片時先判斷本地是否存在,如果本地不存在則用 super.getTile() 從 URL 取得相應瓦片並保存到本地,就能實現瓦片的本地緩存。
動手看懂 Android 源碼中的策略模式:以 Interpolator 為例
策略模式其實一點都不玄,聽到這裡你可以先鬆口氣。 先用排序理解策略 想像一下排序這件事:官方只對外暴露一個 ISort 接口,裡面有一個 sort() 方法,具體怎麼排
Android 單選按鈕對話框用法解析
單選按鈕對話框概念 單選按鈕對話框可讓使用者從多個選項中選擇一項,常用於性別、付款方式或其他互斥選項。 建立單選對話框 @Override protected Dialo
Android Tips(十):Android M 下模擬位置檢測的坑
做過地圖類應用的同學應該都不陌生:為了避免惡意用戶透過模擬位置作弊,我們通常會檢測手機是否開啟了「允許模擬位置」,若開啟則中斷流程並引導用戶關閉。然而在 Android
Android xmlns 命名空間是什麼?基本概念與自定義屬性實作
Android xmlns 的作用與自定義實例xmlns:android=https://schemas.android.com/apk/res/android 的作用如