mercredi 9 février 2011

Map Overlay Demo

After creating your first Google Maps Application,you may wish to add markers to the map to indicate places of interests.That's what you will see  in this article.

Adding markers
First you need to define a new class that extends the ItemizedOverlay class, which can manage a whole set of Overlays(the individual items placed in the map).

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;

public class CustomItemizedOverlay extends ItemizedOverlay{

 private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
 Context mContext;
 
 public CustomItemizedOverlay(Drawable defaultMarker) {
  super(defaultMarker);
  }

 public CustomItemizedOverlay(Drawable defaultMarker,Context context) {
    super(defaultMarker);
    mContext = context;
 }
 public void addOverlay(OverlayItem overlay) {
     mOverlays.add(overlay);
     populate();
 }
 
 @Override
 protected OverlayItem createItem(int i) {  
  return mOverlays.get(i);
 }

 @Override
 public int size() {
  return mOverlays.size();
 }
}

Go back to your main class  MapsActivity .In the following procedure, you'll  create  OverlayItem  and add it to an instance of CustomItemizedOverlay class,then add the CustomItemizedOverlay to the MapView using a GeoPoint  to define its coordinates on the map.
1- First, add an image for the map overlay under res/drawable directory of the project.
2- At the end of your onCreate() method, add 

List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
CustomItemizedOverlay itemizedoverlay = new CustomItemizedOverlay(drawable);


3- Now create an Array of Geopoint that represents the locations of places  you want to show in the map. 

// Define an array containing the mosque overlay items
        
   private OverlayItem [] mosqueItem = {
    new OverlayItem( new GeoPoint(35403398,1054842), "Zitouna Mosque", "Kairouan"),
    new OverlayItem( new GeoPoint(36513315,10194294), "El Abidine Mosque", "El Abidine Mosque")   
        };

4- Add the list of OverlayItem to your collection in the  CustomItemizedOverlay instance.Then add the CustomItemizedOverlay to your MapView.
for(int i=0; i<mosqueitem.length;i++ )
  itemizedoverlay.addOverlay(mosqueitem[i]);                                                                           
mapOverlays.add(itemizedoverlay); 


Your Application looks like the following one :




2 commentaires: