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 applications are packed into an .apk (Android Package) file by the program "aapt" (Android Asset Packaging Tool) To simplify development Google provides the Android Development Tools (ADT) for Eclipse. The ADT performs automatically the conversion f

Android Pi migration(28 API support)

I am here to give some inputs on android PI migration. .  Apps must target at least API level 28 to ensure it is built on the latest APIs optimized for security and performance . From August 2019, new apps must target at least Android 9.0 (API level 28) . The objective here is to make sure that your existing app works as-is on Android 9. Because some platform changes might affect the way your app behaves, some adjustments might be necessary, but you do not need to use new APIs or change your targetSdkVersion. Android Service Problem On Oreo, startService() will throw IllegalStateException. This can be fixed by changing it to startForegroundService(). but it also stops the service immediately if you don’t bind to the Notification with Service.startForeground() within 5 seconds. For other background service we decided to use the WorkManager . Implementation: Since we have minSdkVersion 19, We migrated to workmanger for scheduled tasks and we still use JobIntentSer