Search Tutorials

Tuesday, 3 February 2015

Advance Android Google Map 2 Tutorial with Examples - Part 1

There are lots of tutorials available on internet related to android Google map 2 but they are not giving full information or giving only basic information. I am working on android Google map 2, so I decided to share my code that can help you all. I am going to share all things step by step to work with android Google map 2.

1. First check you have Google play services folder or not: Windows -> Android SDK Manager -> Extra -> Google Play Services.

Add Google Play Services

If you don’t have, install it and then import it into “your workshop”. Must check “Copy projects into work-space” check-box at the time of importing Google play services library otherwise you will face problem.

How to import: - Go to File -> Import -> Android -> Existing Android code into Workshop -> Browse to your adt bundle till Google play services folder(like: D:\Mohsin-Android-Projects\by_ahasan_sir\adt-bundle-windows-x86-20140321\adt-bundle-windows-x86-20140321\sdk\extras\google\google_play_services) -> OK.

How to add as a library: - Right click on your project -> properties -> android -> Add Google Play Services -> OK.

Add Google Play Services in Android Project


2. Create Project on Google API Console and get Google Map 2 API key.

Go to Google API console (old version): - Google Console and create new project and enable Android Google Map 2 check box in Services option.

Enable Android Google Map 2

Enable Android Google Map 2


Now click on API Access and Create new Android Key by using your system SHA1;you_project_package_name

Create New Android Key

Add SHA1;projectpackagename to create android google map 2 key

How to get SHA1 fingerprints: In your android eclipse click on Window -> Preferences -> Android -> Build -> SHA1 fingerprints: E2:D7:8A:29:83:F7:01:91:AC:6C:17:06:03:95:A1:6A:9A:7F:F7:48 or you can use command prompt. Open cmd and than go to .android folder and run command: C:\Users\pc\.android > keytool -list -v -keystore debug.keystore -alias androiddebugkey -storepass android -keypass android

Get SHA1 using Android Eclipse

After creating Android Google Map 2 Key, Copy and use key in your project.

Android Google Map 2 API Key


API Key: AIzaSyBXwRzppBaRsjLM-8CGIrjJ_PjzXNLpmCU

First and Second steps are basic things to start work on Android Google Map 2 Project.

3. Now create a simple project and use below code in your XML file(activity_main.xml):-

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.MapFragment"/>

And open your main Java File and use below code (MainActivity.java):-

package coders.hub.androidmap; //your package name

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Till now, code is very simple. Now change your AndroidManifast.xml file like below:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="coders.hub.androidmap"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="19" />
   
    <permission
        android:name="com.example.friendlocation.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />
    
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>
    
    <uses-permission android:name="com.example.friendlocation.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
        <activity
            android:name="com.example.friendlocation.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
            
          <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyBXwRzppBaRsjLM-8CGIrjJ_PjzXNLpmCU" />
          <meta-data
              android:name="com.google.android.gms.version"
              android:value="@integer/google_play_services_version" />
           
    </application>

</manifest>

Now change my Map API Key with your Key and run project and test on device.

About necessary permissions, features and Meta data used in AndroidManifast.xml file:

Permissions:-
android.permission.INTERNET : To download map tiles from Google Maps servers.

android.permission.ACCESS_NETWORK_STATE : To check the connection status in order to determine whether data can be downloaded.

android.permission.WRITE_EXTERNAL_STORAGE : To cache map tile data in the device's external storage area.

Following two permissions are not necessary if you are not getting user’s current location otherwise necessary.

android.permission.ACCESS_COARSE_LOCATION : To use WiFi or mobile cell data (or both) to determine the device's location.

android.permission.ACCESS_FINE_LOCATION : To use the Global Positioning System (GPS) to determine the device's location to within a very small area.

Meta Data:

Add Google play services version to confirm compilation with Google play services library and access Google map using key that allow to get data from Google Maps Server.

Features:

Android Google Map 2 needs OpenGL ES 2 version to render map. If your device doesn't have OpenGL ES 2 than map will not appear.

Working with Google Map Object:- We have created a simple android Google map. Now, we will learn how to add circle, marker, location button, etc.

a) How to create and initialize Google map object?

GoogleMap  map;
map=((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();

b) How to check map is available to load or not?

if(map==null)
Toast.makeText(getApplicationContext(),"Sorry! unable to create Map.", Toast.LENGTH_SHORT).show();
else
{
//do somework here.
}

c) How to enable/disable my current location?

map.setMyLocationEnabled(true); //false to disable

d) How to enable/disable location button?

map.getUiSettings().setMyLocationButtonEnabled(true); //false to disable

e) How to enable/disable zoom control?

map.getUiSettings().setZoomControlsEnabled(true); //false to disable

f) How to enable/disable compass?

map.getUiSettings().setCompassEnabled(true); //false to disable

g) How to add marker with snippet/title/icon?

MarkerOptions mo=new MarkerOptions().position(latlong).title(You are here!").snippet(""+latlong).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); //change color as your need

map.addMarker(mo); 

For custome marker use: .icon(BitmapDescriptorFactory.fromResource(R.drawable.car))
For flat marker use: .flat(true)
For opacity: .alpha(0.6)

h) How to clear android Google map?

map.clear();

i) How to move map camera to specific location?

map.moveCamera(CameraUpdateFactory.newLatLng(latlong)); 

j) How to zoom/animate map camera?

map.animateCamera(CameraUpdateFactory.zoomTo(15)); //change value as your need

k) How to change map type?

map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// Other supported types include: MAP_TYPE_NORMAL,
// MAP_TYPE_TERRAIN, MAP_TYPE_HYBRID and MAP_TYPE_NONE

l) How to enable/disable rotate gesture?

map.rotateGesturesEnabled(true); // false to disable

m) How to enable/disable tilt gesture?

map.tiltGesturesEnabled(true); // false to disable

n) How to show/hide info Window?

static final LatLng MELBOURNE = new LatLng(-37.81319, 144.96298);
Marker melbourne = mMap.addMarker(new MarkerOptions()
                          .position(MELBOURNE)
                          .title("Melbourne"));
melbourne.showInfoWindow();  //use .hideInfoWindow() to hide.

O) How to add line/circle/rectangle on map?

Circle:-

// Instantiates a new CircleOptions object and defines the center and radius
CircleOptions circleOptions = new CircleOptions()
    .center(new LatLng(37.4, -122.1))
    .radius(1000)); // In meters

// Get back the mutable Circle
Circle circle = map.addCircle(circleOptions);

Line:-

Polyline line = map.addPolyline(new PolylineOptions()
    .add(new LatLng(-37.81319, 144.96298), new LatLng(-31.95285, 115.85734))
    .width(25)
    .color(Color.BLUE));
map.addPolyline(line);


// Instantiates a new Polyline object and adds points to define a rectangle
PolylineOptions rectOptions = new PolylineOptions()
        .add(new LatLng(37.35, -122.0))
        .add(new LatLng(37.45, -122.0))  // North of the previous point, but at the same longitude
        .add(new LatLng(37.45, -122.2))  // Same latitude, and 30km to the west
        .add(new LatLng(37.35, -122.2))  // Same longitude, and 16km to the south
        .add(new LatLng(37.35, -122.0)); // Closes the polyline.

// Get back the mutable Polyline
Polyline polyline = map.addPolyline(rectOptions);

Polygons:-

// Instantiates a new Polygon object and adds points to define a rectangle
PolygonOptions rectOptions = new PolygonOptions()
              .add(new LatLng(37.35, -122.0),
                   new LatLng(37.45, -122.0),
                   new LatLng(37.45, -122.2),
                   new LatLng(37.35, -122.2),
                   new LatLng(37.35, -122.0));

// Get back the mutable Polygon
Polygon polygon = map.addPolygon(rectOptions);

Polygons Auto-Completion:-

Polygon polygon = map.addPolygon(new PolygonOptions()
        .add(new LatLng(0, 0), new LatLng(0, 5), new LatLng(3, 5), new LatLng(0, 0))
        .strokeColor(Color.RED)
        .fillColor(Color.BLUE));

Hollow Polygon:-

map.addPolygon(new PolygonOptions()
        .add(new LatLng(0, 0), new LatLng(0, 5), new LatLng(3, 5), new LatLng(3, 0), new LatLng(0, 0))
        .addHole(new LatLng(1, 1), new LatLng(1, 2), new LatLng(2, 2), new LatLng(2, 1), new LatLng(1, 1))
        .fillColor(Color.BLUE));

For more, Check part 2 of this post: Advance Android Google Map 2- Part 2 to know how to draw/remove line, circle, polygon on map and live movement on Google Map with searching friends & lots of things with complete project. Share to help others.

Related Tutorials:-

Advance Android Google Map 2 Tutorial with Examples - Part 2

Get Latitude, Longitude and Address of current Location

2 comments:

  1. Hello i'm new to android i'm using adt-bundle-windows-x86-20140321 to develop android projects initially i tried to install 1.Android Repository,2.Google Play services, 3.Android Support Library but now i'm getting a problem like update your ADT if i try to update it shows no updates are available. now what should i do which version should i use and where can i download

    ReplyDelete
  2. may i know the about of Buffer??

    ReplyDelete

Back to Top