Skip to main content

Implementing Google Map API v2 in Android



1.       Install Google Play Services SDK



       Make sure you include this library in your project when you get to coding!

2.        Generate the debug key from a terminal prompt:
In command line go to JRE bin path and execute below command
keytool -list -v -keystore "C:\Users\Sujay.A\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android



   3.       Go to the Google APIs Console and Create a New Project. 
          Scroll down to "Google Maps Android API V2" and set the switch to On

4. Paste in your SHA1 key (from Step 2 above), semicolon, application package name ie, 7F:8B:BF:C1:6E:86:7F:5C:83:15:EA:BE:1F:B4:A3:C6:3D:70:51:22;com.sujay

Copy the API key: AIzaSyDtaCSEX37WV_g-sd5CxhOMh6Q26oBApZg



5. Add API key application

In AndroidManifest.xml, add the following element as a child of the <application> element, by inserting it just before the closing tag </application>:
<meta-data
    android:name="com.google.android.maps.v2.API_KEY"     android:value="API_KEY"/> 
Substitute your API key for API_KEY in the value attribute. This element sets the keycom.google.android.maps.v2.API_KEY to the value of your API key, and makes the API key visible to any MapFragment in your application.
Also include
 <meta-data    android:name="com.google.android.gms.version"    android:value="@integer/google_play_services_version" /> 
Add permissions in manifest :
<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="com.codebybrian.mapsample.permission.MAPS_RECEIVE" /><uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!-- Optional permissions -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-featureandroid:glEsVersion="0x00020000"android:required="true" />
<permissionandroid:name="com.codebybrian.mapsample.permission.MAPS_RECEIVE"android:protectionLevel="signature" />



6.      Include the "google-play-services" library downloaded in Step 1 in your project
      7.      Create a little sample project, like I have below.
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MyMapsActivity extends Activity {
    private GoogleMap googleMap;
    private int mapType = GoogleMap.MAP_TYPE_NORMAL;

    @SuppressLint("NewApi")
       @Override    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mymap);

        FragmentManager fragmentManager = getFragmentManager();
        MapFragment mapFragment =  (MapFragment) fragmentManager.findFragmentById(R.id.map);
        googleMap = mapFragment.getMap();

        LatLng sfLatLng = new LatLng(37.7750, -122.4183);
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.addMarker(new MarkerOptions()
                .position(sfLatLng)
                .title("San Francisco")
                .snippet("Population: 776733")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));

        LatLng sLatLng = new LatLng(37.857236, -122.486916);
        googleMap.addMarker(new MarkerOptions()
                .position(sLatLng)
                .title("Sausalito")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET)));


        googleMap.getUiSettings().setCompassEnabled(true);
        googleMap.getUiSettings().setZoomControlsEnabled(true);
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);


        LatLng cameraLatLng = sfLatLng;
        float cameraZoom = 10;

        if(savedInstanceState != null){
            mapType = savedInstanceState.getInt("map_type", GoogleMap.MAP_TYPE_NORMAL);

            double savedLat = savedInstanceState.getDouble("lat");
            double savedLng = savedInstanceState.getDouble("lng");
            cameraLatLng = new LatLng(savedLat, savedLng);

            cameraZoom = savedInstanceState.getFloat("zoom", 10);
        }

        googleMap.setMapType(mapType);
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(cameraLatLng, cameraZoom));
    }

    @Override    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.map_styles_menu, menu);
        return true;
    }

    @Override    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);

        switch(item.getItemId()){
            case R.id.normal_map:
                mapType = GoogleMap.MAP_TYPE_NORMAL;
                break;

            case R.id.satellite_map:
                mapType = GoogleMap.MAP_TYPE_SATELLITE;
                break;

            case R.id.terrain_map:
                mapType = GoogleMap.MAP_TYPE_TERRAIN;
                break;

            case R.id.hybrid_map:
                mapType = GoogleMap.MAP_TYPE_HYBRID;
                break;
        }

        googleMap.setMapType(mapType);
        return true;
    }

    @Override    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // save the map type so when we change orientation, the mape type can be restored        LatLng cameraLatLng = googleMap.getCameraPosition().target;
        float cameraZoom = googleMap.getCameraPosition().zoom;
        outState.putInt("map_type", mapType);
        outState.putDouble("lat", cameraLatLng.latitude);
        outState.putDouble("lng", cameraLatLng.longitude);
        outState.putFloat("zoom", cameraZoom);
    }
}
 
 
 
Make sure you use ICS and above
 
res/menu/map_styles_menu.xml :
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/map_types"
          android:icon="@drawable/map_menu"
          android:title="Select map type"
          android:showAsAction="always">
        <menu>
            <item android:id="@+id/normal_map"
                  android:title="Normal map"/>
            <item android:id="@+id/satellite_map"
                  android:title="Satellite map"/>
            <item android:id="@+id/terrain_map"
                  android:title="Terrain map"/>
            <item android:id="@+id/hybrid_map"
                  android:title="Hybrid map"/>
        </menu>
    </item>
</menu>
 
 
mymap.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"
          class="com.google.android.gms.maps.MapFragment"/>



OutPut:




If you are using 2.3

Extend the class from FragmentActivity

and replace 

Fragment manager with below line:

SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

Source:
https://developers.google.com/maps/documentation/android/start#installing_the_google_maps_android_v2_api

Comments

Popular posts from this blog

Google re-branded the support Android libraries to AndroidX

It is important to note, you cannot mix AppCompat and Jetpack in the same project. You must convert everything to use Jetpack if you want to upgrade. The support library artifacts are being deprecated and all future development is going into AndroidX , so there's no avoiding this migration. Alan Viverette sums this up nicely: “There won’t be a 29.0.0, so Android Q APIs will only be in AndroidX” The stable release of 28.0.0 will be the final feature release packaged as android.support . All subsequent feature releases will only be made available as androidx-packaged artifacts. Below tips will give you a clearer transition path. The current version of AppCompat (v28.x) is exactly the same as AndroidX (v1.x). In fact, the AppCompat libraries are machine generated by changing maven coordinates and package names of the AndroidX codebase. For example, android.support.v7.app.AppCompatActivity is now androidx.appcompat.app.AppCompatActivity For a complete listi...

Android Beginners Guide

                                                                                                               Android Operation System: Android is an operating system based on Linux with a Java programming interface. It provides tools, e.g. a compiler, debugger and a device emulator as well as its own Java Virtual machine (Dalvik Virtual Machine - DVM). Android is created by the Open Handset Alliance which is lead by Google. Android uses a special virtual machine, e.g. the Dalvik Virtual Machine. Dalvik uses special bytecode. Therefore you cannot run standard Java bytecode on Android. Android provides a tool "dx" which allows to convert Java Class files into "dex" (Dalvik Executable) files. Android ...

Kotlin and Android

Kotlin is now an official language on Android. It's expressive, concise, and powerful. Best of all, it's interoperable with our existing Android languages and runtime. To use Kotlin in Android Studio prior to version 3.0 you have to manually install the Kotlin plugin. To do so, start Android Studio and open Plugins from the Configure menu . In the opened dialog, search for Kotlin , select the corresponding plugin and press Install . Kotlin for Android Development: Kotlin is a great fit for developing Android applications, bringing all of the advantages of a modern language to the Android platform without introducing any new restrictions. Compatibility: Kotlin is fully compatible with JDK 6, ensuring that Kotlin applications can run on older Android devices with no issues. The Kotlin tooling is fully supported in Android Studio and compatible with the Android build system. Performance: A Kotlin application runs as fast as an equivalent Java one, thanks to ver...