. f Android Google Map V2 | Android Draw Polygon ~ Android Developers Blog

Wednesday, 4 June 2014

Android Google Map V2 | Android Draw Polygon

Hello Friends,
                               This is my small tutorial on google map v2. This blogs covers
following point:

1. Start Drawing on Google Map | Draw geometry on Google map
2. Clear drawing | Clear polygon
3. Close Polygon
4. Save Geometry

Screen 1:  Click on start drawing button and starting drawing geometry or polygon
                 or polyline.


 Screen2: Click on close polygon button which close the polygon.




Here is my code:

1. MainActivity.java  


  1. /* 
  2.  * Copyright (C) 2014 Mukesh Y authors 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  *      http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  */  
  16. package info.androiddeveloper.googlemapsv2;  
  17.   
  18. import java.util.ArrayList;  
  19.   
  20. import org.osmdroid.api.IGeoPoint;  
  21. import org.osmdroid.util.GeoPoint;  
  22.   
  23. import android.annotation.SuppressLint;  
  24. import android.app.ActionBar;  
  25. import android.app.Activity;  
  26. import android.app.AlertDialog;  
  27. import android.content.Context;  
  28. import android.content.DialogInterface;  
  29. import android.graphics.Color;  
  30. import android.os.Bundle;  
  31. import android.view.Menu;  
  32. import android.view.MenuInflater;  
  33. import android.view.MenuItem;  
  34. import android.view.View;  
  35. import android.view.Window;  
  36. import android.widget.Toast;  
  37.   
  38. import com.google.android.gms.maps.GoogleMap;  
  39. import com.google.android.gms.maps.GoogleMap.OnMapClickListener;  
  40. import com.google.android.gms.maps.MapFragment;  
  41. import com.google.android.gms.maps.model.LatLng;  
  42. import com.google.android.gms.maps.model.MarkerOptions;  
  43. import com.google.android.gms.maps.model.Polygon;  
  44. import com.google.android.gms.maps.model.PolygonOptions;  
  45. import com.google.android.gms.maps.model.PolylineOptions;  
  46.   
  47. /** 
  48.  * @author Mukesh Y 
  49.  */  
  50. public class MainActivity extends Activity implements OnMapClickListener {  
  51.   
  52.  // Google Map  
  53.  private GoogleMap googleMap;  
  54.  ArrayList<latlng> latLang = new ArrayList<latlng>();  
  55.  ArrayList<igeopoint> listPoints = new ArrayList<igeopoint>();  
  56.  boolean isGeometryClosed = false;  
  57.  Polygon polygon;  
  58.  Context context = MainActivity.this;  
  59.  boolean isStartGeometry = false;  
  60.   
  61.  @SuppressLint("NewApi")  
  62.  @Override  
  63.  protected void onCreate(Bundle savedInstanceState) {  
  64.   super.onCreate(savedInstanceState);  
  65.   setContentView(R.layout.activity_main);  
  66.   try {  
  67.    initilizeMap();  
  68.    ActionBar actionBar = this.getActionBar();  
  69.    actionBar.setDisplayHomeAsUpEnabled(true);  
  70.    actionBar.setDisplayShowCustomEnabled(true);  
  71.    actionBar.setDisplayShowTitleEnabled(true);  
  72.    actionBar.setIcon(R.drawable.ic_launcher);  
  73.   } catch (Exception e) {  
  74.   }  
  75.  }  
  76.    
  77.  @Override  
  78.  public boolean onCreateOptionsMenu(Menu menu) {  
  79.   MenuInflater menuInflater = getMenuInflater();  
  80.   menuInflater.inflate(R.menu.map_menu, menu);  
  81.   return super.onCreateOptionsMenu(menu);  
  82.  }  
  83.   
  84.  @Override  
  85.  public boolean onOptionsItemSelected(MenuItem item) {  
  86.   
  87.   switch (item.getItemId()) {  
  88.   case R.id.action_normal:  
  89.    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);  
  90.    return true;  
  91.   
  92.   case R.id.action_hybrid:  
  93.    googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);  
  94.    return true;  
  95.   
  96.   case R.id.action_satellite:  
  97.    googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);  
  98.    return true;  
  99.     
  100.   default:  
  101.    return super.onOptionsItemSelected(item);  
  102.   }  
  103.  }  
  104.   
  105.  /** 
  106.   * function to load map. If map is not created it will create it for you 
  107.   * */  
  108.  private void initilizeMap() {  
  109.   if (googleMap == null) {  
  110.   
  111.    googleMap = ((MapFragment) getFragmentManager().findFragmentById(  
  112.      R.id.map)).getMap();  
  113.   
  114.    // check if map is created successfully or not  
  115.    if (googleMap == null) {  
  116.     Toast.makeText(this"Sorry! unable to create maps",  
  117.       Toast.LENGTH_SHORT).show();  
  118.     return;  
  119.    }  
  120.   
  121.    googleMap.getUiSettings().setMyLocationButtonEnabled(true);  
  122.    // set my location  
  123.    googleMap.setMyLocationEnabled(true);  
  124.    googleMap.getUiSettings().setCompassEnabled(false);  
  125.    googleMap.getUiSettings().setRotateGesturesEnabled(false);  
  126.    // set zooming controll  
  127.    googleMap.getUiSettings().setZoomControlsEnabled(true);  
  128.    googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);  
  129.    googleMap.setOnMapClickListener(this);  
  130.   }  
  131.   
  132.  }  
  133.   
  134.  public void Draw_Map() {  
  135.   PolygonOptions rectOptions = new PolygonOptions();  
  136.   rectOptions.addAll(latLang);  
  137.   rectOptions.strokeColor(Color.BLUE);  
  138.   rectOptions.fillColor(Color.CYAN);  
  139.   rectOptions.strokeWidth(7);  
  140.   polygon = googleMap.addPolygon(rectOptions);  
  141.  }  
  142.   
  143.  @Override  
  144.  protected void onResume() {  
  145.   super.onResume();  
  146.   
  147.  }  
  148.   
  149.  /** 
  150.   * Close the Polygon / join last point to first point 
  151.   *  
  152.   * @param view 
  153.   */  
  154.  public void closePolygon(View view) {  
  155.   if (latLang.size() > 0) {  
  156.    Draw_Map();  
  157.    isGeometryClosed = true;  
  158.    isStartGeometry = false;  
  159.   }  
  160.  }  
  161.   
  162.  /** 
  163.   * Close the Polygon / join last point to first point 
  164.   *  
  165.   * @param view 
  166.   */  
  167.  public void startDrawing(View view) {  
  168.   isStartGeometry = true;  
  169.  }  
  170.   
  171.  @Override  
  172.  public void onMapClick(LatLng latlan) {  
  173.   if (!isGeometryClosed && isStartGeometry) {  
  174.    latLang.add(latlan);  
  175.    GeoPoint point = new GeoPoint(latlan.latitude, latlan.longitude);  
  176.    listPoints.add((IGeoPoint) point);  
  177.    MarkerOptions marker = new MarkerOptions().position(latlan);  
  178.    googleMap.addMarker(marker);  
  179.    if (latLang.size() > 1) {  
  180.     PolylineOptions polyLine = new PolylineOptions().color(  
  181.       Color.BLUE).width((float7.0);  
  182.     polyLine.add(latlan);  
  183.     LatLng previousPoint = latLang.get(latLang.size() - 2);  
  184.     polyLine.add(previousPoint);  
  185.     googleMap.addPolyline(polyLine);  
  186.    }  
  187.   }  
  188.  }  
  189.   
  190.  /** 
  191.   * Clear the all draw lines 
  192.   *  
  193.   * @param view 
  194.   *            Current view of activity 
  195.   */  
  196.  public void clearCanvas(View view) {  
  197.   
  198.   try {  
  199.    AlertDialog.Builder alertdalogBuilder = new AlertDialog.Builder(  
  200.      context);  
  201.   
  202.    alertdalogBuilder.setTitle("Clear");  
  203.    alertdalogBuilder  
  204.      .setMessage(  
  205.        "Do you really want to clear the geometry? This action can't be undone!")  
  206.      .setCancelable(false)  
  207.      .setPositiveButton("Yes",  
  208.        new DialogInterface.OnClickListener() {  
  209.   
  210.         @Override  
  211.         public void onClick(DialogInterface dialog,  
  212.           int id) {  
  213.          // polygon.remove();  
  214.          googleMap.clear();  
  215.          latLang = new ArrayList<latlng>();  
  216.          listPoints = new ArrayList<igeopoint>();  
  217.          isGeometryClosed = false;  
  218.         }  
  219.        })  
  220.      .setNegativeButton("No",  
  221.        new DialogInterface.OnClickListener() {  
  222.   
  223.         @Override  
  224.         public void onClick(DialogInterface dialog,  
  225.           int which) {  
  226.          dialog.cancel();  
  227.         }  
  228.        });  
  229.   
  230.    // Create Alert Dialog  
  231.    AlertDialog alertdialog = alertdalogBuilder.create();  
  232.    // show the alert dialog  
  233.    alertdialog.show();  
  234.   
  235.   } catch (Exception e) {  
  236.   }  
  237.   
  238.  }  
  239.   
  240.  /** 
  241.   * Method for Save Property 
  242.   *  
  243.   * @param view 
  244.   */  
  245.  public void savePolygon(View view) {  
  246.   try {  
  247.    if (isGeometryClosed) {  
  248.     AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(  
  249.       context);  
  250.     alertDialogBuilder.setTitle("Save");  
  251.     alertDialogBuilder  
  252.       .setMessage(  
  253.         "Do you really want to save? This action can't be undone!")  
  254.       .setCancelable(false)  
  255.       .setPositiveButton("Yes",  
  256.         new DialogInterface.OnClickListener() {  
  257.          public void onClick(DialogInterface dialog,  
  258.            int id) {  
  259.           // if this button is clicked, close  
  260.           // current activity  
  261.           // Prop.this.finish();  
  262.           savePolygonAfterAlert();  
  263.          }  
  264.         })  
  265.       .setNegativeButton("No",  
  266.         new DialogInterface.OnClickListener() {  
  267.          public void onClick(DialogInterface dialog,  
  268.            int id) {  
  269.           // if this button is clicked, just close  
  270.           // the dialog box and do nothing  
  271.           dialog.cancel();  
  272.          }  
  273.         });  
  274.   
  275.     // create alert dialog  
  276.     AlertDialog alertDialog = alertDialogBuilder.create();  
  277.   
  278.     // show it  
  279.     alertDialog.show();  
  280.    } else {  
  281.     showDialog(context, "Alert""Close geometry before saving");  
  282.    }  
  283.   } catch (Exception e) {  
  284.   
  285.   }  
  286.   
  287.  }  
  288.   
  289.  /** 
  290.   * Save the Polygon made by user 
  291.   *  
  292.   * @param view 
  293.   */  
  294.   
  295.  public void savePolygonAfterAlert() {  
  296.   // save geometry of polygon  
  297.  }  
  298.   
  299.  /** 
  300.   * Method to show the Dialog box 
  301.   *  
  302.   * @param ctx 
  303.   * @param title 
  304.   * @param msg 
  305.   */  
  306.  public void showDialog(Context ctx, String title, String msg) {  
  307.   AlertDialog.Builder dialog = new AlertDialog.Builder(ctx);  
  308.   dialog.setTitle(title).setMessage(msg).setCancelable(true);  
  309.   dialog.setPositiveButton("Ok"new DialogInterface.OnClickListener() {  
  310.    @Override  
  311.    public void onClick(DialogInterface dialog, int which) {  
  312.     dialog.dismiss();  
  313.    }  
  314.   });  
  315.   AlertDialog alertDialog = dialog.create();  
  316.   alertDialog.show();  
  317.  }  
  318. }  
  319. </igeopoint></latlng></igeopoint></igeopoint></latlng></latlng>  

Download Complete Code : GoogleMapV2

Enjoy Coding .....   cheers :)

Mukesh Kumar

Hi Guys I am from Delhi working as Web/Mobile Application Developer(Android Developer), also have knowledge of Roboelctric and Mockito ,android test driven development... Blogging has been my passion and I think blogging is one of the powerful medium to share knowledge and ideas....

1 comments:

  1. how can i get the area enclosed by the polygon on the google map in android,, i have used the following method to draw a polygon on the google map in my android app

    polygonOptions = new PolygonOptions();
    polygonOptions.fillColor(Color.RED);
    polygonOptions.strokeWidth(5);
    arrayPoints.add(point);
    polygonOptions.addAll(arrayPoints);
    map.addPolygon(polygonOptions);

    i want to show the area in the textview when the polygon is created. plz help.

    ReplyDelete

 

Copyright @ 2013 Android Developers Blog.