This Android tutorial will show how to use markers to display positions using Google maps Android API v2. We will also see features related to using markers like changing the default color, replacing the default icon with a custom icon-image, allow user to drag the marker, show our current position using marker and related event listeners like on-marker-click and on-marker-drag.
Refer the previous Android tutorial on how to draw lines on map using Google Maps Android API for basics on Google maps and prerequisite. Now lets directly jump to the tutorial on adding markers.
In the GoogleMap instance we have created call the method addMarker by passing MarkerOptions as parameter. Use LatLng to define the position to add the marker.
googleMap.addMarker(new MarkerOptions().position(TIMES_SQUARE));
MarkerOptions provides variety of options to customize the marker. Following code is to change the default color of the marker.
googleMap.addMarker(new MarkerOptions() .position(BROOKLYN_BRIDGE) .title("First Pit Stop") .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
googleMap.addMarker(new MarkerOptions() .position(WALL_STREET) .title("Wrong Turn!") .icon(BitmapDescriptorFactory .fromResource(R.drawable.my_flag)));
Just set the draggable to true.
googleMap.addMarker(new MarkerOptions().position(TIMES_SQUARE) .title("Race Start").snippet("Race Start: 9:00 AM CST") .draggable(true));
To add a marker to the current location, we need to know the LatLng. Refer the get current location in Android tutorial to find the current LatLng and using that we can add the marker easily as shown above.
Lets see two main event listeners related to markers OnMarkerClickListener and OnMarkerDragListener. We need to implement these interfaces and add its instance to the GoogleMap instance to track the events.
OnMarkerClickListener has one method onMarkerClick to be implemented. Using the Marker instance passed as argument we can know which marker is clicked.
public boolean onMarkerClick(Marker marker) { Log.i("GoogleMapActivity", "onMarkerClick"); Toast.makeText(getApplicationContext(), "Marker Clicked: " + marker.getTitle(), Toast.LENGTH_LONG) .show(); return false; }
OnMarkerDragListener has got three methods to be implemented. onMarkerDragStart, onMarkerDrag and onMarkerDragEnd. Use onMarkerDrag method cautiously as it will be invoked all through the drag position.
@Override public void onMarkerDrag(Marker marker) { // do nothing during drag } @Override public void onMarkerDragEnd(Marker marker) { toPosition = marker.getPosition(); Toast.makeText( getApplicationContext(), "Marker " + marker.getTitle() + " dragged from " + fromPosition + " to " + toPosition, Toast.LENGTH_LONG).show(); } @Override public void onMarkerDragStart(Marker marker) { fromPosition = marker.getPosition(); Log.d(getClass().getSimpleName(), "Drag start at: " + fromPosition); }
Following is the complete code of map activity.
package com.javapapers.android.maps.marker; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener; 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.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; public class GoogleMapActivity extends FragmentActivity implements OnMarkerClickListener, OnMarkerDragListener { private static final LatLng LOWER_MANHATTAN = new LatLng(40.722543, -73.998585); private static final LatLng TIMES_SQUARE = new LatLng(40.7577, -73.9857); private static final LatLng BROOKLYN_BRIDGE = new LatLng(40.7057, -73.9964); private static final LatLng WALL_STREET = new LatLng(40.7064, -74.0094); private static LatLng fromPosition = null; private static LatLng toPosition = null; private GoogleMap googleMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); addGoogleMap(); // addLines(); addMarkers(); } private void addGoogleMap() { // check if we have got the googleMap already if (googleMap == null) { googleMap = ((SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map)).getMap(); googleMap.setOnMarkerClickListener(this); googleMap.setOnMarkerDragListener(this); } } private void addMarkers() { if (googleMap != null) { // a draggable marker with title and snippet googleMap.addMarker(new MarkerOptions().position(TIMES_SQUARE) .title("Race Start").snippet("Race Start: 9:00 AM CST") .draggable(true)); // marker with custom color googleMap.addMarker(new MarkerOptions() .position(BROOKLYN_BRIDGE) .title("First Pit Stop") .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_GREEN))); // marker with opacity googleMap.addMarker(new MarkerOptions().position(LOWER_MANHATTAN) .title("Second Pit Stop").snippet("Best Time: 6 Secs") .alpha(0.4f)); // marker using custom image googleMap.addMarker(new MarkerOptions() .position(WALL_STREET) .title("Wrong Turn!") .icon(BitmapDescriptorFactory .fromResource(R.drawable.my_flag))); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom( BROOKLYN_BRIDGE, 13)); } } private void addLines() { if (googleMap != null) { googleMap.addPolyline((new PolylineOptions()) .add(TIMES_SQUARE, BROOKLYN_BRIDGE, LOWER_MANHATTAN, TIMES_SQUARE).width(5).color(Color.BLUE) .geodesic(true)); // move camera to zoom on map googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom( LOWER_MANHATTAN, 13)); } } @Override public boolean onMarkerClick(Marker marker) { Log.i("GoogleMapActivity", "onMarkerClick"); Toast.makeText(getApplicationContext(), "Marker Clicked: " + marker.getTitle(), Toast.LENGTH_LONG) .show(); return false; } @Override public void onMarkerDrag(Marker marker) { // do nothing during drag } @Override public void onMarkerDragEnd(Marker marker) { toPosition = marker.getPosition(); Toast.makeText( getApplicationContext(), "Marker " + marker.getTitle() + " dragged from " + fromPosition + " to " + toPosition, Toast.LENGTH_LONG).show(); } @Override public void onMarkerDragStart(Marker marker) { fromPosition = marker.getPosition(); Log.d(getClass().getSimpleName(), "Drag start at: " + fromPosition); } }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.javapapers.android.maps.marker" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <permission android:name="com.javapapers.android.maps.marker.permission.MAPS_RECEIVE" android:protectionLevel="signature" /> <uses-permission android:name="com.javapapers.android.maps.marker.permission.MAPS_RECEIVE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.javapapers.android.maps.marker.GoogleMapActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIyxSyCRCQcX8baAnHL_ohscNcALAak-HnjTO5s" /> </application> </manifest>
<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" tools:context=".GoogleMapActivity" > <fragment android:id="@+id/map" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
Comments are closed for "Markers–Google Maps Android API v2".
this is project give an error while running on emulator =”INSTALL_FAILED_MISSING_SHARED_LIBRARY”
so please give suitable reply and how to solve this error
Planning to make a game using this.
Thanks for this valuable information Joe.
:)
Hi JOE,
Thanks all of your examples are awesome and also coding style are very good again thanks for sharing.
this tutorial examples help me lot for any android beginners.
thank you.
hi buddy there is problem .when i add the location name then marker at that location is drawn but below google map is not shown .. i have integrated the map in the app but it is visible up to limited area ..if i enter the location name shown on the map on below screen then marker is drawn n the map is visible too but if i enter the location name which is not visible on the map below at the current time then the map will move to that location n draw marker on that but map is not changing it still visible to that area at the begining time what is the problem how can i show the map on the desired location
realy nice n good tutorial
Thanks Shahid.
FragmentActivity cannot be resolved to a type. This was the error i got while execute ..
Really very nice tutorial, I try all the sample google application. Everything Working fine Joe, Thank for you turtorial. Will you post application using BashAdapter and Sliding. It will really helpful us…
Hey my app just stopped wrking.. I have put the activity on a button click. But as soon as i click on the button, it causes an exception. Any help would be appreciated.. Thanx in advance.. :)
sir v nice tutorial ,i wanted to ask you , can you help me in showing distance inside the infowindow ??
like when i click on the marker , it shows the places names but i also want to display the distance : 2km below the name of the place
Do you have such tutorial ?
thanking you