In this Android Google Maps API Tutorial, we will create a simple map.To use Google Maps we need Google Maps Android API. Now don’t worry about getting an API is very easy. First lets create our android project for this Android Google Maps Tutorial.
Android Google Maps Tutorial
- Open android studio and create a new Android Project.
- I named it GoogleMaps. We will select Google Maps Activity from the predefined templates. (This will simplify the process of adding google map)
Google Maps Activity
- Now click next -> and finish.
- You will see the below screen when your android google maps tutorial project is fully loaded.
google_maps_api.xml
- See the highlighted text it is a link. Copy this and paste it to your browser (Make sure you are logged in your google account). You will see this.
Developers Console
- Now copy the API Key to your String inside google_maps_api.xml file. (From where you copied the link to create the API).
- Now run your application and you will that the app Start Google Maps (See the screenshot of my output).
Android Google Maps Tutorial
To locate the location(latitude and longitude) and location marker name I have added few line of code in MapsActivity.java
OnMapReady Method( )
public void onMapReady(GoogleMap googleMap) {
//Initializing our map
mMap = googleMap;
//Creating a random coordinate
LatLng latLng = new LatLng(20.5937, 78.9629);
//Adding marker to that coordinate
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Setting onMarkerDragListener to track the marker drag
mMap.setOnMarkerDragListener(this);
//Adding a long click listener to the map
mMap.setOnMapLongClickListener(this);
}
This method is to point out the given location(latitude and longitude)
getCurrentLocation()
private void getCurrentLocation() {
//Creating a location object
Location location = LocationServices.FusedLocationApi.getLastLocation
(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
This method is to point the current location(lat and long)by GPS
moveMap( )
private void moveMap() {
//String to display current latitude and longitude
String msg = latitude + ", "+longitude;
//Creating a LatLng Object to store Coordinates
LatLng latLng = new LatLng(latitude, longitude);
//Adding marker to map
mMap.addMarker(new MarkerOptions()
.position(latLng) //setting position
.draggable(true) //Making the marker draggable
.title("Current Location")); //Adding a title
//Moving the camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Animating the camera
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
//Displaying current coordinates in toast
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
For location marker name
In MapsActivity add few lines of code in OnCreate (here we can get idea on Shared Preferences)
final SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
if(sharedpreferences.contains(Name)){
strname= sharedpreferences.getString(Name,"Default").toString();
// 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);
}else{
/* Alert Dialog Code Start*/
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Location Name"); //Set Alert dialog title here
alert.setMessage("Enter Your Name Here"); //Message here
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//You will get as string input data in this variable.
// here we convert the input to a string and show in a toast.
String srt = input.getEditableText().toString();
strname=srt;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, srt);
editor.commit();
} // End of onClick(DialogInterface dialog, int whichButton)
}); //End of alert.setPositiveButton
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
dialog.cancel();
}
}); //End of alert.setNegativeButton
AlertDialog alertDialog = alert.create();
alertDialog.show();
// 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);
}
We will also need the following permission to be added in our manifest and replace your API key in meta data.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
So far the full code we just created
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {
private GoogleMap mMap;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
String strname ="Current Location";
//String strname; private double longitude;
private double latitude;
//Google ApiClient private GoogleApiClient googleApiClient;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
final SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
if(sharedpreferences.contains(Name)){
strname= sharedpreferences.getString(Name,"Default").toString();
// 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);
}else{
/* Alert Dialog Code Start*/
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Location Name"); //Set Alert dialog title here
alert.setMessage("Enter Your Name Here"); //Message here
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//You will get as string input data in this variable.
// here we convert the input to a string and show in a toast.
String srt = input.getEditableText().toString();
strname=srt;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, srt);
editor.commit();
} // End of onClick(DialogInterface dialog, int whichButton)
}); //End of alert.setPositiveButton
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
dialog.cancel();
}
}); //End of alert.setNegativeButton
AlertDialog alertDialog = alert.create();
alertDialog.show();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
}
//Initializing googleapi client
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onMapReady(GoogleMap googleMap) {
//Initializing our map
mMap = googleMap;
//Creating a random coordinate
LatLng latLng = new LatLng(20.5937,78.9629);
//Adding marker to that coordinate
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true)
.title(strname));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
//Getting current location
private void getCurrentLocation() {
//Creating a location object
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.
ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, 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;
}
Location location = LocationServices.FusedLocationApi
.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
//moving the map to location
moveMap();
}
}
//Function to move the map
private void moveMap() {
//String to display current latitude and longitude
String msg = latitude + ", "+longitude;
//Creating a LatLng Object to store Coordinates
LatLng latLng = new LatLng(latitude, longitude);
//Adding marker to map
mMap.addMarker(new MarkerOptions()
.position(latLng) //setting position
.draggable(true) //Making the marker draggable
.title(strname)); //Adding a title
//Moving the camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Animating the camera
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
//Displaying current coordinates in toast
//Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); }
@Override protected void onStart() {
googleApiClient.connect();
super.onStart();
}
@Override protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
@Override public void onConnected(Bundle bundle) {
getCurrentLocation();
}
@Override public void onConnectionSuspended(int i) {
}
@Override public void onConnectionFailed(ConnectionResult connectionResult)
{
}
}
Output Screenshots
_____________________________________________________________________
Source code for this application GoogleMaps.zip , for apk googlemaps.apk
Happy Coding...
Comments
Post a Comment