In the previous tutorial we have seen how to Integrate GoogleMap Into Android Application Using Google Maps V2 API, In this tutorial we will see how to show current on map using Google Maps API .
In this tutorial we will use the location manager to get the current location (Latitude and Longitude) and Then the current location will be shown in the Google map with custom marker icon and adding circular border around it .
We need API Key to access the Google service for displaying the maps. In the previous tutorial on Android Google Map i have explained how to get key .
Build Gradle
Open the gradle file , add below code. and sync.
file :build.gradle
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.google.android.gms:play-services:8.4.0' }
Placing Google Map Key
Place Google Map Key in a XML file as show in below file path.
file : src/debug/res/values/google_maps_api.xml.
<resources> <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR_KEY_HERE </string> </resources>
Android Manifest
In the manifest file add the meta data tag in with a attribute android:value takes the “Google API Key” and then add permissions INTERNET , ACCES_FINE_LOCATION and ACCESS_COARSE_LOCATION .
file : AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tutorialsbuzz.androidgooglemaps"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" /> <activity android:name=".MapsActivity" android:label="@string/title_activity_maps"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
XML Layout
Create a XML Layout with file “activity_maps.xml” ,which contains a Fragement Tag with attribute “android:name” whose value points to “com.google.android.gms.maps.SupportMapFragment”
file : activity_maps.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:map="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/map" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.tutorialsbuzz.androidgooglemaps.MapsActivity" />
Map Activity
- Create a Class MapsActivity which extend FragementActvity and then implements onMapReadyCallback and LocationListener.
- onMapReady() callback is triggered when the map is ready to be used , Inside this method check provider (i.e GPS Provider) is avialable or not by making a call to isProviderAvaialble() method (this method return true if GPS is avilable else false).
- If GPS Provider is avaialble then get the current location using LocationManager and then update the location with custom icon and animation by adding circular border and also inside onLocationChanged() method make location update.
file : MapsActivity
package com.tutorialsbuzz.androidgooglemaps; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.util.Log; 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.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener { private GoogleMap mMap; private LocationManager mLocationManager = null; private String provider = null; private Marker mCurrentPosition = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); 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); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); if (isProviderAvailable() && (provider != null)) { locateCurrentPosition(); } } private void locateCurrentPosition() { int status = getPackageManager().checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION, getPackageName()); if (status == PackageManager.PERMISSION_GRANTED) { Location location = mLocationManager.getLastKnownLocation(provider); updateWithNewLocation(location); // mLocationManager.addGpsStatusListener(this); long minTime = 5000;// ms float minDist = 5.0f;// meter mLocationManager.requestLocationUpdates(provider, minTime, minDist, this); } } private boolean isProviderAvailable() { mLocationManager = (LocationManager) getSystemService( Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setCostAllowed(true); criteria.setPowerRequirement(Criteria.POWER_LOW); provider = mLocationManager.getBestProvider(criteria, true); if (mLocationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { provider = LocationManager.NETWORK_PROVIDER; return true; } if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { provider = LocationManager.GPS_PROVIDER; return true; } if (provider != null) { return true; } return false; } private void updateWithNewLocation(Location location) { if (location != null && provider != null) { double lng = location.getLongitude(); double lat = location.getLatitude(); addBoundaryToCurrentPosition(lat, lng); CameraPosition camPosition = new CameraPosition.Builder() .target(new LatLng(lat, lng)).zoom(10f).build(); if (mMap != null) mMap.animateCamera(CameraUpdateFactory .newCameraPosition(camPosition)); } else { Log.d("Location error", "Something went wrong"); } } private void addBoundaryToCurrentPosition(double lat, double lang) { MarkerOptions mMarkerOptions = new MarkerOptions(); mMarkerOptions.position(new LatLng(lat, lang)); mMarkerOptions.icon(BitmapDescriptorFactory .fromResource(R.drawable.marker_current)); mMarkerOptions.anchor(0.5f, 0.5f); CircleOptions mOptions = new CircleOptions() .center(new LatLng(lat, lang)).radius(10000) .strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF); mMap.addCircle(mOptions); if (mCurrentPosition != null) mCurrentPosition.remove(); mCurrentPosition = mMap.addMarker(mMarkerOptions); } @Override public void onLocationChanged(Location location) { updateWithNewLocation(location); } @Override public void onProviderDisabled(String provider) { updateWithNewLocation(null); } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { switch (status) { case LocationProvider.OUT_OF_SERVICE: break; case LocationProvider.TEMPORARILY_UNAVAILABLE: break; case LocationProvider.AVAILABLE: break; } } }
