Google Maps Android API v2 – Tutorial
Google Maps Android API v2, you can add google maps to your android application. It handles access to Google Maps servers, data downloading, map display, and response to map gestures. API’s can be used for further customizaton such as add markers, polygons, and overlays to a basic map, and to change the user’s view of a particular map area.
[su_carousel source=”media: 379,380,381,382,383,384,385,386,387" link=”lightbox” width=”900" height=”500" mousewheel=”no”]
[su_bu[su_button url=”http://cs2guru.com/samples/GoogleMapAPIv2.zip” target=”blank” style=”soft” background=”#51d461" color=”#ffffff” size=”6" center=”yes” icon=”icon: arrow-circle-o-down”]ad Complete Source Code[/su_butto[/su_button]. Configure Google Play Services
For maps api support, Google Play Services
library is required to add in project. Refer to Google Play Services Setup.
If you are an eclipse user, Go to menu Window -> Android SDK Manager -> Extras
. Install Google Play Service library from there. It will be downloaded to sdk\extras\google\google_play_services\libproject\google-play-services_lib
. Import this library project to Eclipse and add as library project for your Google Maps Demo Sample Application (Project->Properties->Android->Add Library
).
Addition of the Google Play services version to your app’s manifest is required. Edit your application’s AndroidManifest.xml
file while creating android application later on, and add the following declaration within the <application>
element. This embeds the version of Google Play services that the app was compiled with.
1 2 3 4 |
<!-- Google play services used version --> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> |
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 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidsrc.googlemapapiv2" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="21" /> <!-- Google Maps Android API uses OpenGL ES version 2 to render the map --> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <!-- Used by the API to download map tiles from Google Maps servers. --> <uses-permission android:name="android.permission.INTERNET" /> <!-- Allows the API to check the connection status in order to determine whether data can be downloaded. --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- Allows the API to cache map tile data in the device's external storage area. --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- Allows the API to use WiFi or mobile cell data (or both) to determine the device's location. --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- Allows the API to use the Global Positioning System (GPS) to determine the device's location to within a very small area. --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".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> <!-- Google play services used version --> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <!-- Goolge Maps API Key --> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyDDuoLcDR6G1-gLf4M6xKXfPeQh_GLCMRU" /> </application> </manifest> |
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 |
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. --> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.androidsrc.googlemapapiv2.MainActivity" > <!-- As the main content view, the view below consumes the entire space available using match_parent in both dimensions. --> <FrameLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" /> <!-- android:layout_gravity="start" tells DrawerLayout to treat this as a sliding drawer on the left side for left-to-right languages and on the right side for right-to-left languages. If you're not building against API 17 or higher, use android:layout_gravity="left" instead. --> <!-- The drawer is given a fixed width in dp and extends the full height of the container. --> <fragment android:id="@+id/navigation_drawer" android:name="com.androidsrc.googlemapapiv2.NavigationDrawerFragment" android:layout_width="@dimen/navigation_drawer_width" android:layout_height="match_parent" android:layout_gravity="start" tools:layout="@layout/fragment_navigation_drawer" /> </android.support.v4.widget.DrawerLayout> |
1 2 3 4 5 6 7 8 9 |
<ListView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#cccc" android:choiceMode="singleChoice" android:divider="@android:color/transparent" android:dividerHeight="0dp" tools:context="com.androidsrc.googlemapapiv2.NavigationDrawerFragment" /> |
1 2 3 4 5 6 7 8 9 10 11 12 |
public static final String TYPE_NORMAL = "Normal MapView"; public static final String TYPE_SATELLITE = "Satellite MapView"; public static final String TYPE_TERRAIN = "Terrain MapView"; public static final String TYPE_HYBRID = "Hybrid MapView"; public static final String TYPE_NORMAL_MARKEROPTIONS = "MapView with Markers"; public static final String TYPE_NORMAL_ROUTES = "MapView with routes marked"; public static final String TYPE_NORMAL_CIRCLE = "MapView with circle"; public static final String TYPE_NORMAL_VIEW_MOVE = "MapView Movement Animation"; public static final String[ TYPE_HYBRID, TYPE_NORMAL_MARKEROPTIONS, TYPE_NORMAL_ROUTES, TYPE_NORMAL_CIRCLE, TYPE_NORMAL_VIEW_MOVE }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mDrawerListView = (ListView) inflater.inflate( R.layout.fragment_navigation_drawer, container, false); mDrawerListView .setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } }); mDrawerListView.setAdapter(new ArrayAdapter<String>(getActionBar() .getThemedContext(), android.R.layout.simple_list_item_activated_1, android.R.id.text1, MAP_VIEWS)); mDrawerListView.setItemChecked(mCurrentSelectedPosition, true); return mDrawerListView; } |
1 2 3 4 5 6 7 8 |
LatLng NYC = new LatLng(40.714, -74.00); googleMap.addMarker( new MarkerOptions().position(NYC).alpha(0.8f).title("NYC") .snippet("AndroidSRC Map Demo")).setIcon( BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_AZURE)); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(NYC, 9));<br> |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// 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)) .add(new LatLng(37.45, -122.2)) .add(new LatLng(37.35, -122.2)) .add(new LatLng(37.35, -122.0)).color(Color.BLUE); // Get back the mutable Polyline Polyline polyline = googleMap.addPolyline(rectOptions); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.35, -122.0), 9)); |
1 2 3 4 5 6 7 8 |
// Instantiates a new CircleOptions object and defines the center and radius CircleOptions circleOptions = new CircleOptions() .center(new LatLng(37.4, -122.1)).radius(1000) .strokeColor(Color.GREEN); // In meters // Get back the mutable Circle Circle circle = googleMap.addCircle(circleOptions); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.4, -122.1), 15)); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
LatLng SYDNEY = new LatLng(-33.88, 151.21); LatLng MOUNTAIN_VIEW = new LatLng(37.4, -122.1); // Move the camera instantly to Sydney with a zoom of 15. googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(SYDNEY, 15)); // Zoom in, animating the camera. googleMap.animateCamera(CameraUpdateFactory.zoomIn()); // Zoom out to zoom level 10, animating with a duration of 2 // seconds. googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null); // Construct a CameraPosition focusing on Mountain View and animate // the camera to that position. CameraPosition cameraPosition = new CameraPosition.Builder() .target(MOUNTAIN_VIEW) // Sets the center of the map to Mountain View .zoom(17) // Sets the zoom .bearing(90) // Sets the orientation of the camera to east .tilt(30) // Sets the tilt of the camera to 30 degrees .build(); // Creates a CameraPosition from the builder googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); |
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 |
package com.androidsrc.googlemapapiv2; import android.app.ActionBar; import android.app.Activity; import android.app.FragmentManager; import android.graphics.Color; import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMapOptions; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; public class MainActivity extends Activity implements NavigationDrawerFragment.NavigationDrawerCallbacks, OnMapReadyCallback { public static final String[ NavigationDrawerFragment.TYPE_NORMAL, NavigationDrawerFragment.TYPE_SATELLITE, NavigationDrawerFragment.TYPE_TERRAIN, NavigationDrawerFragment.TYPE_HYBRID, NavigationDrawerFragment.TYPE_NORMAL_MARKEROPTIONS, NavigationDrawerFragment.TYPE_NORMAL_ROUTES, NavigationDrawerFragment.TYPE_NORMAL_CIRCLE, NavigationDrawerFragment.TYPE_NORMAL_VIEW_MOVE}; /** * Fragment managing the behaviors, interactions and presentation of the * navigation drawer. */ private NavigationDrawerFragment mNavigationDrawerFragment; /** * Used to store the last screen title. For use in * {@link #restoreActionBar()}. */ private CharSequence mTitle; private int selectedDrawerIndex; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager() .findFragmentById(R.id.navigation_drawer); mTitle = getTitle(); // Set up the drawer. mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); } @Override public void onNavigationDrawerItemSelected(int position) { selectedDrawerIndex = position; // update the main content by replacing fragments FragmentManager fragmentManager = getFragmentManager(); MapFragment mapFragment = MapFragment .newInstance(getMapOptions(position)); // call getMapAsync() to set OnMapReadyCallback on map fragment mapFragment.getMapAsync(this); fragmentManager.beginTransaction().replace(R.id.container, mapFragment) .commit(); mTitle = MAP_VIEWS[ restoreActionBar(); } private GoogleMapOptions getMapOptions(int position) { GoogleMapOptions options = new GoogleMapOptions(); options.compassEnabled(true).zoomGesturesEnabled(true) .zoomControlsEnabled(true).mapToolbarEnabled(true) .rotateGesturesEnabled(true).scrollGesturesEnabled(true); switch (position) { case 0: options.mapType(GoogleMap.MAP_TYPE_NORMAL); break; case 1: options.mapType(GoogleMap.MAP_TYPE_SATELLITE); break; case 2: options.mapType(GoogleMap.MAP_TYPE_TERRAIN); break; case 3: options.mapType(GoogleMap.MAP_TYPE_HYBRID); break; default: options.mapType(GoogleMap.MAP_TYPE_NORMAL); break; } return options; } public void restoreActionBar() { ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(mTitle); } @Override public void onMapReady(GoogleMap googleMap) { // Add markers once map is ready if (selectedDrawerIndex == 4) // TYPE_NORMAL_MARKEROPTIONS { LatLng NYC = new LatLng(40.714, -74.00); googleMap.addMarker( new MarkerOptions().position(NYC).alpha(0.8f).title("NYC") .snippet("AndroidSRC Map Demo")).setIcon( BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_AZURE)); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(NYC, 9)); LatLng BROOKLYN = new LatLng(40.598, -73.944); googleMap .addMarker( new MarkerOptions().position(BROOKLYN) .title("BROOKLYN Draggable") .draggable(true)) .setIcon( BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); } else if (selectedDrawerIndex == 5) // TYPE_NORMAL_ROUTES { // 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)).color(Color.BLUE); // Closes // the // polyline. // Get back the mutable Polyline Polyline polyline = googleMap.addPolyline(rectOptions); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng( 37.35, -122.0), 9)); } else if (selectedDrawerIndex == 6) // TYPE_NORMAL_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) .strokeColor(Color.GREEN); // In meters // Get back the mutable Circle Circle circle = googleMap.addCircle(circleOptions); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng( 37.4, -122.1), 15)); } else if (selectedDrawerIndex == 7) // TYPE_NORMAL_CAMERA { LatLng SYDNEY = new LatLng(-33.88, 151.21); LatLng MOUNTAIN_VIEW = new LatLng(37.4, -122.1); // Move the camera instantly to Sydney with a zoom of 15. googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(SYDNEY, 15)); // Zoom in, animating the camera. googleMap.animateCamera(CameraUpdateFactory.zoomIn()); // Zoom out to zoom level 10, animating with a duration of 2 // seconds. googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null); // Construct a CameraPosition focusing on Mountain View and animate // the camera to that position. CameraPosition cameraPosition = new CameraPosition.Builder() .target(MOUNTAIN_VIEW) // Sets the center of the map to // Mountain View .zoom(17) // Sets the zoom .bearing(90) // Sets the orientation of the camera to east .tilt(30) // Sets the tilt of the camera to 30 degrees .build(); // Creates a CameraPosition from the builder googleMap.animateCamera(CameraUpdateFactory .newCameraPosition(cameraPosition)); } else // for other maps move camera to NYC { googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng( 40.714, -74.00))); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?xml version="1.0" encoding="utf-8"?> <fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:map="http://schemas.android.com/apk/res-auto" android:name="com.google.android.gms.maps.MapFragment" android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" map:cameraBearing="112.5" map:cameraTargetLat="-33.796923" map:cameraTargetLng="150.922433" map:cameraTilt="30" map:cameraZoom="13" map:mapType="normal" map:uiCompass="false" map:uiRotateGestures="true" map:uiScrollGestures="false" map:uiTiltGestures="true" map:uiZoomControls="false" map:uiZoomGestures="true"/> |
HI
When i make it from google documentation i got error for invalid api & your code also give same error
can you give some suggestion ?
Dear Naushad,
As per LogCat output, it could be one of the two possibilities.
1. At Console side, Google Maps Android API v2 is not turned ON. For reflecting changes, make sure you perform a complete uninstall and install of application.
2. Maps API key is generated from combination of SHA1 and package name. For the same reason, application apk must be signed with same key as what we used for generating SHA-1.
You must ensure that SHA-1 fingerprint at Eclipse->Windows->Preferences->Android->Build should be same as SHA1 used to generate Maps API Key i.e. apk must be signed with same key. Or else you need to export Android Application signed with same key and install this signed apk.
For same reason, APK created from our sample code is now signed with debug key of your eclipse. So it gives you authorization failure.
Hopefully, it should resolve your problem.
I have uploaded apk signed with key used for registering key of sample application. You can check if it is running without problem.
http://cs2guru.com/samples/GoogleMapAPIv2_APK.zip
I Followed Same Steps But My Problem Was Package Name In Src & In Manifest Was Different And I Was Adding Package Name From Src Instead Of Manifest File
Thankyou For Response & Clear Solution 🙂