Thursday 7 June 2012

Mapper.java(urhre)


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.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
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.view.ViewGroup.MarginLayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
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<Direction> directions = new ArrayList<Direction>();
Direction source_dir = null, dest = null;
EditText place;
EditText place_et;
String destination;
double lat, lng;
String source;
boolean flag_online = false;
private LocationManager locationManager;
private String provider;
int height, width;
ImageView i1, i2, i3, i4;
ProgressDialog dialog;
Button home, back, exchange;
String temp;
int flag_firsttime = 1;

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.navigate);
mapView = (MapView) findViewById(R.id.mapview);
this.mapView = (MapView) findViewById(R.id.mapview);
double l1 = 22.97884;
double l2 = 72.49037;

GeoPoint point = new GeoPoint((int) (l1 * 1E6), (int) (l2 * 1E6));
this.mapView.getController().animateTo(point);

height = getWindowManager().getDefaultDisplay().getHeight();
width = getWindowManager().getDefaultDisplay().getWidth();
LinearLayout main = (LinearLayout) findViewById(R.id.main);
main.getLayoutParams().height = (int) ((height) * 0.90);

place = (EditText) findViewById(R.id.place);
place_et = (EditText) findViewById(R.id.place_et);
home = (Button) findViewById(R.id.home);
exchange = (Button) findViewById(R.id.exchange);
back = (Button) findViewById(R.id.back);
source = "Wait..... ";
destination = "surat,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) {
if (isConnected()) {

String destination1 = place_et.getText().toString();
destination = destination1.replaceAll("\\s", "");

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(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.trim()
+ "&destination="
+ destination.trim() + "&sensor=false");

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

} else {
Toast.makeText(getApplicationContext(),
"no internet connection", 4000).show();
}
}
});

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.90), 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);

panel.setBackgroundResource(R.drawable.bottom_bar);
i1 = new ImageView(Mapper.this);
i1.setBackgroundResource(R.drawable.map_file);
i2 = new ImageView(Mapper.this);
i2.setBackgroundResource(R.drawable.urhere_file);

i3 = new ImageView(Mapper.this);
i3.setBackgroundResource(R.drawable.navigate_file);

i4 = new ImageView(Mapper.this);
i4.setBackgroundResource(R.drawable.arroundme_file);

panel.addView(i1);
panel.addView(i2);
panel.addView(i3);
panel.addView(i4);

// i1.getLayoutParams().width = getWindowManager()
// .getDefaultDisplay().getWidth() / 4;
// i2.getLayoutParams().width = getWindowManager()
// .getDefaultDisplay().getWidth() / 4;
// i3.getLayoutParams().width = getWindowManager()
// .getDefaultDisplay().getWidth() / 4;
// i4.getLayoutParams().width = getWindowManager()
// .getDefaultDisplay().getWidth() / 4;

MarginLayoutParams marginParams_i1 = new MarginLayoutParams(i1
.getLayoutParams());
if (height >= 800) {
marginParams_i1.setMargins(12, 0, 12, 0);

} else if (height < 480) {
marginParams_i1.setMargins(8, 0, 8, 0);
} else {

marginParams_i1.setMargins(12, 0, 12, 0);
}
LinearLayout.LayoutParams layoutParams_i1 = new LinearLayout.LayoutParams(
marginParams_i1);
i1.setLayoutParams(layoutParams_i1);

MarginLayoutParams marginParams_i2 = new MarginLayoutParams(i2
.getLayoutParams());
if (height >= 800) {
marginParams_i2.setMargins(12, 0, 12, 0);

} else if (height < 480) {
marginParams_i2.setMargins(8, 0, 8, 0);
} else {
marginParams_i2.setMargins(12, 0, 12, 0);
}
LinearLayout.LayoutParams layoutParams_i2 = new LinearLayout.LayoutParams(
marginParams_i2);
i2.setLayoutParams(layoutParams_i2);

MarginLayoutParams marginParams_i3 = new MarginLayoutParams(i3
.getLayoutParams());
if (height >= 800) {
marginParams_i3.setMargins(12, 0, 12, 0);

} else if (height < 480) {
marginParams_i3.setMargins(8, 0, 8, 0);
} else {
marginParams_i3.setMargins(12, 0, 12, 0);
}
LinearLayout.LayoutParams layoutParams_i3 = new LinearLayout.LayoutParams(
marginParams_i3);
i3.setLayoutParams(layoutParams_i3);

MarginLayoutParams marginParams_i4 = new MarginLayoutParams(i4
.getLayoutParams());
if (height >= 800) {
marginParams_i4.setMargins(12, 0, 12, 0);
} else if (height < 480) {
marginParams_i4.setMargins(8, 0, 8, 0);
} else {
marginParams_i4.setMargins(12, 0, 12, 0);
}
LinearLayout.LayoutParams layoutParams_i4 = new LinearLayout.LayoutParams(
marginParams_i4);
i4.setLayoutParams(layoutParams_i4);
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;

RelativeLayout.LayoutParams tab = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

// tab.setMargins(0,(int)
// (getWindowManager().getDefaultDisplay().getHeight()*0.8) , 0, 0);
addContentView(tabH, tab);
i1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// do whatever you need
Intent intent = new Intent(Mapper.this, Map.class);

startActivity(intent);
}
});

i2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// do whatever you need
// Intent intent = new Intent(Mapper.this, Mapper.class);
//
// startActivity(intent);
}
});
i3.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// do whatever you need
Intent intent = new Intent(Mapper.this,
navigateAllActivity.class);

startActivity(intent);
}
});
i4.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// do whatever you need
Intent intent = new Intent(Mapper.this,
AroundmeActivity.class);

startActivity(intent);
}
});


home.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// do whatever you need
Intent intent = new Intent(Mapper.this,
ZoomByEnterPageActivity.class);

startActivity(intent);
}
});
back.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// do whatever you need
Intent intent = new Intent(Mapper.this,
ZoomByEnterPageActivity.class);
Mapper.this.finish();

startActivity(intent);
}
});

exchange.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
if (isConnected()) {

if (flag_firsttime == 1) {

String destination1 = place_et.getText().toString();
destination = destination1.replaceAll("\\s", "");

// source = "vadodara";
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));
flag_firsttime = 0;
}

temp = source;
source = destination;
destination = temp;
place.setText(source);
place_et.setText(destination);
// source_dir = new Direction(lat, lng, "s");
// // dest = new Direction(20.25,
// // 65.70, "d");
// //
// directions.clear();
// directions.add(source_dir);
// // source.replaceAll(" ", "");

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

// directions.add(dest);
goToPoint();
showPosition();
} else {
Toast.makeText(getApplicationContext(),
"no internet connection", 4000).show();
}
}
});

// 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() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
} // This moves the map center to point p

// 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<Overlay> 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.trim()
+ "&destination="
+ destination.trim()
+ "&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<Address> 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("    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.trim()
+ "&destination="
+ destination.trim()
+ "&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

No comments:

Post a Comment