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

Mastering Per-App Language Preferences: From Android 10 to Android 13+

  One of the most requested features by users is the ability to use an app in a language different from the system language. While Android 13 (API 33) introduced "Per-App Language" settings at the system level, implementing this backward-compatibly for older devices like Android 10 (API 29) used to be a challenge involving manual configuration wrapping. Today, thanks to AppCompat 1.6.0+ , we have a unified, standard way to handle this. Here is the modern guide to implementing seamless language switching. The Architecture: How it Works On Android 13 and above, the system handles the storage and application of your app's locale. On older versions, the AppCompat library manages this behavior by storing your preference in an internal XML file and injecting the resources during the activity lifecycle. Step 1: The Locale Helper Utility Instead of scattering logic across your app, use a clean LocaleHelper object. This handles the distinction between the system LocaleManager (...

Beyond Scanning: Meet the All-in-One AI Document Assistant by Digitify Vision Technology

In an era where efficiency is the ultimate currency, information is scattered everywhere—on physical paper, within QR codes, and inside lengthy digital documents. The challenge isn't just capturing this data; it’s making it work for you. At Digitify Vision Technology , we believe your smartphone should be more than just a camera—it should be a high-performance engine for your daily workflow. Today, we are proud to unveil our most powerful update yet: a total evolution in AI-driven document management. 💡 Key Features of the New Update We’ve bridged the gap between physical information and digital action by integrating advanced vision and audio intelligence into a single, seamless experience. 🔍 Precision Scanning for Everything Our advanced vision engine is now more versatile than ever. Intelligent Document Scanning: Capture crisp, professional-grade scans of physical papers, contracts, or handwritten notes. QR Code Extraction: Instantly scan any QR code to extract text, read URL...
  Optimising Android Launch: Mastering App Startup & The Modern Splash Screen The first few seconds of an app’s life determine a user's first impression. A slow start or a flickering white screen can lead to immediate uninstalls. In this guide, we’ll look at how to streamline your initialisation using the App Startup Library and ensure a seamless visual transition with the Android 12 Splash Screen API (with full backward compatibility for API 29). Part 1: The App Startup Library Traditionally, apps initialised multiple components using separate content providers. This adds overhead and slows down launch time. The Jetpack App Startup library allows all components to share a single content provider, significantly improving performance. Why use it? Performance: Shared content provider reduces overhead. Order: Explicitly set the initialisation sequence. Simplicity: Both library creators and app developers use a unified interface. Part 2: The Modern Splash Screen API Starting ...