android- Google MAP api with multiple pin and draw path

  • Google MAP api with android example.
  • How to use Google map api in android.
  • Sample code for google map api in android.
  • android-Google MAP demo
  • How to display Google map in android.
  • How to put a pin in Google map in android.
  • Multiple pin in android google map.
  • Draw path between two pin in android



MapDemoActivity.java


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class MapDemoActivity extends MapActivity
{
    Context context;
    Drawable drawable,drawableDot;
    List<Overlay> mapOverlays;
    OverlayItem overlayitem;
    HelloItemizedOverlay itemizedoverlay;
    GeoPoint point,point2;
    MapView mapView ;
    TextView tv,tv2;
    int five=50;
    boolean flag=true;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mains);
       
        context=getApplicationContext();
        /** */
        LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener mlocListener = new MyLocationListener(context);
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1,mlocListener);
        /* ***/

        tv=(TextView) findViewById(R.id.textView1);
        tv2=(TextView) findViewById(R.id.textView2);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        mapOverlays = mapView.getOverlays();

        drawable = this.getResources().getDrawable(R.drawable.map128);
       
        itemizedoverlay = new HelloItemizedOverlay(drawable);
        point = new GeoPoint((int)(22.30 * 1E6),(int)(70.80 * 1E6));
        point2= new GeoPoint((int)(25.75 * 1E6),(int)(70.50 * 1E6));
        overlayitem = new OverlayItem(point,"Hiii...!", "I'm at Rajkot,India!");
        itemizedoverlay.addOverlay(overlayitem);
        mapOverlays.add(itemizedoverlay);
       
        try {
            getDistance(point, point2);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    void addPoint(int lat,int lng)
    {
        if(flag)
        {
            drawableDot = this.getResources().getDrawable(R.drawable.ipadblue);
            flag=false;
        }
        else
        {
            drawableDot = this.getResources().getDrawable(R.drawable.iphonered);
            flag=true;
        }
        itemizedoverlay= new HelloItemizedOverlay(drawableDot);
        GeoPoint point2 = new GeoPoint((int)(lat * 1E6)+five,(int)(lng * 1E6)+five);
        //GeoPoint point2 = new GeoPoint((int)(lat * 1E6),(int)(lng * 1E6));
       
        OverlayItem overlayItem2 = new OverlayItem(point2, "", "");
        itemizedoverlay.addOverlay(overlayItem2);
        mapOverlays.add(itemizedoverlay);
        mapView.invalidate();
        tv2.setText(""+five);
        five+=50;
    }

   
private void getDistance(GeoPoint src, GeoPoint dest) throws Exception {

        StringBuilder urlString = new StringBuilder();
        urlString.append("http://maps.googleapis.com/maps/api/directions/json?");
        urlString.append("origin=");//from
        urlString.append( Double.toString((double)src.getLatitudeE6() / 1E6));
        urlString.append(",");
        urlString.append( Double.toString((double)src.getLongitudeE6() / 1E6));
        urlString.append("&destination=");//to
        urlString.append( Double.toString((double)dest.getLatitudeE6() / 1E6));
        urlString.append(",");
        urlString.append( Double.toString((double)dest.getLongitudeE6() / 1E6));
        urlString.append("&mode=walking&sensor=true");
        Log.d("xxx","URL="+urlString.toString());

        // get the JSON And parse it to get the directions data.
        HttpURLConnection urlConnection= null;
        URL url = null;

        url = new URL(urlString.toString());
        urlConnection=(HttpURLConnection)url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.connect();

        InputStream inStream = urlConnection.getInputStream();
        BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));

        String temp, response = "";
        while((temp = bReader.readLine()) != null){
            //Parse data
            response += temp;
        }
        //Close the reader, stream & connection
        bReader.close();
        inStream.close();
        urlConnection.disconnect();

        //Sortout JSONresponse
        JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
        JSONArray array = object.getJSONArray("routes");
            //Log.d("JSON","array: "+array.toString());

        //Routes is a combination of objects and arrays
        JSONObject routes = array.getJSONObject(0);
            //Log.d("JSON","routes: "+routes.toString());

        String summary = routes.getString("summary");
            //Log.d("JSON","summary: "+summary);

        JSONArray legs = routes.getJSONArray("legs");
            //Log.d("JSON","legs: "+legs.toString());

        JSONObject steps = legs.getJSONObject(0);
                //Log.d("JSON","steps: "+steps.toString());

        JSONObject distance = steps.getJSONObject("distance");
            //Log.d("JSON","distance: "+distance.toString());

                String sDistance = distance.getString("text");
                int iDistance = distance.getInt("value");
                System.out.println("Distance :S: "+ sDistance);
                System.out.println("Distance :I: "+ sDistance);

    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
   
    public class MyLocationListener implements LocationListener
    {
        Context context;
       
        MyLocationListener(Context context)
        {
            this.context=context;
        }
        @Override
        public void onProviderDisabled(String provider)
        {
            Toast.makeText(context,"Gps Disabled",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onProviderEnabled(String provider)
        {
            Toast.makeText(context,"Gps Enabled",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras)
        {
        }

        @Override
        public void onLocationChanged(Location location)
        {
            int lat=(int) location.getLatitude();
            int lng=(int) location.getLongitude();
            addPoint(lat,lng);
                String Text = "My current location is: " + "Latitud = "+ location.getLatitude() +"\n Longitud = " + location.getLongitude();
                //Toast.makeText(context,Text,Toast.LENGTH_SHORT).show();
                addPoint(lat,lng);
                //mapView.getOverlays().add(new MyItemOverlay(drawable));
                tv.setText(Text);
        }
}
}


HelloItemizedOverlay.java
import java.util.ArrayList;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;

public class HelloItemizedOverlay extends ItemizedOverlay<OverlayItem>
{
    private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    //private Context mContext;

    public HelloItemizedOverlay(Drawable defaultMarker) {
        super(boundCenterBottom(defaultMarker));
        //mContext = context;
    }
     @Override
     public boolean draw(Canvas canvas, MapView mapView, boolean shadow,long when)
     {
         Paint paint = null;
       
         //GeoPoint gp1 = new GeoPoint((int)(22 * 1E6),(int)(80 * 1E6));
         GeoPoint gp3 = new GeoPoint((int)(18 * 1E6),(int)(50 * 1E6));
         GeoPoint gp2 = new GeoPoint((int)(25 * 1E6),(int)(70 * 1E6));
         GeoPoint gp1=mOverlays.get(0).getPoint();
         //GeoPoint gp2=mOverlays.get(1).getPoint();
       
         Projection projection = mapView.getProjection();
            if (shadow == false)
            {
                 paint = new Paint();
                paint.setAntiAlias(true);
               
                /** drawing first line */
                Point point = new Point();
                projection.toPixels(gp1, point);
                paint.setColor(Color.BLUE);
                Point point2 = new Point();
                projection.toPixels(gp2, point2);
                paint.setStrokeWidth(2);
                canvas.drawLine((float) point.x, (float) point.y, (float) point2.x,
                        (float) point2.y, paint);
               
                /** drawing Second line */
                point = new Point();
                projection.toPixels(gp2, point);
                paint.setColor(Color.BLUE);
                point2 = new Point();
                projection.toPixels(gp3, point2);
                paint.setStrokeWidth(2);
                canvas.drawLine((float) point.x, (float) point.y, (float) point2.x,
                        (float) point2.y, paint);
              
            }
            if(shadow==false && mOverlays.size()>=2)
            {
                for(int i=1;i<mOverlays.size();i++)
                {
                    GeoPoint gpPath1 =mOverlays.get(i-1).getPoint();
                    GeoPoint gpPath2 =mOverlays.get(i).getPoint();
                   
                    paint.setColor(Color.RED);
                    Point point = new Point();
                    projection.toPixels(gpPath1, point);
                   
                    paint.setColor(Color.RED);
                    Point point2 = new Point();
                    projection.toPixels(gpPath2, point2);
                   
                    paint.setStrokeWidth(2);
                    canvas.drawLine((float) point.x, (float) point.y, (float) point2.x,
                        (float) point2.y, paint);
                }
            }
            return super.draw(canvas, mapView, shadow, when);
     }

    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();
    }

    @Override
    protected boolean onTap(int index) {
     // remove below comment if you want to display some dialog on location click
     //OverlayItem item = mOverlays.get(index);
        //AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
        //dialog.setTitle(item.getTitle());
        //dialog.setMessage(item.getSnippet());
        //dialog.show();
        return true;
    }
}


AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="march.fifteen"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
   
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
   

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <uses-library android:name="com.google.android.maps" />
        <activity
            android:name=".MapDemoActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


Post you may like:
  1. Android- download and save image in sd card and read-images from sd card click here
  2. Android- Hidden Codes and tricks & tips of android click here
  3. Android-IDE (AIDE) Develop android application in android phone without PC or eclipse click here
  4. Java 1.7 new Improved features, 1.7 Release date, Examples click here
  5. Google Market is NO-MORE click more



9 comments:

Post a Comment