JavaWeb-based JavaAdding Map Markers and Handling Marker Events in Android Apps

Adding Map Markers and Handling Marker Events in Android Apps

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.

Get the Free Newsletter!
Subscribe to Developer Insider for top news, trends & analysis
This email address is invalid.
Get the Free Newsletter!
Subscribe to Developer Insider for top news, trends & analysis
This email address is invalid.

Latest Posts

Related Stories