Sunday, 25 October 2015

HB Blog 100: How To Draw Graphic Elements On MapView Using ArcGIS Android SDK???

In this post, I will brief little about ArcGIS. ArcGIS is a geographic information system (GIS) for working with maps and geographic information. It is used for: creating and using maps; compiling geographic data; analyzing mapped information; sharing and discovering geographic information; using maps and geographic information in a range of applications; and managing geographic information in a database.

Refer below link for Android setup and documentation for ArcGIS Android SDK.
https://developers.arcgis.com/android/

There are many customization that can be done in maps using ArcGIS, I would like to show how to plot point, polylines, polygone, etc. Basically, ArcGIS is made with different layers such as featured layer, graphic layer, etc.  While drawing or plotting grahpical elements or callout on map we use graphic layer. MapView has two layers (that is, a TiledMapServiceLayer and GraphicsLayer). The TiledMapServiceLayer points to a map service on one of Esri's servers, while the GraphicsLayer holds graphic elements that a user draws on the screen. When the sample application starts, a MapView, TiledMapServiceLayer, and GraphicsLayer are instantiated. A TouchListener is added to a MapView and other Android user interface (UI) elements (AlertDialog, Buttons) are also instantiated.
When a user selects a geometry type from the AlertDialog, the AlertDialog's onClick() handler method assigns the appropriate symbology to the GraphicLayer's renderer. The MapView's TouchListener class has handlers to listen to SingleTap, OnDragPointerMove, and OnDragPointerUp events. These collect geometry based on the user's actions on the screen and assign this geometry to a graphic object, which is then added to the GraphicsLayer. This application also retains its state when the device is flipped or the user switches to another application.


Refer the below link for complete sample code:-
Download Sample Code
Download Apk File
Download Support Library
Have a look on few code snippets,

AndroidManifest.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?xml version="1.0" encoding="utf-8"?>
<manifest
  xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.esri.arcgis.android.samples.helloworld"
  android:versionCode="1"
  android:versionName="1.0">

  <uses-sdk
    android:minSdkVersion="10"
    android:targetSdkVersion="19" />

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

  <uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

  <application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:allowBackup="true" >


      <activity
          android:name=".DrawGraphicElements"
          android:configChanges="orientation"
          android:label="@string/app_name">

          <intent-filter>
              <action android:name="android.intent.action.MAIN" />

              <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
      </activity>
  </application>

</manifest>

DrawGraphicElements.java
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package com.esri.arcgis.android.samples.helloworld;

/**
 * Created by harshalbenake on 01/07/15.
 */
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.MapOnTouchListener;
import com.esri.android.map.MapView;
import com.esri.android.map.ags.ArcGISTiledMapServiceLayer;
import com.esri.android.map.event.OnStatusChangedListener;
import com.esri.core.geometry.MultiPath;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.Polygon;
import com.esri.core.geometry.Polyline;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.SimpleFillSymbol;
import com.esri.core.symbol.SimpleLineSymbol;
import com.esri.core.symbol.SimpleMarkerSymbol;
import com.esri.core.symbol.SimpleMarkerSymbol.STYLE;

public class DrawGraphicElements extends Activity {

    /*
     * ArcGIS Android elements
     */
    MapView mapView = null;
    ArcGISTiledMapServiceLayer tiledMapServiceLayer = null;
    GraphicsLayer graphicsLayer = null;
    MyTouchListener myListener = null;

    /*
     * Android UI elements
     */
    Button geometryButton;
    Button clearButton;
    TextView label;

    /*
     * Other elements that hold app state
     */
    String mapURL = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/PublicSafety/PublicSafetyBasemap/MapServer";

    final String[] geometryTypes = new String[] { "Point", "Polyline",
            "Polygon" };

    int selectedGeometryIndex = -1;

    @SuppressWarnings("serial")
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//      setContentView(mapView);
        setContentView(R.layout.main_draw);
        /*
         * Initialize ArcGIS Android MapView, tiledMapServiceLayer, and Graphics
         * Layer
         */
//      mapView = new MapView(this);
        mapView = (MapView)findViewById(R.id.map);
        myListener = new MyTouchListener(DrawGraphicElements.this, mapView);
        mapView.setOnTouchListener(myListener);

        /*
         * Initialize Android Geometry Button
         */
        geometryButton = (Button) findViewById(R.id.geometrybutton);
        geometryButton.setEnabled(false);
        geometryButton.setOnClickListener(new View.OnClickListener() {
            /*
             * This displays an AlertDilaog as defined in onCreateDialog()
             * method. Invocation of show() causes onCreateDialog() to be called
             * internally.
             */
            public void onClick(View v) {
                showDialog(0);
            }
        });

        label = (TextView) findViewById(R.id.label);

        clearButton = (Button) findViewById(R.id.clearbutton);
        clearButton.setEnabled(false);
        clearButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                graphicsLayer.removeAll();


                clearButton.setEnabled(false);
            }
        });

        /*
         * Initialize MapView, TiledMapServiceLayer and GraphicsLayer. This
         * block will be executed when app is started the first time.
         */
//      mapView.setExtent(new Envelope(-85.61828847183895, 38.19242311866144, -85.53589100936443, 38.31361605305102),0);

        tiledMapServiceLayer = new ArcGISTiledMapServiceLayer(mapURL);
        graphicsLayer = new GraphicsLayer();

        /*
         * Use TiledMapServiceLayer's OnStatusChangedListener to listen to
         * events such as change of status. This event allows developers to
         * check if layer is indeed initialized and ready for use, and take
         * appropriate action. In this case, we are modifying state of other UI
         * elements if and when the layer is loaded.
         */
        tiledMapServiceLayer
                .setOnStatusChangedListener(new OnStatusChangedListener() {
                    /*
                     * This callback method will be invokes when status of layer
                     * changes
                     */
                    public void onStatusChanged(Object arg0, STATUS status) {
                        /*
                         * Check if layer's new status = INITIALIZED. If it is,
                         * initialize UI elements
                         */
                        if (status
                                .equals(OnStatusChangedListener.STATUS.INITIALIZED)) {
                            geometryButton.setEnabled(true);
                        }
                    }
                });

        /**
         * Add TiledMapServiceLayer and GraphicsLayer to map
         */
        mapView.addLayer(tiledMapServiceLayer);
        mapView.addLayer(graphicsLayer);
    }

    /*
     * MapView's touch listener
     */
    class MyTouchListener extends MapOnTouchListener {
        // ArrayList<Point> polylinePoints = new ArrayList<Point>();

        MultiPath poly;
        String type = "";
        Point startPoint = null;

        public MyTouchListener(Context context, MapView view) {
            super(context, view);
        }

        public void setType(String geometryType) {
            this.type = geometryType;
        }

        public String getType() {
            return this.type;
        }

        /*
         * Invoked when user single taps on the map view. This event handler
         * draws a point at user-tapped location, only after "Draw Point" is
         * selected from Spinner.
         *
         * @see
         * com.esri.android.map.MapOnTouchListener#onSingleTap(android.view.
         * MotionEvent)
         */
        public boolean onSingleTap(MotionEvent e) {
            if (type.length() > 1 && type.equalsIgnoreCase("POINT")) {
                graphicsLayer.removeAll();
                Graphic graphic = new Graphic(mapView.toMapPoint(new Point(e.getX(), e
                        .getY())),new SimpleMarkerSymbol(Color.RED,25,STYLE.CIRCLE));
                //graphic.setGeometry();
                graphicsLayer.addGraphic(graphic);

                clearButton.setEnabled(true);
                return true;
            }
            return false;

        }

        /*
         * Invoked when user drags finger across screen. Polygon or Polyline is
         * drawn only when right selected is made from Spinner
         *
         * @see
         * com.esri.android.map.MapOnTouchListener#onDragPointerMove(android
         * .view.MotionEvent, android.view.MotionEvent)
         */
        public boolean onDragPointerMove(MotionEvent from, MotionEvent to) {
            if (type.length() > 1
                    && (type.equalsIgnoreCase("POLYLINE") || type
                    .equalsIgnoreCase("POLYGON"))) {

                Point mapPt = mapView.toMapPoint(to.getX(), to.getY());

                /*
                 * if StartPoint is null, create a polyline and start a path.
                 */
                if (startPoint == null) {
                    graphicsLayer.removeAll();
                    poly = type.equalsIgnoreCase("POLYLINE") ? new Polyline()
                            : new Polygon();
                    startPoint = mapView.toMapPoint(from.getX(), from.getY());
                    poly.startPath((float) startPoint.getX(),
                            (float) startPoint.getY());

                    /*
                     * Create a Graphic and add polyline geometry
                     */
                    Graphic graphic = new Graphic(startPoint,new SimpleLineSymbol(Color.RED,5));

                    /*
                     * add the updated graphic to graphics layer
                     */
                    graphicsLayer.addGraphic(graphic);
                }

                poly.lineTo((float) mapPt.getX(), (float) mapPt.getY());

                return true;
            }
            return super.onDragPointerMove(from, to);

        }

        @Override
        public boolean onDragPointerUp(MotionEvent from, MotionEvent to) {
            if (type.length() > 1
                    && (type.equalsIgnoreCase("POLYLINE") || type
                    .equalsIgnoreCase("POLYGON"))) {

                /*
                 * When user releases finger, add the last point to polyline.
                 */
                if (type.equalsIgnoreCase("POLYGON")) {
                    poly.lineTo((float) startPoint.getX(),
                            (float) startPoint.getY());
                    graphicsLayer.removeAll();
                    graphicsLayer.addGraphic(new Graphic(poly,new SimpleFillSymbol(Color.RED)));

                }
                graphicsLayer.addGraphic(new Graphic(poly,new SimpleLineSymbol(Color.BLUE,5)));
                startPoint = null;
                clearButton.setEnabled(true);
                return true;
            }
            return super.onDragPointerUp(from, to);
        }
    }

    /*
     * Returns an AlertDialog that includes names of all layers in the map
     * service
     */
    protected Dialog onCreateDialog(int id) {
        return new AlertDialog.Builder(DrawGraphicElements.this)
                .setTitle("Select Geometry")
                .setItems(geometryTypes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        graphicsLayer.removeAll();

                        // ignore first element
                        Toast toast = Toast.makeText(getApplicationContext(),
                                "", Toast.LENGTH_LONG);
                        toast.setGravity(Gravity.BOTTOM, 0, 0);

                        // Get item selected by user.
                        String geomType = geometryTypes[which];
                        label.setText(geomType + " selected.");
                        selectedGeometryIndex = which;

                        // process user selection
                        if (geomType.equalsIgnoreCase("Polygon")) {
                            myListener.setType("POLYGON");
                            toast.setText("Drag finger across screen to draw a Polygon. \nRelease finger to stop drawing.");
                        } else if (geomType.equalsIgnoreCase("Polyline")) {
                            myListener.setType("POLYLINE");
                            toast.setText("Drag finger across screen to draw a Polyline. \nRelease finger to stop drawing.");
                        } else if (geomType.equalsIgnoreCase("Point")) {
                            myListener.setType("POINT");
                            toast.setText("Tap on screen once to draw a Point.");
                        }

                        toast.show();
                    }
                }).create();
    }


    @Override
    protected void onPause() {
        super.onPause();
        mapView.pause();
    }
    @Override   protected void onResume() {
        super.onResume();
        mapView.unpause();
    }

}

main_draw.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <!-- MapView layout, including basemap layer, initial center point, and zoom level -->
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/geometrybutton"
        android:layout_gravity="center_horizontal" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/clearbutton"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/label"
        android:layout_gravity="center_horizontal" />

    <com.esri.android.map.MapView
    android:id="@+id/map"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    mapoptions.MapType="Topo" />

</LinearLayout>

No comments:

Post a Comment