Google Maps Android Integration : Polylines | Polygons | Markers | Camera Animation

Spread knowledge

 

We all know how important maps have been to Android Apps. Maps in mobile applications have taken user expereince to a whole new level. And the credit goes to Google for creating Android Map APIs which allow seamless integration of maps into Android Application. But things dont end here, with Google APIs you can not only add maps but can  actually customize the complete map to fit into your application.

marker

 

In this example we will look into how to add a Google map into your application. After adding we will explore different ways with which it can be customized. 

Obtaining the API key

Before we begin, to display Google maps in your app you will have to register it with Google Dev Console and obtain the API key. Steps on how to register your app are mentioned here .

Integrating Google Maps.

  • To begin with the integration first we need to add the following dependency
    compile 'com.google.android.gms:play-services-maps:11.0.2'
  • Add the following snippet in you AndroidManifest.xml
    <meta-data android:name="com.google.android.geo.API_KEY"
    android:value="@string/google_maps_key"/>
  • Create a file by the name google_maps_api.xml in the res>values folder.You will have to add the API Key created in the first step in this file. Add the following
    <resources>
        <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">[YOUR- API-KEY]</string>
    </resource>

     

  • Add the following fragment to the layout file for your MapsActivity. Placing the SupportMapFragment is the simplest way of displaying a map in your app. SupportMapFragment is basically a wrapper around a MapView to automatically handle the necessary life cycle needs.
    <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" />

     

Note: You can also display a map by using a MapView in your own activity. But then you will have to explicitly handle all the lifecycle callbacks while  MapFragment handles this for you.

  • We will have to initialize the SupportMapFragment declared in the layout and call getMapAsync(OnMapReadyCallback) method on the fragment object.
  • Your MapActivity should implement OnMapReadyCallback interface and override onMapReady method
  • Calling getMapAsync will invoke the onMapReady callback along with the GoogleMap object when the map is ready.
  • GoogleMap is the main class of the Google Maps Android API and is the entry point for all methods related to the map

 

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @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);
    }

    /**
      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;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);

        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));

        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

    }
}

 

If you are using Android Studio and want to show your map inside an activity integrating Google map is very simple. You will just have to follow the following steps

  • Create a new project. Once you enter the package name you will be taken to a screen as shown below. Select Google Maps Activity and click on next.
  • With this Studio itself creates all the files with code as shown above.

Enabling Traffic

With Android Map APIs you can even show the current traffic on the map  inside your application similar to what the Google Map appication shows.You just need to call the following method on the map object as shown below

mMap.setTrafficEnabled(true);

 

Changing MapType

A map’s type governs the overall representation of the map. Besides this changing a map type would change the look and feel of your application. Google APIs come with four different types of maps. You can change the map type by just calling a single method on the map object.

mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

 

Adding Markers:

Markers are used to indicate any specific location on the map. A marker can be added on any location on the map

Adding Default Marker:

You can simply add a marker to a location by specifying its latitude and longitude co ordinates.

 

LatLng sydney = new LatLng(-34, 151);
MarkerOptions markerOptions = new MarkerOptions().position(sydney).title("Marker in Sydney").snippet("Sydney is one of the most popular city in Australia");
mMap.addMarker(markerOptions);

 

In the above example we add a marker on the city of sydney by passing its co ordinates and have also set the title and snippet for it. You can also notice that MarkerOptions is used to add a marker( You an read about MarkerOptions here  )

  • position   : Position of the marker
  • title           : Heading of the marker
  • snippet    : Sub heading of the marker

marker_name.png

Changing the color of default marker:

You can also change the color of the default marker as shown below

 

coloured_marker
CYAN coloured marker

 

You can choose any of the following colors

  • HUE_AZURE
  • HUE_BLUE
  • HUE_CYAN
  • HUE_GREEN
  • HUE_MAGENTA
  • HUE_ORANGE
  • HUE_RED
  • HUE_ROSE
  • HUE_VIOLET
  • HUE_YELLOW

 

 

 

 

Adding Icon to the Marker:

One of the most useful feature of a marker is that we can change the icon of the marker to anything we like. Our new custom marker icon can be taken from the device storeage, app resources or even can be retreived from web

markerOptions.icon(BitmapDescriptor);

 

Custom Marker icon

Icon for marker should be a BitmapDescriptor. You can have any image from your app resources as the marker icon. Just add the following code as shown below

BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.logo));
markerOptions.icon(icon);

Polylines

A polyline is basically a list of points, where line segments are drawn between consecutive points. Polylines are used to denote paths on the map. All the points are basically LatLng location with each of them having latitude and longitude co ordinates.

Polylines are drawn with the help of PolylineOptions

Adding default polyline

As already mentioned polyline are used to denote paths between LatLng locations. Below code draws a polyline between three major cities of Australia

LatLng sydney = new LatLng(-34, 151);
LatLng melbourne = new LatLng(37.813, 144.9631);
LatLng auckland = new LatLng(36.8485, 174.7633);

polylineOptions.add(new LatLng[] {
    sydney,
    melbourne,
    auckland
});

 

Screenshot_2017-08-11-17-51-50.png

Changing color of the polyline:

polylineOptions.color(ContextCompat.getColor(this,android.R.color.holo_orange_dark));

 

 

Screenshot_2017-08-11-17-54-08

 

Custom pattern for Polyline

Polylines drawn so far were simple lines of any color. But with Google APIs you can also change the pattern of the polyline drawn. These custom patterns are drawn with the help of the following PatternItem

Below code snippet shows a example where we draw a custom pattern polyline with Dash and Gap.

//Defining a Dash of length 50 pixels
Dash myDASH = new Dash(50);
//Defining a Gap of length 20 pixels
Gap myGAP = new Gap(20);

List < PatternItem > PATTERN_DASHED = Arrays.asList(myDASH, myGAP);

polylineOptions.pattern(PATTERN_DASHED);

mMap.addPolyline(polylineOptions);

 

Screenshot_2017-08-17-20-51-50

Adding Circle

So far we have seen how to  mark a location and how to draw a path between two locations on a map but with Circles you will be able to mark a complete area by highlighting it with the help of Circles

CircleOptions are required to draw circles as shown below

CircleOptions circleOptions = new CircleOptions();
circleOptions.center(new LatLng(-34, 151););
circleOptions.radius(2000);
circleOptions.strokeColor(ContextCompat.getColor(this,android.R.color.holo_orange_dark));
circleOptions.fillColor(ContextCompat.getColor(this,android.R.color.holo_orange_light));

googleMap.addCircle(circleOptions);

 

Screenshot_2017-08-12-18-25-05

 

Adding Polygon

Using circles we were able to hightlight area around a single location point but with Polygons you can now highlight the area between multiple location points.  For drawing Polygons we will be using PolygonOptions

Screenshot_2017-08-17-13-12-00.png

For this example we will be draw a polygon between 4 of Australia’s most popular cities

PolygonOptions polygonOptions=new PolygonOptions();

polygonOptions.add(new LatLng[]{sydney,melbourne,adelaide,brisbane});
polygonOptions.strokeColor(ContextCompat.getColor(this,android.R.color.holo_orange_dark));
polygonOptions.fillColor(ContextCompat.getColor(this,android.R.color.holo_orange_light));


googleMap.addPolygon(polygonOptions);

 

 

Moving/Animating Camera

You must have noticed that whenever you start your app the map is focused somewhere close to africa (as shown in the screenshot below ) even though you have your markers set up in australia. Google map actually doesnt focus on your markers by default. But it exposes APIs with the help of which you can focus the camera anywhere on the map. You can acheive this by using any of these two methods.

  • moveCamera()        : Will animate the camera to the desired position with a smooth                                        animation
  • animateCamera()   : Will move the camera to the desired position instantly.

 

Screenshot_2017-08-17-15-09-25

 

It must be noted that both moveCamera() and animateCamera() take in CameraUpdate as parameter. CameraUpdate defines a camera move. It can be obtained using CameraUpdateFactory as shown in the examples below

Zooming In

Zooms in on the map by moving the viewpoint’s height closer to the Earth’s surface. You can use this to implement you custom zoom in button

mMap.animateCamera(CameraUpdateFactory.zoomIn());

 

Zooming Out

Zooms out on the map by moving the viewpoint’s height farther away from the Earth’s surface.

mMap.animateCamera(CameraUpdateFactory.zoomOut());

 

Focus a location

With this API you can focus the camera on any location on the map by providing its latitude and longitude co ordinates. Calling this would automatically shift focus to the location at the center of the screen.

mMap.animateCamera(CameraUpdateFactory.newLatLng(sydney));

 

Camera Position

So far we were able to modify only one position parameter with CameraUpdateFactory. We were either able to zoom in/out or focus on a particular location. We should not forget that Google Maps can be tilted and rotated with easy gestures, giving users the ability to adjust the map with an orientation that makes sense for them .Google Maps Android API also allows you to change the user’s viewpoint of the map by modifying the map’s camera programatically. This is done with the help of CameraPosition . CameraPosition aggregates all camera position parameters such as location, zoom level, tilt angle, and bearing.

mMap.setBuildingsEnabled(true);

LatLng newyork = new LatLng(40.7128, -74.0059);

CameraPosition cameraPosition = new CameraPosition.Builder()
    .target(newyork) // Sets the center of the map
    .tilt(20) // Sets the tilt of the camera to 20 degrees
    .zoom(17) // Sets the zoom
    .bearing(90) // Sets the orientation of the camera to east
    .build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

 

 

Screenshot_2017-08-17-20-02-45.png

 

Conclusion

Thats it! I hope by now you have a good understanding of how Google Map API works and how to begin with Android Integration. If this tutorial helped you please share it with your friends. Dont forgot to like and comment. Also if you want to learn how to show a current locaton in Google Maps read this.


Spread knowledge

3 Replies to “Google Maps Android Integration : Polylines | Polygons | Markers | Camera Animation”

Leave a Reply

Your email address will not be published. Required fields are marked *