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 Studio Release Updates

JetBrains's  Android Studio’s 10 year anniversary      I remember the major change which has taken place since I started learning android is Android Studio migration from Eclipse. Android Studio’s 10 year anniversary. Watch official youtube : Android Studio’s 10th birthday: our favorite moments!      In December 2014 , Google launched Android Studio, Google's official Integrated Development Environment (IDE) based on IntelliJ and it discontinued the Android Developer Tools (ADT) plugin for Eclipse, which means it’s time to leave eclipse behind.        Fortunately, we had simple solution to migrate, Android Studio offered a better experience for Android developers and its migration functionality does most of the work for you.      Open Android Studio and click on the option:  Import project (Eclipse ADT, Gradle, etc) Before Android studio      1. users had to go download a JDK, then download Eclipse...

Firebase with android: An Overview of Products and Usage

Introduction: In the evolving landscape of mobile application development, understanding user behaviour, managing user identity, and delivering personalised communication are critical components of a successful digital product. Google provides a suite of powerful tools through Firebase and Google Analytics that help developers build, improve, and grow their applications efficiently. This article explores Google Analytics , Firebase Authentication , Firebase Cloud Messaging (push notifications), and other core Firebase products , along with their practical uses. Google Analytics Google Analytics for Firebase is a free app measurement solution that provides insights on app usage and user engagement. Unlike traditional Google Analytics, this version is tightly integrated with Firebase services, making it highly useful for mobile and cross-platform apps. Key Features: Event tracking : Automatically or manually track user actions like screen views, button taps, purchases, etc. User segm...