Draw Route on Android Map not working...? - android

I've been trying to work this piece of code for a week now. The route does not come up. My code is below.
I am trying to draw a route between two geopoints - the location which I'm retrieving from a web service.
My log doesn't show any error.
public class TesterGTC extends MapActivity {
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:2488/Service1.asmx";
private static final String METHOD_NAME1 = "lastKnownLocationAllValues";
private static final String SOAP_ACTION = NAMESPACE + METHOD_NAME1;
private List<Overlay> mapOverlays;
private Projection projection;
MapView mapView;
double latitude;
double longitude;
double endlat;
double endlong;
GeoPoint geoPoint;
MapController myMC;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // Suppress title bar to give more space
setContentView(R.layout.googletrackingclient);
final String orderID = GoogleTrackingMenu.epcID;
final String vehicleid = GoogleTrackingMenu.vehicleid;
Thread t = new Thread(new Runnable() {
public void run() {
String u = orderID;
String v = vehicleid;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
PropertyInfo propInfo = new PropertyInfo();
propInfo.name = "OID";
propInfo.type = PropertyInfo.STRING_CLASS;
request.addProperty(propInfo, u);
PropertyInfo propInfo2 = new PropertyInfo();
propInfo2.name = "vehicleID";
propInfo2.type = PropertyInfo.STRING_CLASS;
request.addProperty(propInfo2, v);
final TextView textview = (TextView) findViewById(R.id.id1);
final TextView myLoc = (TextView) findViewById(R.id.id2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
final ArrayList<EPCISGPSResult> resultList = new ArrayList<EPCISGPSResult>();
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
final SoapObject resultRequestSOAP = (SoapObject) envelope
.getResponse();
final int resultInt = resultRequestSOAP.getPropertyCount();
for (int i = 0; i < resultInt; i++) {
SoapObject resultRequest = (SoapObject) resultRequestSOAP
.getProperty(i);
String vehicleID = resultRequest.getProperty("vehicleID").toString();
String driverName = resultRequest.getProperty("driverName").toString();
String latitude = resultRequest.getProperty("latitude").toString();
String longitude = resultRequest.getProperty("longitude").toString();
String startVenue = resultRequest.getProperty("startVenue").toString();
String destination = resultRequest.getProperty("destination").toString();
String dateReceived = resultRequest.getProperty("dateReceived").toString();
String utc = resultRequest.getProperty("utc").toString();
String orderID = resultRequest.getProperty("orderID").toString();
EPCISGPSResult e = new EPCISGPSResult(vehicleID,driverName, latitude, longitude, startVenue,destination, dateReceived, utc, orderID);
resultList.add(e);
}
latitude = Double.parseDouble(resultList.get(0).getLatitude());
longitude = Double.parseDouble(resultList.get(0).getLongitude());
endlat = Double.parseDouble(resultList.get(resultList.size()-1).getLatitude());
endlong = Double.parseDouble(resultList.get(resultList.size()-1).getLongitude());
int beglat = (int)latitude* 1000000;
int endinglat = (int)endlat* 1000000;
int beglong = (int)longitude* 1000000;
int endinglong = (int)endlong* 1000000;
final GeoPoint gP1 = new GeoPoint(beglat, beglong);
final GeoPoint gP2 = new GeoPoint(endinglat, endinglong);
TesterGTC.this.runOnUiThread(new Runnable() {
public void run() {
int pointer = 0;
pointer = 1;
TextView tview = (TextView) findViewById(R.id.id1);
tview.setText("before map");
mapView = (MapView) findViewById(R.id.myGMap);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
myMC = mapView.getController();
myMC.setZoom(15);
int color = Color.RED;
mapOverlays = mapView.getOverlays();
projection = mapView.getProjection();
TextView txxview = (TextView) findViewById(R.id.id2);
txxview.setText("after map");
MyOverlay newO = new MyOverlay(gP1, gP2, color);
/* TextView textview = (TextView) findViewById(R.id.id1);
textview.setText("This is happening");*/
mapOverlays.add(newO);
} });
}
catch (final Exception e) {
TesterGTC.this.runOnUiThread(new Runnable() {
public void run() {
TextView textview = (TextView) findViewById(R.id.id1);
textview.setText("Your error is: " + e.getMessage().toString());
}
});
} finally {
}
}
});
t.start();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class MyOverlay extends Overlay{
GeoPoint gp1;
GeoPoint gp2;
int color;
public MyOverlay(GeoPoint gp1, GeoPoint gp2, int color){
this.gp1 = gp1;
this.gp2 = gp2;
this.color = color;
}
public void draw(Canvas canvas, MapView mapView, boolean shadow, GeoPoint gP1 , GeoPoint gP2){
super.draw(canvas, mapView, shadow);
TextView textview = (TextView) findViewById(R.id.id1);
textview.setText("This is ALSO happening");
Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(2);
Point p1 = new Point();
Point p2 = new Point();
Path path = new Path();
projection.toPixels(gP1, p1);
projection.toPixels(gP2, p2);
path.moveTo(p2.x, p2.y);
path.lineTo(p1.x,p1.y);
canvas.drawPath(path, mPaint);
}
}
}

Here saddr = source & daddr = destination location.
public void showDirections(View view) {
final Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://maps.google.com/maps?" + "saddr="+ latitude + "," + longitude + "&daddr=" + latitude + "," + longitude));
intent.setClassName("com.google.android.apps.maps","com.google.android.maps.MapsActivity");
startActivity(intent);
}

public class HelloItemizedOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Context mContext = getApplicationContext();
Bitmap bmp = BitmapFactory.decodeFile("pushpin.png");
Drawable drawable = new BitmapDrawable(bmp);
public HelloItemizedOverlay(Drawable drawable) {
super(boundCenterBottom(drawable));
populate();
}
public HelloItemizedOverlay(Drawable drawable, Context context) {
super(boundCenterBottom(drawable));
mContext = getApplicationContext();
populate();
}
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) {
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(
GoogleTrackingPage.this);
// add the overlay item's title and snippet or create owner
String newMessage = "Your order has the following location details \n\nVehicleID: "
+ vehicle
+ "\nDriver: "
+ driver
+ "\nStart Venue: "
+ starting
+ "\nFinal Destination: "
+ desti
+ "\nLast Updated on:" + dateR;
dialog.setTitle("Order Details for " + orderidfrommenu + " at "
+ locationString);
dialog.setMessage(newMessage);
dialog.show();
return true;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,long when)
{
Paint paint = null;
int x = myList.size();
int lastPoint = x-1;
if(myList.size() <= 2){
latitude = Double.parseDouble(myList.get(0).getLatitude());
longitude = Double.parseDouble(myList.get(0).getLongitude());
}
else{
int lP = myList.size()-2;
latitude = Double.parseDouble(myList.get(lP).getLatitude());
longitude = Double.parseDouble(myList.get(lP).getLongitude());
}
endlat = Double.parseDouble(myList.get(myList.size() - 1).getLatitude());
endlong = Double.parseDouble(myList.get(myList.size() - 1).getLongitude());
int beglat = (int)latitude* 1000000;
int endinglat = (int)endlat* 1000000;
int beglong = (int)longitude* 1000000;
int endinglong = (int)endlong* 1000000;
GeoPoint gP1 = new GeoPoint(beglat, beglong);
GeoPoint gP2 = geoPoint;
gP1=mOverlays.get(0).getPoint();
Projection projection = mapView.getProjection();
if (shadow == false)
{
paint = new Paint();
paint.setAntiAlias(true);
Point point = new Point();
projection.toPixels(gP1, point);
paint.setColor(Color.RED);
Point point2 = new Point();
projection.toPixels(gP2, point2);
paint.setStrokeWidth(5);
canvas.drawLine((float) point.x, (float) point.y, (float) point2.x,
(float) point2.y, paint);
}
return super.draw(canvas, mapView, shadow, when);
}
}

Related

moving map in mapview from one location to another in android

i have a situation in my app where i should move my map from one location to another location....i am quite new to android..and i found out how to draw a line in between two locations..
public class Mapview extends MapActivity implements LocationListener{
MapController mc;
GeoPoint p,p1,p2;
LocationManager lm;
String provider;
class Mapoverlay extends com.google.android.maps.Overlay
{
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
// TODO Auto-generated method stub
super.draw(canvas, mapView, shadow);
Point screenpoints=new Point();
Point screenpoints1=new Point();
Point screenpoints2=new Point();
Paint paint;
paint = new Paint();
paint.setColor(Color.RED);
paint.setAntiAlias(true);
paint.setStyle(Style.FILL);
paint.setStrokeWidth(2);
paint.setAlpha(120);
Paint paint1;
paint1 = new Paint();
paint1.setColor(Color.BLUE);
paint1.setAntiAlias(true);
paint1.setStyle(Style.FILL);
paint1.setStrokeWidth(2);
paint1.setAlpha(120);
if(p != null)
{
mapView.getProjection().toPixels(p, screenpoints);
mapView.getProjection().toPixels(p1, screenpoints1);
mapView.getProjection().toPixels(p2, screenpoints2);
// Bitmap map=BitmapFactory.decodeResource(getResources(), R.drawable.pushpin1);
// canvas.drawBitmap(map, screenpoints.x, screenpoints.y-53, null);
canvas.drawLine(screenpoints.x,screenpoints.y,screenpoints1.x,screenpoints1.y, paint);
canvas.drawLine(screenpoints.x,screenpoints.y,screenpoints2.x,screenpoints2.y, paint);
}
return true;
}
}
#Override
protected void onCreate(Bundle icicle) {
// TODO Auto-generated method stub
super.onCreate(icicle);
setContentView(R.layout.mapview);
MapView map=(MapView)findViewById(R.id.mapView);
map.setBuiltInZoomControls(true);
mc=map.getController();
String[] coordinates={"51.4750766129036", "-3.15672342166522"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p=new GeoPoint((int)(lat*1E6), (int)(lng*1E6));
String[] coordinates1={"17.453117" , "78.467586" };
double lat1 = Double.parseDouble(coordinates1[0]);
double lng1 = Double.parseDouble(coordinates1[1]);
p2=new GeoPoint((int)(lat1*1E6), (int)(lng1*1E6));
p1 = new GeoPoint(19240000,-99120000);
// p = new GeoPoint(19241000,-99121000);
lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider=lm.getBestProvider(criteria, true);
Location loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
List<String> lists=lm.getAllProviders();
// float f=loc.distanceTo(loc);
if (loc!=null){
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(loc);
}else{
Toast.makeText(getApplicationContext(), "Provider " + provider+ loc + lists+" has not been selected.", 5000).show();
// this.finish();
}
// Toast.makeText(getApplicationContext(), p.getLatitudeE6()+p.getLongitudeE6(), Toast.LENGTH_SHORT).show();
mc.animateTo(p);
mc.setZoom(1);
map.invalidate();
Mapoverlay mapOverlay = new Mapoverlay();
List<Overlay> listOfOverlays = map.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
}
i am stuck at moving map from one location to another without user activity
for example:when the app initiates location of newyork city is shown then the map should move to texas ...any help willl be grateful
Try This class just pass Activity act,GeoPoint src,GeoPoint dest, int color, MapView mMapView
To call this class do this
new getRoute().DrawPath(this,mGeoPoint,getGeoPoint,Color.RED,mMapView);
public class getRoute
{
/*Variable*/
double mIntentLatitude, mIntentLongitude;
double mCursorLatitude, mCursorLongitude, mStartLatitude, mStartLongitude, mEndLatitude, MEndLongitude;
String mJsonData;
String mEnd_Address, mStart_Address, mName;
int mLength;
GeoPoint mGeoPoint = new GeoPoint(220328269, 725588202);
double mLatitude_End[], mLongitude_End[], mLatitude_Start[], mLongitude_Start[];
Activity activity;
public getRoute
(){
}
boolean error = false;
public void DrawPath(Activity act,GeoPoint src,GeoPoint dest, int color, MapView mMapView01)
{
// connect to map web service
DrawPathBack draw = new DrawPathBack(act, src, dest, color, mMapView01);
draw.execute("Draw");
}
public class DrawPathBack extends AsyncTask<String, Integer,Void>
{
ProgressDialog bar;
List<Overlay> mListOverlay;
MapOverlay mapOverlay;
ItemizedOverlay<OverlayItem> mItemizedOverlay;
GeoPoint src,dest;
int color;
MapView mMapView;
CommonMethod mCommonMethod;
String [] pairs;
String[] lngLat;
public DrawPathBack(Activity act,GeoPoint gpsrc,GeoPoint gpdest, int c, MapView mMap)
{
activity =act;
src=gpsrc;
dest=gpdest;
color = c;
mMapView=mMap;
mListOverlay = mMapView.getOverlays();
mapOverlay = new MapOverlay(mGeoPoint);
mListOverlay.add(mapOverlay);
mMapView.invalidate();
}
#Override
protected Void doInBackground(String... params)
{
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(httpParameters, 60000);
HttpClient client = new DefaultHttpClient();
try {
HttpPost httpPost = new HttpPost("http://maps.googleapis.com/maps/api/directions/json?origin="+ (Double.toString((double)src.getLatitudeE6()/1.0E6)) + "," +(Double.toString((double)src.getLongitudeE6()/1.0E6 ) + "&destination=" + (Double.toString((double)dest.getLatitudeE6()/1.0E6)) + ","+ (Double.toString((double)dest.getLongitudeE6()/1.0E6))+ "&sensor=false"));
mIntentLatitude=((double)src.getLatitudeE6()/1.0E6);
mIntentLongitude=((double)src.getLongitudeE6()/1.0E6);
//httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = client.execute(httpPost);
mJsonData = EntityUtils.toString(httpResponse.getEntity());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress)
{
bar.setMessage("Time Progress "+progress[0]);
}
#Override
protected void onPostExecute(Void result)
{
try {
JSONObject jsonObj = new JSONObject(mJsonData);
// grabbing the routes object
JSONArray routes = jsonObj.getJSONArray("routes");
for (int i = 0; i < routes.length(); i++) {
JSONObject rout = routes.getJSONObject(i);
JSONObject bounds = rout.getJSONObject("bounds");
JSONObject northest = bounds.getJSONObject("northeast");
mStartLatitude = northest.getDouble("lat");
mStartLongitude = northest.getDouble("lng");
JSONObject southwest = bounds.getJSONObject("southwest");
mEndLatitude = southwest.getDouble("lat");
MEndLongitude = southwest.getDouble("lng");
System.out.println("get data from jeson" + mCursorLatitude + mCursorLongitude + mEndLatitude
+ MEndLongitude);
// grabbing the routes legs
JSONArray legs = rout.getJSONArray("legs");
System.out.println("length of legs array " + legs.length());
for (int j = 0; j < legs.length(); j++) {
JSONObject leg = legs.getJSONObject(j);
System.out.println("enter in second array");
JSONObject distance = leg.getJSONObject("distance");
String mTextDistent = distance.getString("text");
System.out.println("distances bitween two point" + mTextDistent);
JSONObject duration = leg.getJSONObject("duration");
String mTextDurestion = duration.getString("text");
mEnd_Address = leg.getString("end_address");
mStart_Address = leg.getString("start_address");
System.out.println("get data from jeson in second arry"
+ mTextDurestion + " " + mEnd_Address + " " + mStart_Address);
JSONArray step = leg.getJSONArray("steps");
mLength = step.length();
mLatitude_End = new double[mLength];
mLongitude_End = new double[mLength];
mLatitude_Start = new double[mLength];
mLongitude_Start = new double[mLength];
for (int k = 0; k < step.length(); k++) {
JSONObject st = step.getJSONObject(k);
System.out.println("enter in third array");
JSONObject end_lo = st.getJSONObject("end_location");
JSONObject start_lo = st
.getJSONObject("start_location");
mLatitude_End[k] = end_lo.getDouble("lat");
mLongitude_End[k] = end_lo.getDouble("lng");
mLatitude_Start[k] = start_lo.getDouble("lat");
mLongitude_Start[k] = start_lo.getDouble("lng");
}
for (int mDistanse = 0; mDistanse < mLength; mDistanse++) {
System.out.println("end location let" + mLatitude_End[mDistanse]);
System.out.println("end location long+"
+ mLongitude_End[mDistanse]);
System.out.println("Start location let"
+ mLatitude_Start[mDistanse]);
System.out.println("Start location long"
+ mLongitude_Start[mDistanse]);
}
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
public class MapOverlay extends com.google.android.maps.Overlay {
public MapOverlay(GeoPoint mGeoPoint) {
}
#Override
public boolean draw(final Canvas canvas, MapView mapView,
boolean shadow, long when) {
Point mpoint = new Point();
Point mpoint1 = new Point();
int let[] = new int[mLength];
int lon[] = new int[mLength];
int let_end[] = new int[mLength];
int lon_end[] = new int[mLength];
GeoPoint newGeoPoint = null;
GeoPoint newGeoPoint1;
for (int k = 0; k < mLength; k++) {
let[k] = (int) (mLatitude_Start[k] * 1E6);
lon[k] = (int) (mLongitude_Start[k] * 1E6);
let_end[k] = (int) (mLatitude_End[k] * 1E6);
lon_end[k] = (int) (mLongitude_End[k] * 1E6);
newGeoPoint1 = new GeoPoint(let_end[k], lon_end[k]);
newGeoPoint = new GeoPoint(let[k], lon[k]);
mapView.getProjection().toPixels(newGeoPoint, mpoint);
mapView.getProjection().toPixels(newGeoPoint1, mpoint1);
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(5);
canvas.drawCircle(mpoint.x, mpoint.y, 5, paint);
paint.setColor(Color.BLUE);
canvas.drawLine(mpoint.x, mpoint.y, mpoint1.x, mpoint1.y, paint);
paint.setColor(Color.BLACK);
paint.setStrokeWidth(100);
paint.setStyle(Paint.Style.FILL);
if(k==mLength-1){
Bitmap bmp = BitmapFactory.decodeResource(activity.getResources(), R.drawable.green_pin);
canvas.drawBitmap(bmp,mpoint1.x ,mpoint1.y-30, null);
}
GeoPoint dumy=new GeoPoint((int)(mIntentLatitude * 1E6), (int)(mIntentLongitude * 1E6));
Point dumy1 = new Point();
mapView.getProjection().toPixels(dumy, dumy1);
Bitmap bmp = BitmapFactory.decodeResource(activity.getResources(), R.drawable.dest_pin);
canvas.drawBitmap(bmp,dumy1.x,dumy1.y - 25, null);
mapView.getController().animateTo(dumy);
mapView.invalidate();
}
return false;
}
}
}
Try this if you want to move map on particular position then get lat or long of that position and just pass in this :
MapController mMapController;
mMapController=mMapView.getController();
mMapController.setCenter(new GeoPoint((int)(lat * 1E6), (int)(lon * 1E6)));
and if you want to draw path between two location then just pass lat and lon in this :
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr="+ String.valueOf(from_lattitude) +","+ String.valueOf(from_longitude) +"&daddr="+ String.valueOf(dest_lati) +","+ String.valueOf(dest_longi)));
startActivity(intent);

plot a route on google maps

I want to draw a route on google map with the change in my position using GPS. As my location changes(when new geopoints are created), the dot moves on the google map but i'm unable to draw the line on the map.
Please help in plotting the route on google maps. Below is my code
`
LocationManager locman;
LocationListener loclis;
Location location;
private MapView map;
List<GeoPoint> geoPointsArray = new ArrayList<GeoPoint>();
private MapController controller;
String provider = LocationManager.GPS_PROVIDER;
double lat;
double lon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initMapView();
initMyLocation();
locman = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//locman.requestLocationUpdates(provider,60000, 100,loclis);
//Location = locman.getLastKnownLocation(provider);
}
/** Find and initialize the map view. */
private void initMapView() {
map = (MapView) findViewById(R.id.mapView);
controller = map.getController();
map.setSatellite(false);
map.setBuiltInZoomControls(true);
}
/** Find Current Position on Map. */
private void initMyLocation() {
final MyLocationOverlay overlay = new MyLocationOverlay(this, map);
overlay.enableMyLocation();
overlay.enableCompass(); // does not work in emulator
overlay.runOnFirstFix(new Runnable() {
public void run() {
// Zoom in to current location
controller.setZoom(16);
controller.animateTo(overlay.getMyLocation());
}
});
map.getOverlays().add(overlay);
}
public void onLocationChanged(Location location) {
if (location != null){
lat = location.getLatitude();
lon = location.getLongitude();
GeoPoint New_geopoint = new GeoPoint((int)(lat*1e6),(int)(lon*1e6));
controller.animateTo(New_geopoint);
}
}
class MyOverlay extends Overlay{
public MyOverlay(){
}
public void draw(Canvas canvas, MapView mapv, boolean shadow){
super.draw(canvas, mapv, shadow);
Paint paint;
paint = new Paint();
paint.setColor(Color.GREEN);
paint.setAntiAlias(true);
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(3);
Projection projection = map.getProjection();
Path p = new Path();
for (int i = 0; i < geoPointsArray.size(); i++) {
if (i == geoPointsArray.size() - 1) {
break;
}
Point from = new Point();
Point to = new Point();
projection.toPixels(geoPointsArray.get(i), from);
projection.toPixels(geoPointsArray.get(i + 1), to);
p.moveTo(from.x, from.y);
canvas.drawLine(from.x, from.y, to.x, to.y, paint);
//p.lineTo(to.x, to.y);
}
}
}
`
Why don't you just draw a polyline? You just need LatLng instances.
var flightPlanCoordinates = [
new google.maps.LatLng(43.290307,-2.884174),
new google.maps.LatLng(41.3973,2.158964),
new google.maps.LatLng(40.462046,-3.809694),
new google.maps.LatLng(38.976895,-1.858366)
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap( map );
I wrote this code quite some time ago so forgive me, it could be cleaned up a lot, but i believe it should do what you need.
public class RouteSegmentOverlay extends Overlay {
private Paint paint;
private ArrayList<GeoPoint> routePoints;
private boolean routeIsActive;
private int numberRoutePoints;
private Path path;
// Constructor permitting the route array to be passed as an argument.
public RouteSegmentOverlay(ArrayList<GeoPoint> routePoints) {
this.routePoints = routePoints;
numberRoutePoints = routePoints.size();
routeIsActive = true;
}
// Method to turn route display on and off
public void setRouteView(boolean routeIsActive){
this.routeIsActive = routeIsActive;
}
public void setColor(int c){
color = c;
}
private int color = 0;
Paint.Style paintStyle = Paint.Style.STROKE;
public void setFillStyle(Paint.Style style){
paintStyle = style;
}
#Override
public void draw(Canvas canvas, MapView mapview, boolean shadow) {
super.draw(canvas, mapview, shadow);
if(! routeIsActive) return;
if(paint==null){
paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeWidth(7);
paint.setStyle(paintStyle);
paint.setAntiAlias(true);
paint.setARGB(255, 0, 0, 255);
paint.setColor(color);
}
if(bitmap==null){
wMin = Integer.MAX_VALUE;
wMax = Integer.MIN_VALUE;
hMin = Integer.MAX_VALUE;
hMax = Integer.MIN_VALUE;
lonMin = Integer.MAX_VALUE;
lonMax = Integer.MIN_VALUE;
latMin = Integer.MAX_VALUE;
latMax = Integer.MIN_VALUE;
Boolean newSegment = true;
Point pt = new Point();
GeoPoint point = null;
ArrayList<Point> points = new ArrayList<Point>();
for(int i=0; i<numberRoutePoints; i++){
point = routePoints.get(i);
int tempLat = point.getLatitudeE6();
int tempLon = point.getLongitudeE6();
if(tempLon<lonMin)lonMin = tempLon;
if(tempLon>lonMax)lonMax = tempLon;
if(tempLat<latMin)latMin = tempLat;
if(tempLat>latMax)latMax = tempLat;
mapview.getProjection().toPixels(routePoints.get(i), pt);
points.add(new Point(pt.x,pt.y));
if(pt.x<wMin)wMin = pt.x;
if(pt.x>wMax)wMax = pt.x;
if(pt.y<hMin)hMin = pt.y;
if(pt.y>hMax)hMax = pt.y;
}
topLeftIn = new GeoPoint(latMax, lonMin);
bottomRightIn = new GeoPoint(latMin, lonMax);
int width = (wMax-wMin);
int height = (hMax-hMin);
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
Canvas c = new Canvas(bitmap);
Path bitmapPath = new Path();
bitmapPath.incReserve(numberRoutePoints);
newSegment = true;
for(Point p : points){
if (newSegment) {
bitmapPath.moveTo(p.x - wMin, p.y - hMin);
newSegment = false;
} else {
bitmapPath.lineTo(p.x - wMin, p.y - hMin);
}
}
c.drawPath(bitmapPath, paint);
}
mapview.getProjection().toPixels(topLeftIn, topLeftOut);
mapview.getProjection().toPixels(bottomRightIn, bottomRightOut);
int l = topLeftOut.x;
int t = topLeftOut.y;
int r = bottomRightOut.x;
int b = bottomRightOut.y;
Rect rect = new Rect(l,t,r,b);
canvas.drawBitmap(bitmap, new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()),rect,null);
}
GeoPoint topLeftIn = null;
GeoPoint bottomRightIn = null;
Point topLeftOut = new Point();
Point bottomRightOut = new Point();
Bitmap bitmap = null;
int wMin = Integer.MAX_VALUE;
int wMax = 0;
int hMin = Integer.MAX_VALUE;
int hMax = 0;
int lonMin = Integer.MAX_VALUE;
int lonMax = 0;
int latMin = Integer.MAX_VALUE;
int latMax = 0;
}

Overlays not showing up on MapView

So I have my mapview set up, and everything runs, but the overlays don't show up on the map. Any suggestions or help at all would be greatly appreciated.
My MapActivity extension class is the following:
public class trailInformation extends MapActivity {
public String trailName = "";
public loadMapDataTask mapTask = new loadMapDataTask();
public myObject inp = new myObject();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trail_info_layout);
// General variable declarations
Intent intent = getIntent();
trailName = intent.getStringExtra(trailsActivity.EXTRA_MESSAGE);
// Sets map to satellite
final MapView map = (MapView) findViewById(R.id.infoMapView);
map.setSatellite(true);
// Setup map input
inp.setID(R.raw.nordhoff_peak_loop);
inp.setName("mapfile");
inp.setMap(map);
// Display Trail Name
Typeface font = Typeface.createFromAsset(getAssets(), "arial.ttf");
TextView trailNameTV = (TextView) findViewById(R.id.infoTitle);
trailNameTV.setText(trailName);
trailNameTV.setTypeface(font);
Display display = getWindowManager().getDefaultDisplay();
trailNameTV.setTextSize(findTextSize(trailNameTV, trailName,
GalleryPageActivity.getDisplaySize(display).x, font));
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
mapTask.execute(inp);
}
public class loadMapDataTask extends AsyncTask<myObject, Void, File> {
#Override
protected File doInBackground(myObject... params) {
File file = getApplicationContext().getFileStreamPath(
params[0].getName());
if (file.exists()) {
return file;
}
InputStream is;
FileOutputStream fos;
try {
is = getResources().openRawResource(params[0].getID());
byte[] buffer = new byte[is.available()];
is.read(buffer);
fos = openFileOutput(params[0].getName(), MODE_PRIVATE);
fos.write(buffer);
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
List<Location> gpsPoints = XMLParser.getPoints(file);
int i = 0;
int index = 0;
GeoPoint[] geoPoints = new GeoPoint[gpsPoints.size()];
ListIterator<Location> it = gpsPoints.listIterator();
while (it.hasNext()) {
index = it.nextIndex();
Location loc = gpsPoints.get(index);
geoPoints[i] = new GeoPoint((int) (loc.getLatitude() * 1E6),
(int) (loc.getLongitude() * 1E6));
it.next();
Log.i("DEBUG", "" + geoPoints[i]);
}
if (geoPoints.length > 1) {
mapOverlay[] overlays = new mapOverlay[(geoPoints.length - 1)];
MapController mc = params[0].getMap().getController();
mc.animateTo(geoPoints[0]);
mc.setZoom(17);
for (int z = 0; z < overlays.length; z++) {
List<Overlay> mapOverlays;
mapOverlays = params[0].getMap().getOverlays();
mapOverlays.add(overlays[z]);
}
} else {
Log.i("DEBUG", "Not drawing lines because " + geoPoints.length
+ " points exist in geopoints array.");
}
return file;
}
#Override
protected void onPostExecute(File result) {
Log.i("DEBUG", "Task executed");
}
}
public static String readRawTextFile(Context ctx, int resId) {
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while ((line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
public float findTextSize(TextView tV, String text, float Width,
Typeface font) {
float textSize = 100;
float scaledPx = 0;
float densityMultiplier = getBaseContext().getResources()
.getDisplayMetrics().density;
TextPaint paint = tV.getPaint();
paint.setTypeface(font);
while (textSize > 20) {
scaledPx = textSize * densityMultiplier;
paint.setTextSize(scaledPx);
if (paint.measureText(text) < Width) {
return textSize;
} else {
textSize--;
}
}
return 0;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
And my mapOverlay class is the following:
public class mapOverlay extends Overlay {
private Projection projection;
public mapOverlay(MapView map) {
super();
projection = map.getProjection();
}
public void draw(Canvas canvas, MapView mapv, boolean shadow, GeoPoint gp1,
GeoPoint gp2) {
super.draw(canvas, mapv, shadow);
// Configuring the paint brush
Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(4);
Point p1 = new Point();
Point p2 = new Point();
Path path1 = new Path();
projection.toPixels(gp1, p1);
projection.toPixels(gp2, p2);
path1.moveTo(p1.x, p1.y);
path1.lineTo(p2.x, p2.y);
canvas.drawPath(path1, mPaint);
}
}
I think I might just be missing something about MapView, and there also might be a problem with my Asynctask since it's my first time using it, but I don't think there is.

path tracing program in android

i want the source code for path tracking program in android.
i see the code in
How to draw a path on a map using kml file?
public void drawPath(NavigationDataSet navSet, int color, MapView mMapView01) {
Log.d(myapp.APP, "map color before: " + color);
// color correction for dining, make it darker
if (color == Color.parseColor("#add331")) color = Color.parseColor("#6C8715");
Log.d(myapp.APP, "map color after: " + color);
Collection overlaysToAddAgain = new ArrayList();
for (Iterator iter = mMapView01.getOverlays().iterator(); iter.hasNext();) {
Object o = iter.next();
Log.d(myapp.APP, "overlay type: " + o.getClass().getName());
if (!RouteOverlay.class.getName().equals(o.getClass().getName())) {
// mMapView01.getOverlays().remove(o);
overlaysToAddAgain.add(o);
}
}
mMapView01.getOverlays().clear();
mMapView01.getOverlays().addAll(overlaysToAddAgain);
String path = navSet.getRoutePlacemark().getCoordinates();
Log.d(myapp.APP, "path=" + path);
if (path != null && path.trim().length() > 0) {
String[] pairs = path.trim().split(" ");
Log.d(myapp.APP, "pairs.length=" + pairs.length);
String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height
Log.d(myapp.APP, "lnglat =" + lngLat + ", length: " + lngLat.length);
if (lngLat.length<3) lngLat = pairs[1].split(","); // if first pair is not transferred completely, take seconds pair //TODO
try {
GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));
mMapView01.getOverlays().add(new RouteOverlay(startGP, startGP, 1));
GeoPoint gp1;
GeoPoint gp2 = startGP;
for (int i = 1; i < pairs.length; i++) // the last one would be crash
{
lngLat = pairs[i].split(",");
gp1 = gp2;
if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
&& gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {
// for GeoPoint, first:latitude, second:longitude
gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));
if (gp2.getLatitudeE6() != 22200000) {
mMapView01.getOverlays().add(new RouteOverlay(gp1, gp2, 2, color));
Log.d(myapp.APP, "draw:" + gp1.getLatitudeE6() + "/" + gp1.getLongitudeE6() + " TO " + gp2.getLatitudeE6() + "/" + gp2.getLongitudeE6());
}
}
// Log.d(myapp.APP,"pair:" + pairs[i]);
}
//routeOverlays.add(new RouteOverlay(gp2,gp2, 3));
mMapView01.getOverlays().add(new RouteOverlay(gp2, gp2, 3));
} catch (NumberFormatException e) {
Log.e(myapp.APP, "Cannot draw route.", e);
}
}
// mMapView01.getOverlays().addAll(routeOverlays); // use the default color
mMapView01.setEnabled(true);
}
but i am unable to execute the code.
if you donot mind can any once give the entire source code .
thanks.
I have two classes HomeActivity and MyOverlay to draw path in google map
here is HomeActivity :
MapView mapView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.e("Home", " activity created");
mapView = (MapView) findViewById(R.id.mapview);
double src_lat = 28.011022; // the testing source 28.011022,73.323802
double src_long = 73.323802;
double dest_lat = 28.008389; // the testing destination 28.008389,73.33599
double dest_long = 73.33599;
Log.e("Home ", " Strting drawing path");
GeoPoint srcGeoPoint = new GeoPoint((int) (src_lat * 1E6),
(int) (src_long * 1E6));
GeoPoint destGeoPoint = new GeoPoint((int) (dest_lat * 1E6),
(int) (dest_long * 1E6));
Log.e("Home ", " Strting drawing path");
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.darkgreen_marker);
mapView.getOverlays();
OverlayItem overlayitem = new OverlayItem(srcGeoPoint, "Hello!", "This is your position");
overLay marker_overlay=new overLay(drawable);
marker_overlay.addOverlay(overlayitem);
mapOverlays.add(marker_overlay);
overlayitem = new OverlayItem(destGeoPoint, "Theater Big ", "Go to this ");
marker_overlay.addOverlay(overlayitem);
mapOverlays.add(marker_overlay);
//mapView.getOverlays().add(new overLay(null, destGeoPoint));
DrawPath(srcGeoPoint, destGeoPoint, Color.GREEN, mapView);
mapView.getController().animateTo(srcGeoPoint);
mapView.getController().setZoom(15);
mapView.setBuiltInZoomControls(true);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
private void DrawPath(GeoPoint src,GeoPoint dest, int color, MapView mMapView01)
{
// connect to map web service
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");//from
urlString.append( Double.toString((double)src.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)src.getLongitudeE6()/1.0E6 ));
urlString.append("&daddr=");//to
urlString.append( Double.toString((double)dest.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)dest.getLongitudeE6()/1.0E6 ));
urlString.append("&ie=UTF8&0&om=0&output=kml");
Log.e("Draw path ","URL="+urlString.toString());
// get the kml (XML) doc. And parse it to get the coordinates(direction route).
Document doc = null;
HttpURLConnection urlConnection= null;
URL url = null;
try
{
url = new URL(urlString.toString());
urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
Log.e(" Home ", " response"+doc.toString());
if(doc.getElementsByTagName("GeometryCollection").getLength()>0)
{
//String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getNodeName();
String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue() ;
Log.d("draw path ","path="+ path);
String [] pairs = path.split(" ");
String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height
// src
GeoPoint startGP = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
mMapView01.getOverlays().add(new MyOverLay(startGP,startGP,1));
GeoPoint gp1;
GeoPoint gp2 = startGP;
for(int i=1;i<pairs.length;i++) // the last one would be crash
{
lngLat = pairs[i].split(",");
gp1 = gp2;
// watch out! For GeoPoint, first:latitude, second:longitude
gp2 = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
mMapView01.getOverlays().add(new MyOverLay(gp1,gp2,2,color));
Log.d("Draw path","pair:" + pairs[i]);
}
mMapView01.getOverlays().add(new MyOverLay(dest,dest, 3)); // use the default color
}
}catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
catch (ParserConfigurationException e){
e.printStackTrace();
}
catch (SAXException e){
e.printStackTrace();
}
}
public class overLay extends ItemizedOverlay<OverlayItem>{
private List<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
GeoPoint gp1;
Drawable marker;
public overLay(Drawable marker) {
super(marker);
this.marker=marker;
}
public void addOverlay(OverlayItem overlay){
mOverlays.add(overlay);
Log.e(" Map Overlay __", " adding new item "+overlay);
populate();
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when){
Projection projection = mapView.getProjection();
Point point = new Point();
for(int i=0;i<mOverlays.size();i++){
OverlayItem g = getItem(i);
gp1=g.getPoint();
projection.toPixels(gp1, point);
Bitmap bmp = BitmapFactory.decodeResource(
getResources(), R.drawable.marker_red);
canvas.drawBitmap(bmp, point.x-10, point.y-35, null);
}
return super.draw(canvas, mapView, shadow, when);
}
#Override
public boolean onTap(int index){
/* GeoPonit p MapView mapView*/
OverlayItem item = getItem(index);
GeoPoint gp=item.getPoint();
String msg=item.getSnippet();
mapView.getController().animateTo(gp);
Log.e("-- map view --", " marker clicked "+gp);
LayoutInflater infalter=getLayoutInflater();
final LinearLayout table = (LinearLayout)infalter.inflate(R.layout.popup_baloon_layout, null);
table.setWillNotDraw(false);
final MapView.LayoutParams lp2 = new MapView.LayoutParams(
150,100,gp,-15,-10,MapView.LayoutParams.BOTTOM_CENTER);
TextView addrs=(TextView)table.findViewById(R.id.address);
addrs.setText(msg);
ImageView call_img=(ImageView)table.findViewById(R.id.imageView1);
call_img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("__ Home __", " making call to 12345");
Bundle bundle=new Bundle();
mapView.removeView(table);
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + bundle.getString("12345")));
HomeActivity.this.startActivity(intent);
}
});
table.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mapView.removeView(table);
//table=null;
}
});
mapView.addView(table,lp2);
return true;
}
#Override
protected OverlayItem createItem(int i) {
Log.e("Map Overlay __", " creating overlay item "+i);
return mOverlays.get(i);
}
#Override
public int size() {
Log.e("Map Overlay __", " getting overlay size ");
return mOverlays.size();
}
}
and MyOverLay class :
public class MyOverLay extends Overlay{
private GeoPoint gp1;
private GeoPoint gp2;
//private int mRadius=6;
private int mode=0;
private int defaultColor;
//private String text="";
//private Bitmap img = null;
private Context context;
public MyOverLay(GeoPoint gp1,GeoPoint gp2,int mode,Context context){// GeoPoint is a int. (6E)
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
defaultColor = 999; // no defaultColor
this.context=context;
}
public MyOverLay(GeoPoint gp1,GeoPoint gp2,int mode, int defaultColor,Context context){
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
this.defaultColor = defaultColor;
this.context=context;
}
/*public void setText(String t){
this.text = t;
}
public void setBitmap(Bitmap bitmap){
this.img = bitmap;
}*/
public int getMode(){
return mode;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when){
Projection projection = mapView.getProjection();
if (shadow == false){
Paint paint = new Paint();
paint.setAntiAlias(true);
Point point = new Point();
projection.toPixels(gp1, point);
// mode=1:start
if(mode==1){
if(defaultColor==999)
paint.setColor(Color.BLUE);
else
paint.setColor(defaultColor);
Bitmap bmp = BitmapFactory.decodeResource(
context.getResources(), R.drawable.marker_red);
canvas.drawBitmap(bmp, point.x-10, point.y-35, null);
/*RectF oval=new RectF(point.x - mRadius, point.y - mRadius,
point.x + mRadius, point.y + mRadius);*/
// start point
//canvas.drawOval(oval, paint);
}
// mode=2:path
else if(mode==2){
if(defaultColor==999)
paint.setColor(Color.RED);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(5);
paint.setAlpha(120);
canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
}
/* mode=3:end */
else if(mode==3){
/* the last path */
if(defaultColor==999)
paint.setColor(Color.GREEN);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(5);
paint.setAlpha(120);
canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
Bitmap bmp = BitmapFactory.decodeResource(
context.getResources(), R.drawable.marker_red);
canvas.drawBitmap(bmp, point.x-16, point.y-38, null);
/*RectF oval=new RectF(point2.x - mRadius,point2.y - mRadius,
point2.x + mRadius,point2.y + mRadius);
paint.setAlpha(255);
canvas.drawOval(oval, paint);*/
}
}
return super.draw(canvas, mapView, shadow, when);
}
#Override
public boolean onTap(GeoPoint p, MapView mapView){
return false;
}
}
These classes use kml to draw path between two locations.

Draw line between two points in google map in android [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Drawing a line/path on Google Maps
How can i draw line beetween two points in google map?
public class DrivingDirection extends MapActivity implements
IDirectionsListener {
Button btnRedirectHome;
Vector<GeoPoint> mapData = new Vector<GeoPoint>();
Vector<GeoPoint> NearData = new Vector<GeoPoint>();
MapView mapView;
MapController mc;
GeoPoint p;
GeoPoint endpoint;
MapOverlay mapOverlay;
private AlertDialog.Builder alertDialog1, alertDialog;
boolean exception = false;
// ** Called when the activity is first created. *//*
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.courtdetaildetdirection_layout);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
Bundle extras = getIntent().getExtras();
String courtId = extras != null ? extras.getString("CourtId") : "";
if(GUIStatics.previousActivityNameFalg.equalsIgnoreCase("MatchDetailActivity"))
{
if (GUIStatiMethods
.connectionCheck(DrivingDirection.this)) {
Court_Player_LocationFatcher objectCourt_Player_LocationFatch = new Court_Player_LocationFatcher();
objectCourt_Player_LocationFatch.Court_Player_LocationFatch(GUIStatics.strUserID,courtId);
final CourtDetailFatcher myCourtDetailFatcher = new CourtDetailFatcher();
myCourtDetailFatcher.CourtDetailFatch(courtId);
}
}
else if(GUIStatics.previousActivityNameFalg.equalsIgnoreCase("FavoritesActivity"))
{
if (GUIStatiMethods
.connectionCheck(DrivingDirection.this)) {
Court_Player_LocationFatcher objectCourt_Player_LocationFatch = new Court_Player_LocationFatcher();
objectCourt_Player_LocationFatch.Court_Player_LocationFatch(GUIStatics.strUserID,courtId);
final CourtDetailFatcher myCourtDetailFatcher = new CourtDetailFatcher();
myCourtDetailFatcher.CourtDetailFatch(courtId);
}
}
else
{
if (GUIStatiMethods
.connectionCheck(DrivingDirection.this)) {
Court_Player_LocationFatcher objectCourt_Player_LocationFatch = new Court_Player_LocationFatcher();
objectCourt_Player_LocationFatch.Court_Player_LocationFatch(GUIStatics.strUserID,courtId);
final CourtDetailFatcher myCourtDetailFatcher = new CourtDetailFatcher();
myCourtDetailFatcher.CourtDetailFatch(courtId);
}
}
TextView TextViewCourtDetailHeader = (TextView) this
.findViewById(R.id.TextViewCourtDetailHeader);
TextView TextViewCourtDetailAddress = (TextView) this
.findViewById(R.id.TextViewCourtDetailAddress);
TextView TextViewCourtDetailNoOfCourtAndType = (TextView) this
.findViewById(R.id.TextViewCourtDetailNoOfCourtAndType);
TextView TextViewCourtDetailCourtType = (TextView) this
.findViewById(R.id.TextViewCourtDetailCourtType);
TextView TextViewCourtDetailLight = (TextView) this
.findViewById(R.id.TextViewCourtDetailLight);
TextViewCourtDetailHeader
.setText(CourtDetailDataHandler.object.COURTNAME);
TextViewCourtDetailAddress
.setText(CourtDetailDataHandler.object.COURTADDRESS);
TextViewCourtDetailNoOfCourtAndType
.setText(CourtDetailDataHandler.object.NUMBEROFCOURT);
TextViewCourtDetailCourtType
.setText(CourtDetailDataHandler.object.COURTTYPE);
TextViewCourtDetailLight.setText("Lights: "
+ CourtDetailDataHandler.object.COURTLIGHT);
String url = "http://maps.google.com/maps?f=d&hl=en&saddr="
+ Court_Player_LocationHandler.mCOURTLAT + ","
+ Court_Player_LocationHandler.mCOURTLON + "&daddr="
+ Court_Player_LocationHandler.mUSERLAT + ","
+ Court_Player_LocationHandler.mUSERLON
+ "&ie=UTF8&0&om=0&z=20&output=kml";
Document d = GetDataFromServer(url);
if (exception) {
exception = false;
GeoPoint source = new GeoPoint(
(int) (Double
.parseDouble(Court_Player_LocationHandler.mCOURTLAT) * 1E6),
(int) (Double
.parseDouble(Court_Player_LocationHandler.mCOURTLON) * 1E6));
mapData.add(source);
GeoPoint destination = new GeoPoint(
(int) (Double
.parseDouble(Court_Player_LocationHandler.mUSERLAT) * 1E6),
(int) (Double
.parseDouble(Court_Player_LocationHandler.mUSERLON) * 1E6));
mapData.add(destination);
} else {
ParseServerData(d);
}
LinearLayout zoomLayout = (LinearLayout) findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();
zoomLayout.addView(zoomView, new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mapView.displayZoomControls(true);
mc = mapView.getController();
for (int i = 0; i < mapData.size(); i++) {
GeoPoint gp = mapData.get(i);
mc.animateTo(gp);
}
for (int i = 0; i < NearData.size(); i++) {
GeoPoint gp = mapData.get(i);
mc.animateTo(gp);
}
mc.setZoom(18);
// ---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
class MapOverlay extends com.google.android.maps.Overlay {
Paint innerPaint;
int infoWindowOffsetX, infoWindowOffsetY, testX, testY, id;
boolean showWindow = false;
Bitmap bitmap, bmp, bitMoreInformation;
String argName;
boolean temp = true;
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.marker);
// ---translate the GeoPoint to screen pixels---
Paint myPaintBlack1 = new Paint();
myPaintBlack1.setColor(Color.BLUE);
myPaintBlack1.setStyle(Style.STROKE);
myPaintBlack1.setStrokeWidth(4f);
Point screenPts[] = new Point[mapData.size()];
for (int i = 0; i < mapData.size(); i++) {
Point screenPt = new Point();
GeoPoint gp = mapData.get(i);
mapView.getProjection().toPixels(gp, screenPt);// screenPts[i]);
screenPts[i] = screenPt;
if (i == 0)
canvas.drawBitmap(bmp, screenPts[i].x - bmp.getWidth() / 2,
screenPts[i].y - bmp.getHeight(), null);
if (i == mapData.size() - 1)
canvas.drawBitmap(bmp, screenPts[i].x - bmp.getWidth() / 2,
screenPts[i].y - bmp.getHeight(), null);
}
for (int i = 0; i < NearData.size(); i++) {
Point screenPs = new Point();
GeoPoint gp = mapData.get(i);
mapView.getProjection().toPixels(gp, screenPs);// screenPts[i]);
canvas.drawBitmap(bmp, screenPs.x - bmp.getWidth() / 2,
screenPs.y - bmp.getHeight(), null);
}
for (int i = 1; i < screenPts.length; i++) {
canvas.drawLine(screenPts[i - 1].x, screenPts[i - 1].y,
screenPts[i].x, screenPts[i].y, myPaintBlack1);
}
return true;
}
public Paint getInnerPaint() {
if (innerPaint == null) {
innerPaint = new Paint();
innerPaint.setARGB(225, 75, 75, 75); // gray
innerPaint.setAntiAlias(true);
}
return innerPaint;
}
#Override
public boolean onTap(GeoPoint p, MapView mapView) {
return true;
}
}
public Document GetDataFromServer(String url) {
try {
URL updateURL = new URL(url);
URLConnection conn = updateURL.openConnection();
InputStream is = conn.getInputStream();
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(is);
is.close();
return document;
} catch (Exception e) {
exception = true;
System.out.print("Exception:-" + e);
}
exception = true;
return null;
}
private void ParseServerData(Document doc) {
Element rootElement = doc.getDocumentElement();
rootElement.normalize();
NodeList nodeLst = doc.getElementsByTagName("LookAt");
int c = nodeLst.getLength();
System.out.println("count= " + c);
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
// Points p = new Points();
Element Elmnt = (Element) fstNode;
double lat = Double
.parseDouble(getTextValue(Elmnt, "latitude"));
double lng = Double
.parseDouble(getTextValue(Elmnt, "longitude"));
GeoPoint gp = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapData.add(gp);
}
}
}
public String getTextValue(Element ele, String tagName) {
String textVal = "";
NodeList nl = ele.getElementsByTagName(tagName);
if (nl != null && nl.getLength() > 0) {
Element el = (Element) nl.item(0);
NodeList ndlist = el.getChildNodes();
Node node = ndlist.item(0);
if (node != null)
textVal = node.getNodeValue();
}
return textVal;
}
// handler for the background updating
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
}
};
#Override
protected boolean isRouteDisplayed() {
return false;
}
public void onDirectionsAvailable(Route route,
com.cipl.Courts.DrivingDirections.Mode mode) {
}
public void onDirectionsNotAvailable() {
}
}
The above code draw line between two point on Map in android.

Categories

Resources