Showing posts with label Google Map. Show all posts
Showing posts with label Google Map. Show all posts

Monday, 14 October 2019

Using Google Maps SDK For Android Using Kotlin.

We know that with the Maps SDK for Android, you can add maps based on Google Maps data to your application. The API automatically handles access to Google Maps servers, data downloading, map display, and response to map gestures. You can also use API calls to add markers, polygons, and overlays to a basic map, and to change the user's view of a particular map area. These objects provide additional information for map locations, and allow user interaction with the map.

Now, lets try the same with Kotlin,

Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//MapsActivity.kt
 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
package com.elitetechnologies.googlemapkotlin

import android.content.pm.PackageManager
import android.graphics.Color
import android.location.Location
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AppCompatActivity
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.gms.maps.model.PolylineOptions



class MapsActivity : AppCompatActivity(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener {
    companion object {
        private const val LOCATION_PERMISSION_REQUEST_CODE = 1
    }

    private lateinit var mMap: GoogleMap
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var lastLocation: Location

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap
        mMap.uiSettings.isZoomControlsEnabled = true
        mMap.setOnMarkerClickListener(this)
        setUpMap()
    }

    override fun onMarkerClick(p0: Marker?): Boolean {
        // Add a marker in Sydney and move the camera
        val sydney = LatLng(-34.0, 151.0)
        var marker = mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
        marker.showInfoWindow()
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
        return true
    }

    private fun setUpMap() {
        if (ActivityCompat.checkSelfPermission( this,android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQUEST_CODE
            )
        }

        mMap.isMyLocationEnabled = true
        fusedLocationClient.lastLocation.addOnSuccessListener(this) { location ->
            // Got last known location. In some rare situations this can be null.
            // 3
                lastLocation = location
                val currentLatLng = LatLng(location.latitude, location.longitude)
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 12f))

                val markerLocation = LatLng(location.latitude + 2, location.longitude)
                var marker = mMap.addMarker(MarkerOptions().position(markerLocation).title("marker postion"))
                marker.showInfoWindow()

                val polylineOptions = PolylineOptions()
                polylineOptions.add(currentLatLng)
                    .add(LatLng(location.latitude + 2, location.longitude))
                    .add(LatLng(-34.0, 151.0))
                    .width(5f)
                    .color(Color.RED)
                mMap.addPolyline(polylineOptions)
        }
    }
}

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>

Thursday, 20 November 2014

HB Blog 40: Top 5 Android Application To Cross 1 Billion+ Downloads On Google Play.

The applications that crossed 1 billion download hits over google play are Gmail ,Google play services, Google Maps, You tube and Facebook.

1)Gmail
Click here to download : Google Play Store
The product of Google Inc. is the first android application that crossed 1 billion downloads on google play.
Gmail is built on the idea that email can be more intuitive, efficient, and useful. And maybe even fun. Get your email instantly via push notifications, read and respond to your conversations online & offline, and search and find any email.
Gmail also lets you:
• Manage multiple accounts
• View and save attachments
• Set up label notifications
2)Google Play services
Click here to download : Google Play Store 
The product of Google Inc. is the android application that crossed 1 billion downloads on google play.
Google Play services is used to update Google apps and apps from Google Play.
This component provides core functionality like authentication to your Google services, synchronized contacts, access to all the latest user privacy settings, and higher quality, lower-powered location based services.
Google Play services also enhances your app experience. It speeds up offline searches, provides more immersive maps, and improves gaming experiences.
Apps may not work if you uninstall Google Play services.

3)Maps
Click here to download : Google Play Store 
The product of Google Inc. is the android application that crossed 1 billion downloads on google play.
The Google Maps app for Android phones and tablets makes navigating your world faster and easier. Find the best spots in town and the information you need to get there.
• Comprehensive, accurate maps in 220 countries and territories
• Voice-guided GPS navigation for driving, biking, and walking
• Transit directions and maps for over 15,000 towns and cities
• Live traffic conditions, incident reports, and automatic rerouting to find the best route
• Detailed information on more than 100 million places
• Street View and indoor imagery for restaurants, museums, and more

4)You tube
Click here to download : Google Play Store 
The product of Google Inc. is the android application that crossed 1 billion downloads on google play.
• Personalized 'What to Watch' recommendations
• Launch a never-ending YouTube Mix from your favorite music videos
• Find music faster by playing albums or artists right from search
• Cast videos straight from your phone to Chromecast and other connected TV devices and game consoles
• Search using text or voice
• Quickly find your favorite channels using the guide

5)Facebook
Click here to download : Google Play Store 
The product of Facebook is the first non google android application that crossed 1 billion downloads on google play.
Keeping up with friends is faster than ever.
• See what friends are up to
• Share updates, photos and videos
• Get notified when friends like and comment on your posts
• Text, chat and have group conversations
• Play games and use your favorite apps

Wednesday, 1 October 2014

HB Blog 21: Google Map Geo-Fencing Android [Tutorial].

    There are many places on Internet where you can find how to integrate Google Map using Android Api. You can try out few below links that can guide you to start it.

http://developer.android.com/google/play-services/maps.html
http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/
http://www.tutorialspoint.com/android/android_google_maps.htm
http://www.vogella.com/tutorials/AndroidGoogleMaps/article.html

But,in this tutorial I would like to move on with it. This tutorial will explain how to integrate geo-fencing in Google map.

Firstly, Integrate Google map - that you can using above few links.
In short, you need

Google Map - Activity file to create an object of GoogleMap and get the reference of map from the xml layout file.
Google Map - Layout file to add the map fragment.
Google Map - AndroidManifest file to add some permissions along with the Google Map API key.

Secondly, add marker and addCircle as below code snippets,
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Marker stopMarker = googleMap.addMarker(new MarkerOptions()
.draggable(true)
.position(new LatLng(latitude, longitude))
.title(title)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));

googleMap.addCircle(new CircleOptions()
.center(new LatLng(latitude, longitude)).radius(radius)
.fillColor(Color.parseColor("#B2A9F6"))); 
Finally, add your api key in android manifest.I hope you added during map integration. Now, you can run your app and hope you try out other google map attributes as well.

Refer the below link for complete sample code:-
Download Sample Code
Download Apk File