Map Marker Example in Android

4

This example show you how to draw movable marker on to map. You can darg and drop the marker to change its position. Can be used in any application where u want to take input from user for map location.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it MapMarkerExample.
2.) You will see some default code into your main.xml and android manifest file.
3.) Add internet permission to your manifest file or write following in android.manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.example.mapmarker" xmlns:android="http://schemas.android.com/apk/res/android"
	android:versionCode="1" android:versionName="1.0">
	<uses-sdk android:minSdkVersion="7" />

	<uses-permission android:name="android.permission.INTERNET" />
	<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
	<application android:icon="@drawable/icon" android:label="@string/app_name">
		<uses-library android:name="com.google.android.maps" />
		<activity android:label="@string/app_name" android:name=".MapMarkerActivity">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
	</application>
</manifest>

4.) Write following into main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="wrap_content" android:layout_height="wrap_content">
	<com.google.android.maps.MapView
		android:id="@+id/map" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:apiKey="0jp8vWjNayJISFKdvcJwGmwsjgoCoQrT_dflCfQ"
		android:clickable="true" />
	<ImageView android:id="@+id/drag" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:src="@drawable/marker"
		android:visibility="gone" />
</RelativeLayout>

5.) CreateYour own map API key and replace it in above main.xml.
6.) Add any marker image or push pin image in drawable folder.
7.) Run for output.

Steps:

1.) Create a project named MapMarkerExample and set the information as stated in the image.

Build Target: Android 2.1 (Google API)
Application Name: MapMarkerExample
Package Name: com.example.mapmarker
Activity Name: MapMarkerActivity
Min SDK Version: 7

2.) Open MapMarkerActivity.java file and write following code there:

package com.example.mapmarker;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;

public class MapMarkerActivity extends MapActivity {
  private MapView map=null;
  private MyLocationOverlay me=null;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    map=(MapView)findViewById(R.id.map);
    
    map.getController().setCenter(getPoint(21.0000169992044,
                                            78.0000484771729));
    map.setBuiltInZoomControls(true);
   
    
    Drawable marker=getResources().getDrawable(R.drawable.marker);
    
    marker.setBounds(0, 0, marker.getIntrinsicWidth(),marker.getIntrinsicHeight());
    
    map.getOverlays().add(new SitesOverlay(marker));
    
    me=new MyLocationOverlay(this, map);
    map.getOverlays().add(me);
  }
  
  @Override
  public void onResume() {
    super.onResume();
    
    me.enableCompass();
  }   
  
  @Override
  public void onPause() {
    super.onPause();
    
    me.disableCompass();
  }   
  
  @Override
  protected boolean isRouteDisplayed() {
    return(false);
  }
  
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_S) {
      map.setSatellite(!map.isSatellite());
      return(true);
    }
    else if (keyCode == KeyEvent.KEYCODE_Z) {
      map.displayZoomControls(true);
      return(true);
    }
    
    return(super.onKeyDown(keyCode, event));
  }

  private GeoPoint getPoint(double lat, double lon) {
    return(new GeoPoint((int)(lat*1000000.0),
                          (int)(lon*1000000.0)));
  }
    
  private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
    private List<OverlayItem> items=new ArrayList<OverlayItem>();
    private Drawable marker=null;
    private OverlayItem inDrag=null;
    private ImageView dragImage=null;
    private int xDragImageOffset=0;
    private int yDragImageOffset=0;
    private int xDragTouchOffset=0;
    private int yDragTouchOffset=0;
    
    public SitesOverlay(Drawable marker) {
      super(marker);
      this.marker=marker;
      
      dragImage=(ImageView)findViewById(R.id.drag);
      xDragImageOffset=dragImage.getDrawable().getIntrinsicWidth()/2;
      yDragImageOffset=dragImage.getDrawable().getIntrinsicHeight();
      
      items.add(new OverlayItem(getPoint(21.169992044,
              							78.484771729),
                                "Mumbai",
                                "Maharashtra, India"));
      populate();
    }
    
    @Override
    protected OverlayItem createItem(int i) {
      return(items.get(i));
    }
    
    @Override
    public void draw(Canvas canvas, MapView mapView,
                      boolean shadow) {
      super.draw(canvas, mapView, shadow);
      
      boundCenterBottom(marker);
    }
    
    @Override
    public int size() {
      return(items.size());
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event, MapView mapView) {
      final int action=event.getAction();
      final int x=(int)event.getX();
      final int y=(int)event.getY();
      boolean result=false;
      
      if (action==MotionEvent.ACTION_DOWN) {
        for (OverlayItem item : items) {
          Point p=new Point(0,0);
          
          map.getProjection().toPixels(item.getPoint(), p);
          
          if (hitTest(item, marker, x-p.x, y-p.y)) {
            result=true;
            inDrag=item;
            items.remove(inDrag);
            populate();

            xDragTouchOffset=0;
            yDragTouchOffset=0;
            
            setDragImagePosition(p.x, p.y);
            dragImage.setVisibility(View.VISIBLE);

            xDragTouchOffset=x-p.x;
            yDragTouchOffset=y-p.y;
            
            break;
          }
        }
      }
      else if (action==MotionEvent.ACTION_MOVE && inDrag!=null) {
        setDragImagePosition(x, y);
        result=true;
      }
      else if (action==MotionEvent.ACTION_UP && inDrag!=null) {
        dragImage.setVisibility(View.GONE);
        
        GeoPoint pt=map.getProjection().fromPixels(x-xDragTouchOffset,
                                                   y-yDragTouchOffset);
        OverlayItem toDrop=new OverlayItem(pt, inDrag.getTitle(),
                                           inDrag.getSnippet());
        Toast.makeText(MapMarkerActivity.this, pt.getLatitudeE6()+" "+pt.getLongitudeE6(), Toast.LENGTH_SHORT).show();
        items.add(toDrop);
        populate();
        
        inDrag=null;
        result=true;
      }
      
      return(result || super.onTouchEvent(event, mapView));
    }
    
    private void setDragImagePosition(int x, int y) {
      RelativeLayout.LayoutParams lp=
        (RelativeLayout.LayoutParams)dragImage.getLayoutParams();
            
      lp.setMargins(x-xDragImageOffset-xDragTouchOffset,
                      y-yDragImageOffset-yDragTouchOffset, 0, 0);
      dragImage.setLayoutParams(lp);
    }
  }
}       

3.) Compile and build the project.
4.) Move the marker shown on the map with the help of mouse for results shown below.

Output

Did you enjoy this article?
Share
the
Love
Get Free Updates
  • Ganesh

    Thanks very nice…

  • kunal

    It didn’t work for me:(

  • http://NA Dipankar

    Great tutorial…..it elp me a lot…keep this type of wo’rk well done !!

  • Philippe

    “Unfortunately, MapMarkerExample has stopped”
    Can you help me
    Thank you from France Cote d’Azur – Thanks for the job

Proudly designed by Theme Junkie.