Wednesday, March 6, 2013

Android Draw Multiple polygon on Map overlay

Android Draw Multiple polygon on  Map overlay



Below I wrote the code for how to draw a multiple polygon on Google map overlay.
I hope it will help full for you.


Screen Shot



Activity Source code


package com.example.androidtest;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;

/**
 * @author vijayakumar
 */

public class AndroidprojectMApActivity extends MapActivity {
       MapView myMapView = null;
       MapController myMC = null;
       GeoPoint geoPoint = null;
        GeoPoint gP1;
       private List<Overlay> mapOverlays;
     PathOverlay pathOverlay = null;
       private Projection projection;
        List<GeoPoint>  path = new ArrayList<GeoPoint>();
       /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myMapView = (MapView) findViewById(R.id.mapview);
        myMapView.setBuiltInZoomControls(true);
          mapOverlays = myMapView.getOverlays();       
          projection = myMapView.getProjection();
          MapController mapController = myMapView.getController();
          mapController.setZoom(14);
          mapOverlays.add(new PathOverlay());
       
       }

       @Override
       protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
       }

      }


Overlay Source Code
package com.example.androidtest; 
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.util.Log;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

class PathOverlay extends Overlay{
       Point startPoint = null, endPoint = null;
       Path path  = null;
       GeoPoint gPointA;
       GeoPoint gPointA1;
       Point pointA ;
       Point pointA1 ;
      //private final List<GeoPoint> _points;
  
    public void draw(Canvas canvas, MapView mapv, boolean shadow){
        super.draw(canvas, mapv, shadow);
        Projection projection = mapv.getProjection();
        Paint   mPaint = new Paint();
        mPaint.setDither(true);
        mPaint.setColor(Color.parseColor("#FF0000"));
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mPaint.setStrokeJoin(Paint.Join.BEVEL);
        mPaint.setStrokeCap(Paint.Cap.BUTT);
        mPaint.setStrokeWidth(2);
          InputStream is = mapv.getResources().openRawResource(R.raw.json);
          byte[] buffer;
            try {
                  buffer = new byte[is.available()];
                    while (is.read(buffer) != -1);
                      String jsontext = new String(buffer);
                      JSONObject  fromobj3 = null;
                      JSONObject  fromobj4 = null;
                      JSONObject  fromobj5 = null;
                      JSONObject jObject2 =  new JSONObject(jsontext);
                      JSONObject  fromobj = jObject2.getJSONObject("kml");
                      JSONObject  fromobj1 = fromobj.getJSONObject("document");
                      JSONObject  fromobj2 = fromobj1.getJSONObject("folder");
                      JSONArray entries = fromobj2.getJSONArray("placemark");
                      int i;
                      for (i=0;i<entries.length();i++)
                      {
                            JSONObject post = entries.getJSONObject(i);
                            fromobj3 = post.getJSONObject("polygon");
                            fromobj4 = fromobj3.getJSONObject("outerboundaryis");
                            fromobj5 = fromobj4.getJSONObject("linearring");
                            String  coordinates =   fromobj5.getString("coordinates").toString();
                           
                                String[] coor = coordinates.split("0.00 ");
                                path = new Path();
                                             for(int j = 0; j<coor.length;j++) {
                                                       String latlong[] = coor[j].substring(0, coor[j].length()-1).split(",");
                                                         Double lon = Double.valueOf(latlong[0].toString());
                                                         Double lat = Double.valueOf(latlong[1].toString());
                                                         gPointA = new GeoPoint((int) (lat * 1E6), (int)((lon) * 1E6));
                                                            pointA = new Point();
                                                            projection.toPixels(gPointA, pointA);
                                                            Log.d("greenzone", "Geo Points   ::    " +gPointA.getLatitudeE6()  +" :: " + gPointA.getLongitudeE6());
                                                            if (j == 0) { //This is the start point
                                                             path.moveTo(pointA.x,pointA.y);
                                                            }
                                                            else {
                                                            if (j == coor.length - 1)// This is the link last point to first point
                                                               {
                                                             path.lineTo(pointA.x, pointA.y);
                                                                }
                                                            else// this is the first and last middle points
                                                               {
                                                             path.lineTo(pointA.x, pointA.y);
                                                                }
                                                               }
                                                    }
                                             canvas.drawPath(path, mPaint);
                                                  }
                   
            } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            } catch (JSONException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
     
    }
   
}

Download Source Code

29 comments:

  1. It's nice example explained by you which i read and know the process of implement activity source code and overlay source code that help me to draw multiple polygon on Google map in android.Thanks...

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. hello, your programm is very fine, but it is very slow... can you help me please or can you say how i can fix this? i am a beginner in android programming.

    thanks.

    ReplyDelete
  4. I'm gone to inform my little brother, that he should also go to see this web site on regular basis to take updated from hottest news update. Read the Full Piece of writing

    ReplyDelete
  5. What's up, just wanted to mention, I loved this post. It was helpful. Keep on posting! click through the up coming web site

    ReplyDelete
  6. hi, may i know the json in raw folder. Actually what it conatains.

    ReplyDelete
  7. Obviouslу, you'll be able to go to sites as You - Tube at which you might locate lots of funny vids. Many people will be happy with replaceable batteries for home use and occasional outings. Even today, I go big game hunting and all this, and the more dangerous something is, the happier I am.

    Also visit my page; next page
    my page :: http://wiki.valiantentertainment.com

    ReplyDelete
  8. The reason for this is muscle is build up when
    your physical exercise burns your fat. Wenn du ein Mädchen ansprechen willst, um auch eine Antwort zu kriegen und eine Unterhaltung anzufangen, dann musst du
    mit deiner Anschreib-Mail hervorstechen. Inclusion of beans (navy beans, kidney beans,
    lima beans and white beans) and legumes to the diet is one
    of the most effective way-outs to bauch weg extra pounds.


    Feel free to surf to my blog post; just click the next webpage

    ReplyDelete
  9. ӏ'll right away snatch your rss as I can not find your e-mail subscription hyperlink or newsletter service. Do you've any?

    Please аllow me recοgnize in order that I mаy subѕcribе.
    Thanks. does clear tinnitus work
    my webpage: does clear tinnitus work

    ReplyDelete
  10. Usually, a brand new website takes about six months
    to one year to appear in the SERPs of Google, assuming the service provider is worth their salt.
    This means you tend to be copying it through file sharing websites like rapidshare,
    megaupload, hotfile, etcetera. It would be optimum thought to select the local SEO service after checking the rank
    of their website. This will not only help you find the best service provider
    but will help you build an idea about the recent SEO market.

    SEO must be implemented by following a step by step process.
    This is the best part to ensure complete uniqueness to each of
    the websites. Pages and articles are very different, as far as Joomla is concerned.
    The thing that needs to be emphasized is to create text of your website in such a way that the algorithms find them easily.
    The title is supposed to explain the article, and the title is what your readers
    see when they search for content. People these days use
    the Internet for a varied purpose. The final way that
    you can use your Deviant - ART profile for SEO purposes is by being an active member of the community ' watch the work of others (especially if they are related to your business), encourage others to watch your work, comment on work, list other users as your friends. For instance, how many TV viewers then came to your car lot and purchased a vehicle. ' Every page should be optimized with additional keywords.
    Think wine, and keep the URL intact. Create a general,
    high-level category in which you want to manage all phrases'for example 'global,' 'online,' 'channel,
    ' and so on. A well-formed internal linking structure and good sitemap can ensure all pages of a website being indexed by a search engine. 4) Managing your online business. A person can find all sorts of products available at various prices on the internet. Such companies know the best about industry and market trends. SEO requires understanding of various algorithms.

    Also visit my site :: Suggested Resource site

    ReplyDelete
  11. Download Source Code link is not working

    ReplyDelete
  12. R.raw.json not found , i am new in android development please resolve link Download Source Code. so i can run this example .... waiting

    ReplyDelete
  13. She acquіred the concept fгom cooking pіоneer
    Barbarа Kerr. Do-it-youгself breaԁ іs not οnly faіrly ѕimple to maκe, but it's improved for you. The Emancipation of Mimi is the tenth studio album by American singer Mariah Carey.

    Feel free to surf to my web blog ... carscarl34.bravejournal.com

    ReplyDelete
  14. Үou've made some good points there. I looked on the internet to find out more about the issue and found most individuals will go along with your views on this website.

    Also visit my blog post Member.marketingbodz.Com

    ReplyDelete
  15. http://androidroadies.blogspot.in/

    ReplyDelete
  16. Fantastic work man, keep your heads high you did it.
    http://rachelpulley.tumblr.com/

    ReplyDelete
  17. May I know the json response format in raw folder??

    ReplyDelete


  18. Just seen your Article, it amazed me and surpised me with god thoughts that eveyone will benefit from it. It is really a very informative post for all those budding entreprenuers planning to take advantage of post for business expansions. You always share such a wonderful articlewhich helps us to gain knowledge .Thanks for sharing such a wonderful article, It will be deinitely helpful and fruitful article.
    Thanks
    DedicatedHosting4u.com


    ReplyDelete
  19. Thank You! For sharing such a great article, It’s been an amazing article. It provides lot’s of information, I really enjoyed to read this, I hope, I will get these kinds of information on a regular basis from your side.
    Mobile App Development Companies in Nigeria
    Apps Development Company in South Africa

    ReplyDelete
  20. I am overwhelmed by your post with such a nice topic. Usually, I visit your blogs http://kitestep.com/ and get updated with the information you include but today’s blog would be the most appreciable...

    Thanks
    Cpa offers

    ReplyDelete

  21. Your post is very good. I got to learn a lot from your post. Thank you for sharing your article for us. it is amazing post
    what is seo
    types of seo


    ReplyDelete

  22. This is a fantastic idea! I like it a lot because it's super easy for the audience to see the value of opting in. wonderful and amazing post very use full your post thanks for sharing your article
    Android Application development
    Web application

    ReplyDelete
  23. I would like to thank you for the efforts you had made for writing this wonderful piece of writing.
    Cost of an app development like Byjus

    ReplyDelete
  24. I’m going to read this. I’ll be sure to come back. thanks for sharing. and also This article gives the light in which we can observe the reality. this is very nice one and gives indepth information. thanks for this nice article... directions

    ReplyDelete
  25. Thanks for sharing such great information. Hope we will get regular updates from your side.
    elearning solution
    supply chain development
    challenges in education


    ReplyDelete
  26. Excellent!! really nice! I love your great and concise information. - Ace Infoway

    ReplyDelete
  27. Nice post thanks for sharing with us..
    If you have any requirement regarding App development like Android and iOS app development , so just click on link
    android application development company in USA

    ReplyDelete

Check out this may be help you

Related Posts Plugin for WordPress, Blogger...