Wednesday, February 4, 2015

Getting start Google Maps in Android

Google maps is very popular in these days. So most of mobile apps use Google maps to server their customers. In this tutorial I’m going to demonstrate how to use Google maps for your android app using Google service
 1)   Step is to add Google play serves to your android adt bundle.

Open Eclipse Windows Android SDK Manager
 Go to Android SDK Manager and click and check you have Google play serves with your adt bundle. If not you have to download it.
2)   Like that way you have to check your adt bundle contain
To check you have to select Obsolete  tick on your android sdk manager window . If not you have to install that also
 If you done now your ready to get privet key from Google services to your android application.

3)   Then go to the place where java install in your computer.
Program Files (x86)\Java\jre7\bin
Then “shift+right click” and open command prompt 
Then type like this
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

then you have to copy the SHA1 that your prompt from the cmd.

5) Then go to the API & AUTH -> APIs and on the Google Maps Android API v2 and Translate API



6)   Then goto

APIs & auth -> Credentials -> public api access ->create new key -> android key
7)Then enter your SHA1 key ; android project name

After you completing typing click the create button
Then google provide a api key  

Copy the API Key. Late you need that.

8) then Create a work place for the project
In Eclipse goto File Import Android Existing Android Code Into Workspace
9. Click on Browse and select Google Play Services project from your android sdk folder. You can locate play services library project from
android-sdk-windows\extras\google\google_play_services\libproject\google-play-services_lib
10. Importantly while importing check Copy projects into workspace option as shown in the below image.
11. In Eclipse create a new project by going to File New Android Application Project and fill required details. I kept my project name as Google Maps V2 and package name
12. Now we need to use Google Play Services project as a library to use project. So right click on project and select properties. In the properties window on left side select Android. On the right you can see Add button under library section. Click it and select google play services project which we imported previously.
 13)
14)
15)at last your workplace is display like this.
16) Then you need to give permission in manifest file
<!-- Goolge API Key -->
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyAo7D5KmWcB8hdw6QZ_GNz5BSDLejlv6m0" />
<--add your api here as android:value -->
      

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
<!-- Required OpenGL ES 2.0. for Maps V2 -->
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />


17)Setup map
New google maps are implemented using MapFragments which is a sub class of Fragmentsclass. Open your main activity layout file activity_main.xml file and add following code. I usedRelativeLayout as a parent element. You can remove it and use MapFragment directly.

XML

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

JAVA CODE

MainActivity.java
public class MainActivity extends Activity {

    // Google Map
    private GoogleMap googleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            // Loading map
            initilizeMap();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * function to load map. If map is not created it will create it for you
     * */
    private void initilizeMap() {
        if (googleMap == null) {
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();

            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initilizeMap();
    }

}



MAP Properties



Showing Current Location
You can show user’s current location on the map by calling setMyLocationEnabled(). Pass true / false to enable or disable this feature
googleMap.setMyLocationEnabled(true); // false to disable

Zooming Buttons
You can call setZoomControlsEnabled() function to get rid of those zooming controls on the map. By disabling these buttons map zooming functionality still work by pinching gesture.
googleMap.getUiSettings().setZoomControlsEnabled(false); // true to enable

Zooming Functionality
You can disable zooming gesture functionality by calling setZoomGesturesEnabled()
googleMap.getUiSettings().setZoomGesturesEnabled(false);

Compass Functionality
Compass can be disabled by calling setCompassEnabled() function
googleMap.getUiSettings().setCompassEnabled(true);

My Location Button
My location button will be used to move map to your current location. This button can be shown / hidden by calling setMyLocationButtonEnabled() function
googleMap.getUiSettings().setMyLocationButtonEnabled(true);

Map Rotate Gesture
My rotate gesture can be enabled or disabled by calling setRotateGesturesEnabled() method
googleMap.getUiSettings().setRotateGesturesEnabled(true);
Although google maps provides lot of other features, I covered only basic topics in this tutorial. Remaining topics seems to be pretty much lengthy, so I’ll post them as separate articles.

Changing Map Type
Google provides 4 kinds of map types NormalHybridSatellite and Terrain. You can toggle to any kind of map using googleMap.setMapType() method.
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);

Custom Marker Icon
Apart from maps native marker icons, you can use own image to show as a marker. You can load the icon from any kind of supported sources.
fromAsset(String assetName) – Loading from assets folder
fromBitmap (Bitmap image) – Loading bitmap image
fromFile (String path) – Loading from file
fromResource (int resourceId) – Loading from drawable resource

// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;

// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");

// Changing marker icon
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.my_marker_icon)));

// adding marker
googleMap.addMarker(marker);

Moving Camera to a Location with animation
You may want to move camera to a particular position. Google maps provides set of functions to achieve this.
CameraPosition cameraPosition = new CameraPosition.Builder().target(
                new LatLng(17.385044, 78.486671)).zoom(12).build();

googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));


Following are enhancements and features that google maps provides. You can utilize these features which suites to your requirements.

Changing Marker Color
By default map marker color will be RED. Google maps provides some set of predefined colored icons for the marker.
// ROSE color icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

// GREEN color icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));


Placing a Marker
You can place a marker on the map by using following code.
// latitude and longitude
double latitude = ;
double longitude = ;

// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps ");

// adding marker
googleMap.addMarker(marker);




Create Application to get current location & draw the shortest path for the provided location from the current location
For this first we have to create two java class call GPSTracker and GMapV2Direction

GMapV2Direction java class



import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.google.android.gms.maps.model.LatLng;


import android.util.Log;

public class GMapV2Direction {
       
      public final static String MODE_DRIVING = "driving";
      public final static String MODE_WALKING = "walking";
     
      public GMapV2Direction() { }
     
     
      public Document getDocument(LatLng start, LatLng end, String mode) {
            String url = "http://maps.googleapis.com/maps/api/directions/xml?"
                  + "origin=" + start.latitude + "," + start.longitude 
                  + "&destination=" + end.latitude + "," + end.longitude
                  + "&sensor=false&units=metric&mode=driving";
           
            Log.d("GoogleMapsDirection", url);
        try {
           
            HttpClient httpClient = new DefaultHttpClient();
           
            HttpContext localContext = new BasicHttpContext();
           
            HttpPost httpPost = new HttpPost(url);
           
           
            //execute in  request in http cilent
            System.out.println("a"+httpPost);
            System.out.println("b"+localContext);
            HttpResponse response = httpClient.execute(httpPost, localContext);
           
            //sent or received http msg
           
            InputStream in = response.getEntity().getContent();
            System.out.println("c"+in);
            //enables application to obtain paser that produse DOM object tree from XML
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            System.out.println("d"+builder);
            Document doc = builder.parse(in);
            System.out.println("e"+doc);
            return doc;
        } catch (Exception e) {
            e.printStackTrace();
        }
            return null;
      }
     
      public String getDurationText (Document doc) {
            NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
       
        Log.i("DurationText", node2.getTextContent());
            return node2.getTextContent();
      }
     
      public int getDurationValue (Document doc) {
            NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        Log.i("DurationValue", node2.getTextContent());
            return Integer.parseInt(node2.getTextContent());
      }
     
      public String getDistanceText (Document doc) {
            NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        Log.i("DistanceText", node2.getTextContent());
            return node2.getTextContent();
      }
     
      public int getDistanceValue (Document doc) {
            NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        Log.i("DistanceValue", node2.getTextContent());
            return Integer.parseInt(node2.getTextContent());
      }
     
      public String getStartAddress (Document doc) {
            NodeList nl1 = doc.getElementsByTagName("start_address");
        Node node1 = nl1.item(0);
        Log.i("StartAddress", node1.getTextContent());
            return node1.getTextContent();
      }
     
      public String getEndAddress (Document doc) {
            NodeList nl1 = doc.getElementsByTagName("end_address");
        Node node1 = nl1.item(0);
        Log.i("StartAddress", node1.getTextContent());
            return node1.getTextContent();
      }
     
      public String getCopyRights (Document doc) {
            NodeList nl1 = doc.getElementsByTagName("copyrights");
        Node node1 = nl1.item(0);
        Log.i("CopyRights", node1.getTextContent());
            return node1.getTextContent();
      }
     
      //decode the received String in http mssage to geopints

                  //Google provides the routing results as an encoded polylines format
      public ArrayList<LatLng> getDirection (Document doc) {
            NodeList nl1, nl2, nl3;
        ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
        nl1 = doc.getElementsByTagName("step");
        if (nl1.getLength() > 0) {
            for (int i = 0; i < nl1.getLength(); i++) {
                Node node1 = nl1.item(i);
                nl2 = node1.getChildNodes();

                Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
                nl3 = locationNode.getChildNodes();
                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
                double lat = Double.parseDouble(latNode.getTextContent());
                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                double lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));

                locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "points"));
                ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
                for(int j = 0 ; j < arr.size() ; j++) {
                  listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
                }

                locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "lat"));
                lat = Double.parseDouble(latNode.getTextContent());
                lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));
            }
        }
       
        return listGeopoints;
      }
     
      private int getNodeIndex(NodeList nl, String nodename) {
            for(int i = 0 ; i < nl.getLength() ; i++) {
                  if(nl.item(i).getNodeName().equals(nodename))
                        return i;
            }
            return -1;
      }
     
      private ArrayList<LatLng> decodePoly(String encoded) {
            ArrayList<LatLng> poly = new ArrayList<LatLng>();
            int index = 0, len = encoded.length();
            int lat = 0, lng = 0;
            while (index < len) {
                  int b, shift = 0, result = 0;
                  do {
                        b = encoded.charAt(index++) - 63;
                        result |= (b & 0x1f) << shift;
                        shift += 5;
                  } while (b >= 0x20);
                  int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
                  lat += dlat;
                  shift = 0;
                  result = 0;
                  do {
                        b = encoded.charAt(index++) - 63;
                        result |= (b & 0x1f) << shift;
                        shift += 5;
                  } while (b >= 0x20);
                  int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
                  lng += dlng;
                 
                  LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
                  poly.add(position);
            }
            return poly;
      }
}


GPSTracker java class

package com.ISURU.testmapper;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

      private final Context mContext;

      // flag for GPS status
      boolean isGPSEnabled = false;

      // flag for network status
      boolean isNetworkEnabled = false;

      // flag for GPS status
      boolean canGetLocation = false;

      Location location; // location
      double latitude; // latitude
      double longitude; // longitude

      // The minimum distance to change Updates in meters
      private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

      // The minimum time between updates in milliseconds
      private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

      // Declaring a Location Manager
      protected LocationManager locationManager;

      public GPSTracker(Context context) {
            this.mContext = context;
            getLocation();
      }

      public Location getLocation() {
            try {
                  locationManager = (LocationManager) mContext
                              .getSystemService(LOCATION_SERVICE);

                  // getting GPS status(name of loaction provider'gps'(constant))
                  isGPSEnabled = locationManager
                              .isProviderEnabled(LocationManager.GPS_PROVIDER);

                  // getting network status
                  isNetworkEnabled = locationManager
                              .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                  if (!isGPSEnabled && !isNetworkEnabled) {
                        // no network provider is enabled
                  }
                  else {
                        this.canGetLocation = true;
                        if (isNetworkEnabled) {
                              locationManager.requestLocationUpdates(
                                          LocationManager.NETWORK_PROVIDER,
                                          MIN_TIME_BW_UPDATES,
                                          MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                              Log.d("Network", "Network");
                              if (locationManager != null) {
                                    location = locationManager
                                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                                    if (location != null) {
                                          latitude = location.getLatitude();
                                          longitude = location.getLongitude();
                                    }
                              }
                        }
                        // if GPS Enabled get lat/long using GPS Services
                        if (isGPSEnabled) {
                              if (location == null) {
                                    locationManager.requestLocationUpdates(
                                                LocationManager.GPS_PROVIDER,
                                                MIN_TIME_BW_UPDATES,
                                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                                    Log.d("GPS Enabled", "GPS Enabled");
                                    if (locationManager != null) {
                                          location = locationManager
                                                      .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                          if (location != null) {
                                                latitude = location.getLatitude();
                                                longitude = location.getLongitude();
                                          }
                                    }
                              }
                        }
                  }

            } catch (Exception e) {
                  e.printStackTrace();
            }

            return location;
      }
     
      //what to do when no gps
      public void stopUsingGPS(){
            if(locationManager != null){
                  locationManager.removeUpdates(GPSTracker.this);
            }          
      }
     
     
      public double getLatitude(){
            if(location != null){
                  latitude = location.getLatitude();
            }
           
            // return latitude
            return latitude;
      }
     
     
      public double getLongitude(){
            if(location != null){
                  longitude = location.getLongitude();
            }
           
            // return longitude
            return longitude;
      }
     
      //find gps N wifi anable
      public boolean canGetLocation() {
            return this.canGetLocation;
      }
     
      //show alerts
      public void showSettingsAlert(){
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
       
        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                  Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                  //acsess to the settings option
                  mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
      }

      @Override
      public void onLocationChanged(Location location) {
      }

      @Override
      public void onProviderDisabled(String provider) {
      }

      @Override
      public void onProviderEnabled(String provider) {
      }

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

      @Override
      public IBinder onBind(Intent arg0) {
            return null;
      }

}

Then we want to create the UI with one fragment for load the map and two buttons to get the location and draw the path

XML File



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
   
<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.MapFragment"
    android:layout_width="match_parent"
    android:layout_height="354dp"
    android:layout_above="@+id/editText1"
    android:layout_alignParentTop="true"
    android:layout_x="-2dp"
    android:layout_y="1dp" />

<Button
    android:id="@+id/button2"
    android:layout_width="162dp"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:text="Draw Location" />

<Button
    android:id="@+id/button1"
    android:layout_width="161dp"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:text="Get Location" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/button2"
    android:layout_alignParentLeft="true"
    android:ems="10" />
   
</RelativeLayout>


Then the java file

package com.ISURU.testmapper;

import android.app.Activity;
import android.os.Bundle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Document;

import com.google.android.gms.internal.in;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class GetLocation extends Activity{
     
      private GoogleMap googleMap;
      MarkerOptions markerOptions;
      LatLng fromlatlng;
      private Double latitude1;
      private Double longitude1;
      private BufferedReader in;
      LatLng toPosition ;
      EditText destination;
     
     
      public static double longt;
      public static double lati;
     
      // GPSTracker class
      GPSTracker gps;
      GoogleMap mMap;
    GMapV2Direction md;
    Button getloc,drawloc;
    LatLng fromPosition ;
     
    private class DoAsyncTask extends AsyncTask<URL, Integer, Long> {///Constructor

            String lat,lon,temp;
            String locName=destination.getText().toString();
           
            protected Long doInBackground(URL... params) {//callbackmethod
     
     
            // TODO Auto-generated method stub

            String addressUrl = "http://maps.googleapis.com/maps/api/geocode/json?address="
                            + locName
                            + "&sensor=true";
            try {
                 
                        HttpClient httpClient = new DefaultHttpClient();// Client

                        HttpGet getRequest = new HttpGet();
                        getRequest.setURI(new URI(addressUrl));

                        // HttpPost postRequest = new HttpPost();
                        // postRequest.setURI(new URI(url));

                        HttpResponse response = httpClient.execute(getRequest);
                        in = new BufferedReader(new InputStreamReader(response
                                .getEntity().getContent()));
                        StringBuffer sb = new StringBuffer("");
                        String line = "";
                        String NL = System.getProperty("line.separator");
                        while ((line = in.readLine()) != null) {
                            sb.append(line + NL);
                        }
                        in.close();
                        String page = sb.toString();
                       
                        //mylon.setText(page);
                        JSONObject jsonObject = new JSONObject(page);
                        if (jsonObject.has("results")) {
                            JSONArray jsonArray = (JSONArray) jsonObject.get("results");
                            //mylon.setText(locName);

                            if (jsonArray.length() > 0) {
                                jsonObject = (JSONObject) jsonArray.get(0);
                                if (jsonObject.has("geometry")) {
                                    jsonObject = (JSONObject) jsonObject
                                            .get("geometry");

                                    if (jsonObject.has("location")) {
                                        JSONObject location = (JSONObject) jsonObject
                                                .get("location");

                                        latitude1 = (Double) location.get("lat");
                                        longitude1 = (Double) location.get("lng");
                                                                                  
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                     
                    } finally {
                        if (in != null) {
                            try {
                                in.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

            return null;
      }

      @Override
            protected void onPostExecute(Long result) {
            // TODO Auto-generated method stub
           
            //interact with gui only here#######################################
            Log.e(locName,latitude1+""+longitude1);
            toPosition = new LatLng(latitude1,longitude1);
            Log.e("to",""+toPosition);
           
            draw();
      }

      @Override
            protected void onPreExecute() {
           
            // TODO Auto-generated method stub
                       
            locName=destination.getText().toString();
                  Log.e("Name", locName);
      }
    
}    
     
    public Document getDocument(LatLng start, LatLng end, String mode) {
     
            String url = "http://maps.googleapis.com/maps/api/directions/xml?"
                  + "origin=" + start.latitude + "," + start.longitude 
                  + "&destination=" + end.latitude + "," + end.longitude
                  + "&sensor=false&units=metric&mode=driving";
           
            Log.d("GoogleMapsDirection", url);
        try {
           
            HttpClient httpClient = new DefaultHttpClient();
           
            HttpContext localContext = new BasicHttpContext();
           
            HttpPost httpPost = new HttpPost(url);
           
           
            //execute in  request in http cilent
            Log.d("httpPost", url);
            Log.d("localContext",""+ localContext);
            HttpResponse response = httpClient.execute(httpPost, localContext);
            Log.d("response",""+ response);
            //sent or received http msg
           
            InputStream in = response.getEntity().getContent();
            Log.d("in",""+ in);
            //enables application to obtain paser that produse DOM object tree from XML
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
          
            Log.d("builder",""+ builder);
            Document doc = builder.parse(in);
          
            Log.d("doc",""+ doc);
            return doc;
        } catch (Exception e) {
            e.printStackTrace();
        }
            return null;
      }
     
    public void draw()
      {
      Log.e("from",""+fromPosition);
      Log.e("to",""+toPosition);
            mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start"));
            mMap.addMarker(new MarkerOptions().position(toPosition).title("End"));
           
            //Document doc = md.getDocument(fromPosition, toPosition, GMapV2Direction.MODE_DRIVING);
            Document doc = getDocument(fromPosition, toPosition, GMapV2Direction.MODE_DRIVING);
            Log.e("md",""+md);
            Log.e("mMap",""+mMap);
            Log.e("doc",""+doc);
            ArrayList<LatLng> directionPoint = md.getDirection(doc);
            PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
           
            for(int i = 0 ; i < directionPoint.size() ; i++) {               
                  rectLine.add(directionPoint.get(i));
                  //directionPoint the array returned by the decodePoly method are stored
            }
           
            mMap.addPolyline(rectLine);
      }
     
   
      @TargetApi(Build.VERSION_CODES.HONEYCOMB)
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.getlocation);
       
        getloc=(Button)findViewById(R.id.button1);
            drawloc=(Button)findViewById(R.id.button2);
            destination = (EditText)findViewById(R.id.editText1);
            Log.e("i'm look ing @2","ggggggggg");
             md = new GMapV2Direction();
             //load the default map to web view
                  mMap = ((MapFragment)getFragmentManager().findFragmentById(
                    R.id.map)).getMap();
        
                  getloc.setOnClickListener(new View.OnClickListener() {
                       
                        @Override
                        public void onClick(View v) {
                              // TODO Auto-generated method stub
                              // create class object 
                          gps = new GPSTracker(GetLocation.this);

                              // check if GPS enabled      
                          if(gps.canGetLocation()){
                             
                              double latitude = gps.getLatitude();
                              double longitude = gps.getLongitude();
                             
                              longt = longitude;
                              lati = latitude;
                              Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();   
                             
                             
                              fromPosition=new LatLng(latitude,longitude);
                                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(fromPosition, 16));
                              mMap.setMyLocationEnabled(true);
                          }else{
                             
                              gps.showSettingsAlert();
                          }
                             
                        }
                  });
                   
                             
                  drawloc.setOnClickListener(new View.OnClickListener() {
                       
                        @Override
                        public void onClick(View v) {
                              // TODO Auto-generated method stub
                              new DoAsyncTask().execute();
                        }
                  });
                 
       
      }

}








No comments:

Post a Comment