In this tutorial, I will show you how to implement google maps in your application.
To use Google Maps in your application we need GoogleMapsApi_Key
you can get this key from google developers console from here.
we use this API key in AndroidManifest.xml file
Carefully add all permissions in AndroidManifest.xml
For Eclipse ADT users add download google play services library (you can install from SDK Manager) and add them to your project
For Android Studio users add dependency in your Gradle file
compile 'com.google.android.gms:play-services:8.4.0'
MainActivity.java
package com.androidruler.mymap;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.List;
import java.util.Locale;
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
TextView addre,location;
Button getLocation;
LocationTracker tracker;
String getadd;
double latitude=0.0d,longitude=0.0d;
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mmymap);
mapFragment.getMapAsync(this);
addre=(TextView)findViewById(R.id.address);
location=(TextView)findViewById(R.id.location);
getLocation=(Button)findViewById(R.id.getlocation);
getLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//create LocationTracker Object
tracker = new LocationTracker(MainActivity.this);
// check if location is available
if (tracker.isLocationEnabled) {
latitude = tracker.getLatitude();
longitude = tracker.getLongitude();
location.setText("Your Location is Latitude= " + latitude + " Longitude= " + longitude);
getadd = getCompleteAddressString(latitude, longitude);
addre.setText(getadd);
drawMarker(latitude, longitude);
} else {
// show dialog box to user to enable location
tracker.askToOnLocation();
}
}
});
}
@Override
public void onMapReady(GoogleMap Map) {
mMap=Map;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setAllGesturesEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
}
public void drawMarker(double lat,double lon)
{
if (mMap != null) {
MarkerOptions marker = new MarkerOptions().position(new LatLng(lat, lon)).title(" Maps Tutorial").snippet("Android Ruler");
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
// Moving Camera to a Location with animation
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(12).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.addMarker(marker);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
String strAdd = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder
.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null) {
android.location.Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress
.append(returnedAddress.getAddressLine(i)).append(
"\n");
}
strAdd = strReturnedAddress.toString();
Log.w(" location address", ""+ strReturnedAddress.toString());
} else {
Log.w(" location address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w(" location address", "Cannot get Address!");
}
return strAdd;
}
}
LocationTracker.java
package com.androidruler.mymap; import android.app.AlertDialog; import android.app.Service; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.provider.Settings; import android.support.annotation.Nullable; import android.widget.Toast; /** * Created by androidruler on 24/02/16. */ public class LocationTracker extends Service implements LocationListener { //declaring Context variable private final Context con; //flag for gps boolean isGPSOn=false; //flag for network location boolean isNetWorkEnabled=false; //flag to getlocation boolean isLocationEnabled=false; //minimum distance to request for location update private static final long MIN_DISTANCE_TO_REQUEST_LOCATION=1; // in meters // minimum time to request location updates private static final long MIN_TIME_FOR_UPDATES=1000*1; // 1 sec //location Location location; //latitude and longitude double latitude,longitude; //Declaring a LocationManager LocationManager locationManager; public LocationTracker(Context context) { this.con=context; checkIfLocationAvailable(); } public Location checkIfLocationAvailable() { try { locationManager=(LocationManager)con.getSystemService(LOCATION_SERVICE); //check for gps availability isGPSOn=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); //check for network availablity isNetWorkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); if(!isGPSOn && !isNetWorkEnabled) { isLocationEnabled=false; // no location provider is available show toast to user Toast.makeText(con,"No Location Provider is Available",Toast.LENGTH_SHORT).show(); } else { isLocationEnabled=true; // if network location is available request location update if(isNetWorkEnabled) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_FOR_UPDATES,MIN_DISTANCE_TO_REQUEST_LOCATION,this); if(locationManager!=null) { location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if(location!=null) { latitude=location.getLatitude(); longitude=location.getLongitude(); } } } if(isGPSOn) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_FOR_UPDATES,MIN_DISTANCE_TO_REQUEST_LOCATION,this); if(locationManager!=null) { location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if(location!=null) { latitude=location.getLatitude(); longitude=location.getLongitude(); } } } } }catch (Exception e) { } return location; } // call this to stop using location public void stopUsingLocation() { if(locationManager!=null) { locationManager.removeUpdates(LocationTracker.this); } } // call this to getLatitude public double getLatitude() { if(location!=null) { latitude=location.getLatitude(); } return latitude; } //call this to getLongitude public double getLongitude() { if(location!=null) { longitude=location.getLongitude(); } return longitude; } public boolean isLocationEnabled() { return this.isLocationEnabled; } //call to open settings and ask to enable Location public void askToOnLocation() { AlertDialog.Builder dialog=new AlertDialog.Builder(con); //set title dialog.setTitle("Settings"); //set Message dialog.setMessage("Location is not Enabled.Do you want to go to settings to enable it?"); // on pressing this will be called dialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); con.startActivity(intent); } }); //on Pressing cancel dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // show Dialog box dialog.show(); } @Override public void onLocationChanged(Location location) { } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Nullable @Override public IBinder onBind(Intent intent) { return null; } } //layout for MainActivity activity_main.xml<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="300dp" android:id="@+id/mmymap" android:layout_alignParentTop="true" android:name="com.google.android.gms.maps.SupportMapFragment" /> <Button android:id="@+id/getlocation" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="getLocation" android:layout_below="@+id/mmymap" /> <TextView android:id="@+id/location" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/getlocation"/> <TextView android:id="@+id/address" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/location"/> </RelativeLayout> AndroidManifest.xml<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidruler.mymap" > <permission android:name="com.androidruler.mymap.permission.MAPS_RECEIVE" android:protectionLevel="signature" /> <uses-permission android:name="com.androidruler.mymap.permission.MAPS_RECEIVE" /> <!-- Required OpenGL ES 2.0. for Maps V2 --> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- API key for the Android Maps API v2. The value is defined as a string resource. --> <meta-data android:name="com.google.android.geo.API_KEY" android:value="AIzaSyB46A0jQLS9lm1x-fO07tD-EPHzoxCvMkg"/> </application> </manifest>