dcsimg
October 1, 2016
Hot Topics:

Adding Map Markers and Handling Marker Events in Android Apps

  • May 4, 2015
  • By Vipul Patel
  • Send Email »
  • More Articles »

Introduction

In earlier articles on working with Google maps, we have explored how to set up the development environment as well as basics of working with Google Maps in an Android environment. In this article, we will learn how to handle map markers: add map markers to a map, as well as handle map marker events.

Map Markers

Google maps uses markers to visually indicate a location. When you search for a location or an address on maps.google.com, the current display is relocated to the area that was searched and a marker is displayed.

For example, searching for the Space Needle on maps.google.com results in the following to be displayed:

Marker1
Figure 1: We can see that a marker was placed on the map where the landmark is located.

We can add markers in Android applications that use Google Maps, as well as conduct activities whenever we have an event, like a click event, happening on the markers.

Hands On

In this hands on, we will add a marker on the map location specified by the user. Additionally, we will wire to the long tap event to add a marker on the map. For the hands on portion, we will continue to use the project that we created earlier, adding another activity for dealing with map markers.

Add a new Blank Activity, called MapMarkerActivity, to the project.

Marker2
Figure 2: Adding the new Blank Activity

Click Finish to add the activity.

Open the layout file activity_map_marker.xml and change the default contents, as shown in the following code segment.

<?xml version="1.0" encoding= "utf-8"?>
<LinearLayout 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"
   android:orientation="vertical"

   tools:context="com.example.vipulp.myapplication.
      MapMarkerActivity">


   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal">

      <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:id="@+id/textView"
         android:text="Location:"
         android:textSize="20sp" />

      <EditText
         android:layout_width="183dp"
         android:layout_height="wrap_content"
         android:id="@+id/editText"
         android:layout_gravity="center_horizontal" />

      <Button
         android:layout_width="71dp"
         android:layout_height="wrap_content"
         android:text="Go"
         android:id="@+id/button"
         android:onClick="findLocation" />

   </LinearLayout>



   <fragment xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/map"
      android:name="com.google.android.gms.maps.SupportMapFragment"
      android:layout_width="match_parent"
      android:layout_height="fill_parent" />

</LinearLayout>

Now we are ready to make the changes in the Java file entitled MapMarkerActivity.java.

Add the following import statements.

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

import com.google.android.gms.maps.CameraUpdate;
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.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.IOException;
import java.util.List;

Change the default class definition to what's shown in the following code snippet:

public class MapMarkerActivity extends FragmentActivity
   implements OnMapReadyCallback {

Add the following local class variables.

GoogleMap mMap;
Marker marker;

Modify the onCreate method to handle the long click event handler.

protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_map_marker);
   SupportMapFragment mapFrag = (SupportMapFragment)
      getSupportFragmentManager().
         findFragmentById(R.id.map);
   mMap = mapFrag.getMap();

   if(mMap != null) {

      mMap.setOnMapLongClickListener(new
               GoogleMap.OnMapLongClickListener() {
            @Override
            public void onMapLongClick (LatLng latLng){
               Geocoder geocoder =
                  new Geocoder(MapMarkerActivity.this);
               List<Address> list;
               try {
                  list = geocoder.getFromLocation(latLng.latitude,
                     latLng.longitude, 1);
               } catch (IOException e) {
                  return;
               }
               Address address = list.get(0);
               if (marker != null) {
                  marker.remove();
               }

               MarkerOptions options = new MarkerOptions()
                  .title(address.getLocality())
                  .position(new LatLng(latLng.latitude,
                     latLng.longitude));

               marker = mMap.addMarker(options);
            }
         });
      }
   }

Next, we will implement the onMapReady method.

public void onMapReady(final GoogleMap map) {
   this.mMap = map;
}

Finally, we will implement the Click event for the button on the layout file.

public void findLocation(View v) throws IOException {

   EditText et = (EditText)findViewById(R.id.editText);
   String location = et.getText().toString();
   Geocoder geocoder = new Geocoder(this);
   List<Address> list = geocoder.getFromLocationName(location, 1);
   Address add = list.get(0);
   String locality = add.getLocality();
   LatLng ll = new LatLng(add.getLatitude(), add.getLongitude());
   CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, 15);
   mMap.moveCamera(update);
   if(marker != null)
      marker.remove();
  MarkerOptions markerOptions = new MarkerOptions()
      .title(locality)
      .position(new LatLng(add.getLatitude(), add.getLongitude()));
   marker = mMap.addMarker(markerOptions);

}

Lastly, we need to wire the MapMarkerActivity from the MainActivity. Add a button on the MainActivity layout file and wire up the invocation of the MapMarkerActivity to the click event of the button.

When we run the application and invoke the MapMarkerActivity, and we search for a landmark, we will see that the marker is displayed at the landmark we have searched for. In addition, when we long tap on any location on the map, the marker moves to that location.

Summary

In this article, we have learned how to handle map markers in Google Maps in an Android application.

About the Author

Vipul Patel is a technology geek based in Seattle. He can be reached at vipul.patel@hotmail.com. You can visit his LinkedIn profile at https://www.linkedin.com/pub/vipul-patel/6/675/508.


Tags: Java, Google Maps, Android applications, map marker, Click event




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel