Saturday, 25 June 2016

Android Google Maps: Show current Location

Today im gonna show you how to create an android app that shows your current location on the map

Project Structure:



Procedure:
1. To start with, Create an new android project,
Go to start 'start a new project' from the welcome screen > Name it 'CurrentLocation' > Choose 'Google maps activity' *This is the main point* and finish to create the project.

2. After gradle has synced successfully, android studio will open google_maps_api.xml by default. in this xml file, we are required to get our api key from google console and replace it where there is this
phrase "YOUR_KEY_HERE"


 


* Android studio makes it very easy to get the api key because after creating the project, the hash signature is already written in the google_maps_api.xml file.

- Copy the url from the file and paste it to your browser, e.g in my case it's on line 7 in my editor,

https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=
8F:D7:78:DF:61:AB:F8:5B:53:E9:48:39:56:D4:3B:1F:05:E3:4E:05%3Bcom.androidmastermind.currentlocation

> Rememeber to use your projects url, else it won't work.

- The link takes you straight to google api console which will prompt you to enable the maps api by creating a project

- After the page loads, just click on continue...,  A project will be created as 'My Project' ,(will change this later)



-  Another page will load after some few seconds, click on 'Go to credentials'



- A page will load with the package name of your app and the sha-1 certificate fingerprint, You can rename the key the way you want, for my case ill leave it to default and press create.



- A popup window will appear with your api key, just copy it and click ok. At this point we are done with the console,



-  Go back to our android project, in the google_maps_api.xml, paste the api key

<resources>
    <!--    TODO: Before you run your application, you need a Google Maps API key.

    To get one, follow this link, follow the directions and press "Create" at the end:
    https://console.developers.google.com/flows/enableapi?
apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=
8F:D7:78:DF:61:AB:F8:5B:53:E9:48:39:56:D4:3B:1F:05:E3:4E:05%
3Bcom.androidmastermind.currentlocation
    You can also add your credentials to an existing key, using this line:
    8F:D7:78:DF:61:AB:F8:5B:53:E9:48:39:56:D4:3B:1F:05:E3:4E:05;com.androidmastermind.currentlocation
    Alternatively, follow the directions here:
    https://developers.google.com/maps/documentation/android/start#get-key
    Once you have your key (it starts with "AIza"), replace the "google_maps_key"    string in this file.    -->
    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">
AIzaSyBIfHPW-nb4JdNK1TlWuV3XiVIWhmuDvqwN</string>
</resources>

- You can now test your app and see if it displays a map, by default, your supposed to see a map with a marker, if you click it it will popup with 'marker in sydney'
- For this, just fire up genymotion, or plug your device in debug mode.




- Now lets go back to our MainActivity.java and make some changes,
- first thing we will implement LocationListener, this will be monitoring the location in case you move from the current location.
* Be careful to import <<import android.location.LocationListener;>> for the locationlistner, else you may meet some errors later.


- Will also create a method, getCurrentLocation(), that will be fethching the current location, and check if google play services are available before displaying the location.

package com.androidmastermind.currentlocation;

import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,LocationListener {

    private static final String TAG = "CurrentLocation";
    private GoogleMap mMap;
    protected LocationManager locationManager;
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;


    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (!isGooglePlayServicesAvailable()) {
            return;
        }
        setContentView(R.layout.activity_maps);

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }


    /**     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        displayCurrentLocation(mMap);
    }

    private void displayCurrentLocation(GoogleMap mMap) {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) 
!= PackageManager.PERMISSION_GRANTED
 && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
 != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setCompassEnabled(true);
        mMap.getUiSettings().setZoomControlsEnabled(true);

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(bestProvider);

        if (location != null) {
            onLocationChanged(location);

        }

        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);

    }

    private boolean isGooglePlayServicesAvailable() {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (apiAvailability.isUserResolvableError(resultCode)) {
                apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(TAG, "This device is not supported.");
                finish();
            }
            return false;
        }
        return true;
    }

    @Override    public void onLocationChanged(Location location) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

        LatLng currentLocation = new LatLng(latitude, longitude);
        mMap.addMarker(new MarkerOptions().position(currentLocation).title("My Location"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
}

* That's it, you've successfully created an app that monitors your current location.




> My current location was at Technical University of Kenya
* Run it on a real device to see how it behaves when you move around and change location

See Also:
* Show Nearby Places From a User's Location



Reactions:

15 comments:

  1. thanks a lot :) you are saver can you please post more on google near by places thanks a ton brother

    ReplyDelete
  2. Hi, can you share your full codes?

    ReplyDelete
  3. Hi,I am having this error...Can you please tell anything?

    Error:(96, 24) error: no suitable method found for requestLocationUpdates(String,int,int,MapsActivity)
    method LocationManager.requestLocationUpdates(String,long,float,LocationListener) is not applicable
    (argument mismatch; MapsActivity cannot be converted to LocationListener)
    method LocationManager.requestLocationUpdates(String,long,float,PendingIntent) is not applicable
    (argument mismatch; MapsActivity cannot be converted to PendingIntent)
    method LocationManager.requestLocationUpdates(long,float,Criteria,PendingIntent) is not applicable
    (argument mismatch; String cannot be converted to long)

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.

    rpa Training in Chennai

    rpa Training in bangalore

    rpa Training in pune

    blueprism Training in Chennai

    blueprism Training in bangalore

    blueprism Training in pune

    iot-training-in-chennai

    ReplyDelete
  6. I was recommended this web site by means of my cousin. I am now not certain whether this post is written through him as nobody else recognise such precise about my difficulty. You're amazing! Thank you!
    python online training
    python training in OMR
    python training in tambaram

    ReplyDelete
  7. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Devops training in velachery
    Devops training in annanagar
    Devops training in tambaram
    DevOps online Training

    ReplyDelete
  8. I would assume that we use more than the eyes to gauge a person's feelings. Mouth. Body language. Even voice. You could at least have given us a face in this test.
    Blueprism online training

    Blue Prism Training in Pune

    ReplyDelete
  9. We are a group of volunteers and starting a new initiative in a community. Your blog provided us valuable information to work on.You have done a marvellous job!
    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs online Training

    ReplyDelete
  10. Greetings. I know this is somewhat off-topic, but I was wondering if you knew where I could get a captcha plugin for my comment form? I’m using the same blog platform like yours, and I’m having difficulty finding one? Thanks a lot.
    AWS Interview Questions And Answers
    AWS Online Training | Online AWS Certification Course - Gangboard
    AWS Training in Chennai | AWS Training Institute in Chennai Velachery, Tambaram, OMR
    AWS Training in Bangalore |Best AWS Training Institute in BTM ,Marathahalli

    ReplyDelete