In this tutorial we’ll discuss and implement some interesting features of android google maps API in our application. Before we get onto the discussion. Please make sure that you’ve been through the Android Google Maps Setup. It’s a prerequisite.
In this tutorial we’ll implement a few interesting features provided by the Android Google Maps API. Features include map markers, map types, camera animations and a few more. Add the map fragment in the content_main.xml
layout as we had done in the previous tutorial. This attaches the MapFragment to our MainActivity
. To get hold of the GoogleMap object in our MainActivity
class we need to implement the OnMapReadyCallback
interface and override the onMapReady
callback method.
Using the google map object we can change the map type too. There are four different types of map and each give different view of the map. These types are Normal, Hybrid, Satellite and Terrain. We can use them as given below.
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
We can enable/disable map zoom and rotations using the following lines of codes:
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
Some other customization methods available in the GoogleMap class are given below.
addCircle(CircleOptions options)
: This method add a circle to the mapaddPolygon(PolygonOptions options)
: This method add a polygon to the mapaddTileOverlay(TileOverlayOptions options)
: This method add tile overlay to the mapanimateCamera(CameraUpdate update)
: This method Moves the map according to the update with an animationclear()
: This method removes everything from the mapgetMyLocation()
: This method returns the currently displayed user locationmoveCamera(CameraUpdate update)
: This method repositions the camera according to the instructions defined in the updatesetTrafficEnabled(boolean enabled)
: This method Toggles the traffic layer on or offsnapshot(GoogleMap.SnapshotReadyCallback callback)
: This method Takes a snapshot of the mapstopAnimation()
: This method stops the camera animation if there is one in progressgoogleMap.addMarker(new MarkerOptions()
.position(new LatLng(37.4233438,-122.0728817))
.title("LinkedIn")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(37.4629101,-122.2449094))
.title("Facebook")
.snippet("Facebook HQ: Menlo Park"));
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(37.3092293,-122.1136845))
.title("Apple"));
snippet()
is used to display more data over the marker when it’s tapped. Animating or moving the camera to a specific point is performed using the following snippet:
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.4233438,-122.0728817),16));
In the above code 16 is the zoom level number. The map zooms in and centers onto the defined LatLng object. Note
: The LatLng object is instantiated and passed with the latitude and longitude double values.
The MainActivity.java is defined as below:
package com.journaldev.MapsInAction;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
SupportMapFragment mapFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(37.4233438, -122.0728817))
.title("LinkedIn")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(37.4629101,-122.2449094))
.title("Facebook")
.snippet("Facebook HQ: Menlo Park"));
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(37.3092293, -122.1136845))
.title("Apple"));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.4233438, -122.0728817), 10));
}
});
}
});
}
@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);
}
@Override
public void onMapReady(GoogleMap googleMap) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(37.4233438, -122.0728817))
.title("LinkedIn")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(37.4629101,-122.2449094))
.title("Facebook")
.snippet("Facebook HQ: Menlo Park"));
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(37.3092293, -122.1136845))
.title("Apple"));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.4233438, -122.0728817), 10));
}
}
We call getMapAsync()
on the SupportMapFragment object to register the callback. The FloatingActionButton invokes a new OnMapReadyCallBack method with a different map type. The content_main.xml
contains the MapFragment as shown below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.journaldev.MapsInAction.MainActivity"
tools:showIn="@layout/activity_main">
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_gravity="center"
android:layout_height="match_parent"
/>
</RelativeLayout>
The output of the android google maps example in action is shown below. This brings an end to this tutorial. You can download the final Android Google Maps Example project from the below link and replace the YOUR_API_KEY with the your own google maps api key.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Hii Anupam, I want ask u, Can i use google map in same file means without using new project file?
- Mangesh Goyal
HI Anupam, Smokin hot stuff! You’ve trimmed my dim. I feel as bright and fresh as your prolific website and blogs! I made the program below in java and compiled with javac command in Window7 (64bit machine). It simply post my machine IP and Mac address to my server application. When i run this script with java as >java Macregister I get what is expected, the program runs well on my machine. When I try to run it on other machines (Win8 - 32 Bit) I get error message and nothing works. My problem is 1) to make it compatible for all machines 2) to convert it into JAR application so that it is self executable on different machines. I am a new to Java and am struct, please help me out. It was cool to see your article pop up in my google search for the process yesterday. Great Guide. Keep up the good work! Best Regards, Irene Hynes
- Irene Hynes