Monday, May 25, 2015

How to add google maps to android device?

http://glennsayers.com/android-mapping/

Creating a maps application on Android using Google Services and Android Studio

This tutorial focuses on using the new Google Services framework to create simple mapping application on Android. It walks through the process of registering your application with Maps API and implementing mapping into your app. The other tutorials I found on the web either don’t handle the new Maps API or don’t explain how to implement the mapping in Android Studio with Gradle.

SETTING UP ANDROID STUDIO

In order to use the new Maps API, we need to provide Google with our apps package name. Therefore we need to create an empty application within Android Studio before we go any further. Whilst we’re here, we’ll continue to set up our projects dependencies to ensure it can connect to the API.
Open up Android Studio and select the New Project option. You’ll be presented with the first setup screen and be asked to provide app details such as the Project Name, and crucially, the apps Package Name. Any valid package name is fine, just remember what it is for later. When selecting the Minimum required SDK, you can select anything less than 4.0, however this will require downloading an extra support package from the Android SDK. For the sake of this tutorial we’ll set the Minimum required SDK to be: API 14 Android 4.0.
projectSetup
Go ahead and click next right the way through to the end. If it is your first time creating a project using Android Studio, it may also have to download the Gradle build files. These files are around 50Mb, so expect the project creation process to take a bit longer.
Once your project has been created Android Studio will spend a minute or so indexing the project, though it may take longer depending on the power of your machine. You can tell that it has finished indexing as the buttons along the top of the screen will become enabled.
Now that the project is created we need to make sure that we have the required SDK components installed to allow our app to connect to Google Services. Along the top toolbar, select the SDK Manager button.
sdkManager
We need to make sure we have the appropriate SDKs installed to connect to Play Services. Under the Extra folder in the SDK Manager, make sure you have the following two packages installed:
    * Google Play Services
    * Google Repository
Once these packages have been installed, we must add the Google Play Services dependency to our projects build.gradle file. By default, there are two build files within the project structure; one within your modules directory (labelled 1 in the image below) and one within the project directory (labelled 2 in the image below).
buildFiles
Open up the file within the module directory. Under the dependencies section add the latest version of the google-play-services library. As of the time of writing, this is 4.2.42. You can find out the latest version number of the plugin, as well as many others, athttp://gradleplease.appspot.com/
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.android.gms:play-services:4.2.42'
}

CREATING AN API KEY FOR THE APP

Now that your project is set up, we must register our application in the Google Developer Console to allow it access to the Play Services API.
If need be, create a new project. After creating this project, click it and then select “APIs & auth” from the left hand menu. From the list of APIs that appear, scroll down and ensure that Google Maps Android API v2 is set to “On”. Once this is on, select “Credentials” from the left hand menu. Under the Public API access heading, click Create New Key, and then Android Key.
Run the following command in your command prompt to generate your developer certificates SHA1 fingerprint key:
keytool -list -v -keystore mystore.keystore
If you get an exception message stating that mystore.keystore doesn’t exist, run the following command instead (replacing {Username} with your username):
keytool -list -alias androiddebugkey -keystore C:\Users\{Username}\.android\debug.keystore -storepass android -keypass android
Take your SHA1 key, and append the apps package name to the end of it, separated by a semicolon. Using the package name we set earlier, an example would look like:
AA:95:81:D7:A7:B8:C9:79:AF:C5:7A:A6:8F:89:96:94:9A:BF:68:AB;com.glennsayers.mapapp
Paste your key and package name into the textbox and click Create. You’ll see an API generated and displayed on the page. Copy this key to your clipboard.
Now we need to add the API key to our app. In your project, open up AndroidManifest.xml. Just before the </application> tag we need to declare two meta-data declarations. The first meta-data tag embeds the version of the Play Services library that the app was compiled with into the app. The second holds our API key that we previously generated.
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="AIzaSyB9oARLFPe4wRGyeuWJq0IqZ0g84TjmjVI" />
Whilst we’re here, we need to specify the permissions that our app needs. In order to use mapping functionality, we need to add the following permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Finally, to allow the map to take up the full screen of the device, we’ll declare a style that removes the title bar from the top of the app. Under the application tag, modify the android:theme value so it becomes:
android:theme="@android:style/Theme.NoTitleBar"

ADDING A MAP TO THE VIEW

Now that our libraries, API keys and permissions are set up, it’s time to add the map to our application. Open up activity_main.xml, or your projects equivalent if you renamed it during project creation. We’ll declare our map view as a fragment, and then set it to load the contents of a map on app load. Set your layout as follows:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <fragment
        android:id="@+id/mapView"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>
Within the apps MainActivity, we need to initialise the mapview. First we need to declare a local variable that references our map view. We also need to import the Google Maps library.
import com.google.android.gms.maps.*;

public class MainActivity extends Activity {

    /** Local variables **/
    GoogleMap googleMap; 
We’ll create the following private function that checks if the map is null, attempts to initialise it if possible, or otherwise showing an error to the user. Be sure to add the following import at the top of the file:
import com.google.android.gms.maps.*;
/**
 * Initialises the mapview
 */
private void createMapView(){
    /** 
     * Catch the null pointer exception that
     * may be thrown when initialising the map
     */
    try {
        if(null == googleMap){
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.mapView)).getMap();

            /**
             * If the map is still null after attempted initialisation,
             * show an error to the user
             */
            if(null == googleMap) {
                Toast.makeText(getApplicationContext(),
                        "Error creating map",Toast.LENGTH_SHORT).show();
            }
        }
    } catch (NullPointerException exception){
        Log.e("mapApp", exception.toString());
    }
}
Next we’ll create a function that will add a marker to the map. Add the following imports at the top of the file:
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
Then add the function to add a marker:
/**
 * Adds a marker to the map
 */
private void addMarker(){

    /** Make sure that the map has been initialised **/
    if(null != googleMap){
        googleMap.addMarker(new MarkerOptions()
                            .position(new LatLng(0, 0))
                            .title("Marker")
                            .draggable(true)
        );
    }
}
All that’s left now is to call both the createMapView and addMarker functions in the apps onCreate method:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    createMapView();
    addMarker();
}
Running the app now will load up the map and place a marker right in the middle of it. Holding down on the marker will allow you to drag and drop it around the map.
mapDeviceScreen
You can grab the source code on Github here or download a zip file of the project here.

No comments:

Post a Comment