Thursday, 12 April 2012

source to destination path in map

package com.qualcomm.QCARSamples.ImageTargets;

/**
* Google Maps Tutorial
* Txt2Java pCode Generated File
* Version 1.0.1.4
* B&P Software 2011
*
* This requires the Google API (Android 2.1)
* The mapping requires the correct API key in main.xml (B&P's won't work for other compilers)
* Uses the direction service to draw a blue line between the endpoints of the direction steps
* Stores the written directions also
*
*/

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.hardware.SensorListener;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
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.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import android.view.View.OnClickListener;

public class Mapper extends MapActivity implements LocationListener,
SensorListener {
MapView mapView;
MapController mc;
GeoPoint p;
ArrayList directions = new ArrayList();
Direction source_dir = null, dest = null;
TextView place;
EditText place_et;
String destination;
double lat, lng;
String source;
boolean flag_online = false;
private LocationManager locationManager;
private String provider;

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.navigate);
mapView = (MapView) findViewById(R.id.mapview);
int height = getWindowManager().getDefaultDisplay().getHeight();
int width = getWindowManager().getDefaultDisplay().getWidth();
LinearLayout main = (LinearLayout) findViewById(R.id.main);
main.getLayoutParams().height = (int) ((height) * 0.90);

place = (TextView) findViewById(R.id.place);
place_et = (EditText) findViewById(R.id.place_et);

source = "ahmedabad";
destination = "vadodara,gujarat";
destination = place_et.getText().toString();
Button gps = (Button) findViewById(R.id.gps);
gps.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// if (flag_online == false) {
// String coordinates[] = { "42.35849", "-71.06010" };
// lat = Double.parseDouble(coordinates[0]);
// lng = Double.parseDouble(coordinates[1]);
// p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
// place.setText("Name of Place" + " Ahmedabad");
// getDirections("http://maps.googleapis.com/maps/api/directions/json?origin="
// + source
// + "&destination="
// + "vadodara,gujarat"
// + "&sensor=false");
//
//
// goToPoint();
// showPosition();
// flag_online = true;
// } else if (isConnected() == true) {
destination = place_et.getText().toString();

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin
// provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager
.getLastKnownLocation(provider);

// Initialize the location fields
String coordinates[] = { "42.35849", "-71.06010" };
lat = Double.parseDouble(coordinates[0]);
lng = Double.parseDouble(coordinates[1]);

if (location != null) {
System.out.println("Provider " + provider
+ " has been selected.");
String lat1 = " " + (double) (location.getLatitude());
String lng1 = " " + (double) (location.getLongitude());
lat = Double.parseDouble(lat1);
lng = Double.parseDouble(lng1);

} else {

Toast.makeText(getApplicationContext(),
"Provider not available", 4000).show();
}
onLocationChanged(location);
getAddress();

p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
place.setText("Name of Place" + " " + source);
source_dir = new Direction(lat, lng, "s");
// dest = new Direction(20.25,
// 65.70, "d");
//
directions.clear();
directions.add(source_dir);
// source.replaceAll(" ", "");

getDirections_online("http://maps.googleapis.com/maps/api/directions/json?origin="
+ source
+ "&destination="
+ destination
+ "&sensor=false");

// directions.add(dest);
goToPoint();
showPosition();

// }
}
});

TabHost tabH = new TabHost(this);
TabWidget tabWidget = new TabWidget(this);
LinearLayout lin = new LinearLayout(this);
lin.setOrientation(LinearLayout.HORIZONTAL);
tabWidget.setId(android.R.id.tabs);
tabH.addView(tabWidget);
tabH.addView(lin);
FrameLayout fl = new FrameLayout(this);
fl.setId(android.R.id.tabcontent);
fl.setPadding(0, (int) (getWindowManager().getDefaultDisplay()
.getHeight() * 0.92), 0, 0);
lin.addView(fl);
tabH.setup();
// android.widget.TabHost.TabSpec ts1 = tabH.newTabSpec("hi");

tabH.addTab(tabH.newTabSpec("tag")

.setIndicator("").setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
// -- this tab contains multiple control grouped in a panel --
// //
LinearLayout panel = new LinearLayout(Mapper.this);
panel.setOrientation(LinearLayout.HORIZONTAL);
ImageView iv = new ImageView(Mapper.this);
iv.setBackgroundResource(R.drawable.icon_vuforia);
ImageView i1 = new ImageView(Mapper.this);
i1.setBackgroundResource(R.drawable.icon_vuforia);
ImageView i2 = new ImageView(Mapper.this);
i2.setBackgroundResource(R.drawable.icon_vuforia);
ImageView i3 = new ImageView(Mapper.this);
i3.setBackgroundResource(R.drawable.icon_vuforia);
ImageView i4 = new ImageView(Mapper.this);
i4.setBackgroundResource(R.drawable.icon_vuforia);

panel.addView(i1);
panel.addView(i2);
panel.addView(i3);
panel.addView(i4);
panel.addView(iv);
i1.getLayoutParams().width = getWindowManager()
.getDefaultDisplay().getWidth() / 5;
i2.getLayoutParams().width = getWindowManager()
.getDefaultDisplay().getWidth() / 5;
i3.getLayoutParams().width = getWindowManager()
.getDefaultDisplay().getWidth() / 5;
i4.getLayoutParams().width = getWindowManager()
.getDefaultDisplay().getWidth() / 5;
iv.getLayoutParams().width = getWindowManager()
.getDefaultDisplay().getWidth() / 5;
return panel;
} // TAB 1 done
}));
// ts1.setContent(new Intent(this,Tab1.class));
// tabH.addTab(ts1);
tabH.getTabWidget().getChildAt(0).getLayoutParams().height = (int) 0.000000001;
tabH.getTabWidget().getChildAt(0).getLayoutParams().width = (int) 0.0000000001;

LinearLayout.LayoutParams tab = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM);

// tab.setMargins(0,(int)
// (getWindowManager().getDefaultDisplay().getHeight()*0.8) , 0, 0);
addContentView(tabH, tab);

// getDirections("http://maps.googleapis.com/maps/api/directions/json?origin=Ahmedabad,Gujarat&destination=Vadodara,Gujarat&sensor=false");

mapView.setBuiltInZoomControls(true); // newer one

// This sets up where to show a push pin

// This gets everything going
// goToPoint();
// showPosition();

}// oncreate

@Override
protected boolean isRouteDisplayed() {
return true;
}// isroutedisplayed

public boolean isConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null;

}

// This moves the map center to point p
public void goToPoint() {
int cx = (int) (((directions.get(0).lat + directions.get(directions
.size() - 1).lat) / 2d) * 1E6);
int cy = (int) (((directions.get(0).lng + directions.get(directions
.size() - 1).lng) / 2d) * 1E6);
GeoPoint gp = new GeoPoint(cx, cy);
int latSpan = (int) (Math.abs(directions.get(0).lat
- directions.get(directions.size() - 1).lat) * 1E6);
int lngSpan = (int) (Math.abs(directions.get(0).lng
- directions.get(directions.size() - 1).lng) * 1E6);
mc = mapView.getController();
mc.zoomToSpan(latSpan, lngSpan);
mc.animateTo(gp);

}// goto

// This shows the pushpin at point p
public void showPosition() {
MapOverlay mapOverlay = new MapOverlay();
List listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}// showpos

class MapOverlay extends Overlay {

@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(5);

Point screenPts = new Point();
GeoPoint gp;
int i = 0;
float lx = 0;
float ly = 0;
while (i < directions.size()) { dest = directions.get(i); gp = new GeoPoint((int) (dest.lat * 1E6), (int) (dest.lng * 1E6)); mapView.getProjection().toPixels(gp, screenPts); if (i > 0)
canvas.drawLine(lx, ly, screenPts.x, screenPts.y, paint);
lx = screenPts.x;
ly = screenPts.y;
i++;
}// drawing route

mapView.getProjection().toPixels(p, screenPts);

// This puts the marker on the map
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.pushpin);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 46, null);
return true;
}

@Override
public boolean onTouchEvent(MotionEvent event, MapView mapView) {
// Touch event
// When the map is pressed and released the pushpin goes
// to that point
if (event.getAction() == 1) {
p = mapView.getProjection().fromPixels((int) event.getX(),
(int) event.getY());
directions.clear();
source_dir = new Direction(lat, lng, "s");
// dest = new Direction(20.25,
// 65.70, "d");
//
directions.add(source_dir);
// source.replaceAll(" ", "");
getDirections_online("http://maps.googleapis.com/maps/api/directions/json?origin="
+ source
+ "&destination="
+ destination
+ "&sensor=false");

// directions.add(dest);

goToPoint();
showPosition();
}// if
return false;
}// ontouch

}// mapoverlay class

// http://maps.googleapis.com/maps/api/directions/output?parameters
// http://maps.googleapis.com/maps/api/directions/json?origin=Boston,MA&destination=Concord,MA&sensor=false

public void getDirections(String loginUrl) {
JSONObject jArray = null;
String result = "";
String s;
String s1;
String s2;
directions.clear();

try {
HttpGet request = new HttpGet(loginUrl);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity entityResponse = response.getEntity();
result = EntityUtils.toString(entityResponse);

} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}

try {
JSONArray array = jArray.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONArray legs1 = steps.getJSONArray("steps");
for (int i = 0; i < legs1.length(); i++) { JSONObject steps1 = legs1.getJSONObject(i); if (i == 0) s = steps1.getString("start_location"); else s = steps1.getString("end_location"); // Toast.makeText(getApplicationContext(), " "+s, 6000).show(); s1 = s.substring(s.indexOf(":") + 1); // cut off beginning s = s1.substring(s1.indexOf(":") + 1, s1.indexOf("}")); // isolate // longitude s1 = s1.substring(0, s1.indexOf(",")); // isolate latitude s.replaceAll(" ", ""); // remove spaces s1.replaceAll(" ", ""); s2 = steps1.getString("html_instructions"); // Toast.makeText(getApplicationContext(), ""+s2, 4000).show(); source_dir = new Direction(Double.parseDouble(s), Double.parseDouble(s1), s2); directions.add(source_dir); }// for } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } }// getdirections public void getDirections_online(String loginUrl) { JSONObject jArray = null; String result = ""; String s; String s1; String s2; // directions.clear(); try { HttpGet request = new HttpGet(loginUrl); HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); HttpEntity entityResponse = response.getEntity(); result = EntityUtils.toString(entityResponse); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { jArray = new JSONObject(result); } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } try { JSONArray array = jArray.getJSONArray("routes"); JSONObject routes = array.getJSONObject(0); JSONArray legs = routes.getJSONArray("legs"); JSONObject steps = legs.getJSONObject(0); JSONArray legs1 = steps.getJSONArray("steps"); for (int i = 0; i < legs1.length(); i++) { JSONObject steps1 = legs1.getJSONObject(i); /* * if (i == 0) s = steps1.getString("start_location"); else */ s = steps1.getString("end_location"); // Toast.makeText(getApplicationContext(), " "+s, 6000).show(); s1 = s.substring(s.indexOf(":") + 1); // cut off beginning s = s1.substring(s1.indexOf(":") + 1, s1.indexOf("}")); // isolate // longitude s1 = s1.substring(0, s1.indexOf(",")); // isolate latitude s.replaceAll(" ", ""); // remove spaces s1.replaceAll(" ", ""); s2 = steps1.getString("html_instructions"); // Toast.makeText(getApplicationContext(), ""+s2, 4000).show(); dest = new Direction(Double.parseDouble(s), Double.parseDouble(s1), s2); directions.add(dest); }// for } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } }// getdirections void getAddress() { try { Geocoder gcd = new Geocoder(this, Locale.getDefault()); List
addresses = gcd.getFromLocation(lat, lng, 5);

if (addresses.size() > 0) {
/*
* for (int i = 0; i < addresses.size(); i++) { Address address
* = addresses.get(i);
*
* int maxIndex = address.getMaxAddressLineIndex(); for (int x =
* 0; x <= maxIndex; x++) {
* result.append(address.getAddressLine(x)); result.append(",");
* } result.append(address.getLocality()); result.append(",");
* result.append(address.getPostalCode());
* result.append("\n\n"); }
*/
Address address = addresses.get(0);

String source1 = address.getAddressLine(1);
source = source1.substring(0, source1.indexOf(",") );

//Toast.makeText(getApplicationContext(), source, 4000).show();
// result.append("" + lat + lng);

}
} catch (IOException ex) {
// editTextShowLocation.append(ex.getMessage().toString());
} catch (NullPointerException f) {

}
}

public class Direction {
public double lng = 0;
public double lat = 0;
public String txt = "";

public Direction(double latitude, double longitude, String written) {
lng = longitude;
lat = latitude;
txt = written;
}// constructor

}// direction class

@Override
public void onAccuracyChanged(int arg0, int arg1) {
// TODO Auto-generated method stub

}

@Override
public void onSensorChanged(int sensor, float[] values) {
// TODO Auto-generated method stub

}

@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
String lat1 = " " + (double) (location.getLatitude());
String lng1 = " " + (double) (location.getLongitude());
lat = Double.parseDouble(lat1);
lng = Double.parseDouble(lng1);

p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
place.setText("Name of Place" + " Ahmedabad");
getAddress();
directions.clear();
source_dir = new Direction(lat, lng, "s");
// dest = new Direction(20.25,
// 65.70, "d");
//
directions.add(source_dir);
// source.replaceAll(" ", "");
getDirections_online("http://maps.googleapis.com/maps/api/directions/json?origin="
+ source + "&destination=" + destination + "&sensor=false");

// directions.add(dest);

goToPoint();
showPosition();
// Toast.makeText(getApplicationContext(), source + destination, 4000)
// .show();
}

@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub

}
// TODO: Fill In Methods Etc.
}// class

3 comments:

  1. May I get complete code of it(including xml and manifest,xml )

    ReplyDelete
  2. May I get complete code of it(including xml and manifest,xml )

    ReplyDelete
  3. May I get complete code of it(including xml and manifest,xml thnks

    ReplyDelete