Marker on OpenStreetMap is draw slow - android

I am using OSM maps in my App. I am using 3.0.8 jar file for osmdroid. i have an issue with when i draw custom marker on Map it draw after 2-3 seconds. I goggled it find a solution that use library 3.0.5 osmdroid. when i tried it gives error that android dependencies failed. so please give me way that can i solve this problem.
here is my code for draw a custom marker.
public class Map extends Activity {
GoogleMap gMap;
static int loginCheck = 0;
ConnectionDetector conDec;
ArrayList<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
SharedPreferences prefs;
LatLng latLng;
MarkerOptions markerOptions;
LinearLayout botlay;
EditText desc;
MyItemizedOverlay myItemizedOverlay = null;
MyLocationOverlay myLocationOverlay = null;
ArrayList<OverlayItem> anotherOverlayItemArray, overlayItemArray;
GeoPoint p, loc, currentLocationPixels, t;
GeoPoint myPoint1;
Projection proj;
GPSTracker gps;
double my_Latitude, my_Longitude;
private MapView mapView;
private MapController myMapController;
public int count = 0;
EditText ed1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map1);
ed1 = (EditText) findViewById(R.id.descr);
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
mapView = (MapView) findViewById(R.id.mapViewosm);
mapView.setBuiltInZoomControls(true);
mapView.setMultiTouchControls(true);
myMapController = mapView.getController();
myMapController.setZoom(15);
ScaleBarOverlay myScaleBarOverlay = new ScaleBarOverlay(this);
mapView.getOverlays().add(myScaleBarOverlay);
Drawable marker = getResources().getDrawable(
android.R.drawable.star_big_on);
int markerWidth = marker.getIntrinsicWidth();
int markerHeight = marker.getIntrinsicHeight();
marker.setBounds(0, markerHeight, markerWidth, 0);
ResourceProxy resourceProxy = new DefaultResourceProxyImpl(
getApplicationContext());
myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy);
// add overlay for current location..RAJ
MyCurrentItemizedOverlay myCurrentLocationOverlay = new MyCurrentItemizedOverlay(
marker, resourceProxy);
mapView.getOverlays().add(myCurrentLocationOverlay);
mapView.getOverlays().add(myItemizedOverlay);
// mapView.postInvalidate();
gps = new GPSTracker(Map.this);
// check if GPS enabled
if (gps.canGetLocation()) {
while (gps.getLatitude() == 0.0 || gps.getLongitude() == 0.0) {
gps.canGetLocation();
}
my_Latitude = gps.getLatitude();
my_Longitude = gps.getLongitude();
// \n is for new line
// Toast.makeText(getApplicationContext(),
// "Your Location is - \nLat: " + my_Latitude + "\nLong: " +
// my_Longitude, Toast.LENGTH_LONG).show();
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
// set the current loaction for clicked location..
p = new GeoPoint((int) (my_Latitude * 1E6), (int) (my_Longitude * 1E6));
// add overlay for current location..RAJ
currentLocationPixels = new GeoPoint((int) (my_Latitude * 1E6),
(int) (my_Longitude * 1E6));
// its mine..
Toast.makeText(
getApplicationContext(),
"Your Location is - \nLat: " + my_Latitude + "\nLong: "
+ my_Longitude, Toast.LENGTH_LONG).show();
// ConvertPointToLocation(currentLocationPixels);
myLocationOverlay = new MyLocationOverlay(this, mapView);
// mapView.getOverlays().add(myLocationOverlay);
// myLocationOverlay.enableMyLocation();
// myLocationOverlay.getMyLocation();
mapView.invalidate();
// String coordinates[] = {
// myLocationOverlay.getMyLocation().getLatitudeE6()+"",
// myLocationOverlay.getMyLocation().getLatitudeE6()+"" };
// double lat = (double)
// myLocationOverlay.getMyLocation().getLatitudeE6();
// double lng = (double)
// myLocationOverlay.getMyLocation().getLongitudeE6();
// //
// //
// p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
// mapView.postInvalidate();
// double lat = (double) loc.getLatitudeE6();
// double lng = (double) loc.getLongitudeE6();
// addLocation(my_Latitude, my_Longitude);
// myLocationOverlay.runOnFirstFix(new Runnable() {
// public void run() {
// mapView.getController().animateTo(
// myLocationOverlay.getMyLocation());
// }
// });
// mapView.getOverlays().add(touchOverlay);
}
// private void addLocation(double lat, double lng) {
// // ---Add a location marker---
//
// p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
//
// Drawable marker = getResources().getDrawable(
// android.R.drawable.star_big_on);
// int markerWidth = marker.getIntrinsicWidth();
// int markerHeight = marker.getIntrinsicHeight();
// marker.setBounds(0, markerHeight, markerWidth, 0);
//
// ResourceProxy resourceProxy = new DefaultResourceProxyImpl(
// getApplicationContext());
//
// myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy);
// mapView.getOverlays().add(myItemizedOverlay);
//
// List<Overlay> listOfOverlays = mapView.getOverlays();
// listOfOverlays.clear();
// listOfOverlays.add(myItemizedOverlay);
// mapView.invalidate();
// }
#Override
protected void onResume() {
super.onResume();
myLocationOverlay.enableMyLocation();
myLocationOverlay.enableFollowLocation();
}
#Override
protected void onPause() {
super.onPause();
myLocationOverlay.disableMyLocation();
myLocationOverlay.disableFollowLocation();
}
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> overlayItemList = new ArrayList<OverlayItem>();
public MyItemizedOverlay(Drawable pDefaultMarker,
ResourceProxy pResourceProxy) {
super(pDefaultMarker, pResourceProxy);
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean arg2) {
super.draw(canvas, mapView, arg2);
// ---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
// ---add the marker---
if (count == 1) {
int caller = getIntent().getIntExtra("button", 0);
switch (caller) {
case R.id.btMap:
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_annotation_darkblue);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 50, null);
break;
case R.id.imageButton1:
Bitmap bmp1 = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_annotation_green);
canvas.drawBitmap(bmp1, screenPts.x, screenPts.y - 50, null);
break;
case R.id.imageButton2:
Bitmap bmp2 = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_annotation_bue);
canvas.drawBitmap(bmp2, screenPts.x, screenPts.y - 50, null);
break;
case R.id.imageButton3:
Bitmap bmp3 = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_annotation_light);
canvas.drawBitmap(bmp3, screenPts.x, screenPts.y - 50, null);
break;
case R.id.imageButton4:
Bitmap bmp4 = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_annotation_purple);
canvas.drawBitmap(bmp4, screenPts.x, screenPts.y - 50, null);
break;
case R.id.imageButton5:
Bitmap bmp5 = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_annotation_red);
canvas.drawBitmap(bmp5, screenPts.x, screenPts.y - 50, null);
break;
case R.id.imageButton6:
Bitmap bmp6 = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_annotation_yellow);
canvas.drawBitmap(bmp6, screenPts.x, screenPts.y - 50, null);
break;
}
}
// Bitmap bmp = BitmapFactory.decodeResource(getResources(),
// R.drawable.pin_annotation_green);
// if (count == 1) {
// canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 50, null);
// }
}
public void addItem(GeoPoint p, String title, String snippet) {
OverlayItem newItem = new OverlayItem(title, snippet, p);
overlayItemList.add(newItem);
populate();
}
#Override
public boolean onSnapToItem(int arg0, int arg1, Point arg2,
IMapView arg3) {
return false;
}
#Override
protected OverlayItem createItem(int arg0) {
return overlayItemList.get(arg0);
}
#Override
public int size() {
return overlayItemList.size();
}
#Override
public boolean onLongPress(MotionEvent e, MapView mapView) {
proj = mapView.getProjection();
loc = (GeoPoint) proj.fromPixels((int) e.getX(), (int) e.getY());
ConvertPointToLocation(loc);
return true;
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e, MapView mapView) {
count = 1;
Projection proj = mapView.getProjection();
p = (GeoPoint) proj.fromPixels((int) e.getX(), (int) e.getY());
// ConvertPointToLocation(p);
return true;
}
}
public class MyCurrentItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> overlayItemList = new ArrayList<OverlayItem>();
public MyCurrentItemizedOverlay(Drawable pDefaultMarker,
ResourceProxy pResourceProxy) {
super(pDefaultMarker, pResourceProxy);
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean arg2) {
super.draw(canvas, mapView, arg2);
// ---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(currentLocationPixels, screenPts);
// ---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_annotation_current_location);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 50, null);
}
public void addItem(GeoPoint p, String title, String snippet) {
OverlayItem newItem = new OverlayItem(title, snippet, p);
overlayItemList.add(newItem);
populate();
}
#Override
public boolean onSnapToItem(int arg0, int arg1, Point arg2,
IMapView arg3) {
return false;
}
#Override
protected OverlayItem createItem(int arg0) {
return overlayItemList.get(arg0);
}
#Override
public int size() {
return overlayItemList.size();
}
}
// Method for convert the lat & long into Address
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6, point.getLongitudeE6() / 1E6,
1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0)
.getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT)
.show();
} catch (IOException e) {
e.printStackTrace();
}
return address;
}
public void btHome(View v) {
startActivity(new Intent(Map.this, JamInfo.class));
}
public void btMap(View v) {
}
public void btReport(View v) {
startActivity(new Intent(Map.this, Report.class));
}
public void btSetting(View v) {
startActivity(new Intent(Map.this, Setting.class));
}
}

The first thing I would try to is to stop allocating Bitmaps every draw cycle. Your draw() methods should be as fast as possible and allocating objects in that method will surely slow things down - especially if the garbage collector has to run. You should create all those Bitmaps in the constructor and store them in variables. Also it is recommended that you don't call toPixels() every draw cycle if you can avoid it - call it only when the location changes and store it (and update it if the zoom level changes).
Take a look at the sample application OpenStreetMapViewer for some well-crafted examples of how to use osmdroid.

Related

How to make the touch event in openstreetmap android

I am suffering in OSM map. This new for me. I want to print the Toast message on Single-click and on Long press I try all things that can i do. But i don't get the right way. Here is my code. Please give me right way to solve this. Thanks in dvance. please
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map1);
final MapView mapView = (MapView) findViewById(R.id.mapViewosm);
mapView.setBuiltInZoomControls(true);
MapController myMapController = mapView.getController();
myMapController.setZoom(13);
ScaleBarOverlay myScaleBarOverlay = new ScaleBarOverlay(this);
mapView.getOverlays().add(myScaleBarOverlay);
Drawable marker = getResources().getDrawable(
android.R.drawable.star_big_on);
int markerWidth = marker.getIntrinsicWidth();
int markerHeight = marker.getIntrinsicHeight();
marker.setBounds(0, markerHeight, markerWidth, 0);
ResourceProxy resourceProxy = new DefaultResourceProxyImpl(
getApplicationContext());
myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy);
mapView.getOverlays().add(myItemizedOverlay);
GeoPoint myPoint1 = new GeoPoint(0 * 1000000, 0 * 1000000);
myItemizedOverlay.addItem(myPoint1, "myPoint1", "myPoint1");
GeoPoint myPoint2 = new GeoPoint(50 * 1000000, 50 * 1000000);
myItemizedOverlay.addItem(myPoint2, "myPoint2", "myPoint2");
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
myLocationOverlay.enableMyLocation();
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(
myLocationOverlay.getMyLocation());
}
});
// 2nd
// // --- Create Overlay
// overlayItemArray = new ArrayList<OverlayItem>();
//
// DefaultResourceProxyImpl defaultResourceProxyImpl = new
// DefaultResourceProxyImpl(
// this);
// MyItemizedIconOverlay myItemizedIconOverlay = new
// MyItemizedIconOverlay(
// overlayItemArray, null, defaultResourceProxyImpl);
// mapView.getOverlays().add(myItemizedIconOverlay);
// // ---
// locationManager = (LocationManager)
// getSystemService(Context.LOCATION_SERVICE);
//
// // for demo, getLastKnownLocation from GPS only, not from NETWORK
// Location lastLocation = locationManager
// .getLastKnownLocation(LocationManager.GPS_PROVIDER);
// if (lastLocation != null) {
// updateLoc(lastLocation);
// }
// 1st
anotherOverlayItemArray = new ArrayList<OverlayItem>();
anotherOverlayItemArray.add(new OverlayItem("0, 0", "0, 0",
new GeoPoint(0, 0)));
anotherOverlayItemArray.add(new OverlayItem("US", "US", new GeoPoint(
38.883333, -77.016667)));
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay = new
ItemizedIconOverlay<OverlayItem>(
this, anotherOverlayItemArray, myOnItemGestureListener);
mapView.getOverlays().add(anotherItemizedIconOverlay);
}
// 1st
OnItemGestureListener<OverlayItem> myOnItemGestureListener = new
OnItemGestureListener<OverlayItem>() {
#Override
public boolean onItemLongPress(int arg0, OverlayItem arg1) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "long tap",
Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onItemSingleTapUp(int index, OverlayItem item) {
Toast.makeText(getApplicationContext(), "single tap",
Toast.LENGTH_SHORT).show();
Toast.makeText(
Map.this,
item.mDescription + "\n" + item.mTitle + "\n"
+ item.mGeoPoint.getLatitudeE6() + " : "
+ item.mGeoPoint.getLongitudeE6(),
Toast.LENGTH_LONG).show();
return true;
}
};
in osm you can use MapEventsReceiver like blew to detect taps:
MapEventsReceiver mReceive = new MapEventsReceiver() {
#Override
public boolean singleTapConfirmedHelper(GeoPoint p) {
// write your code here
return false;
}
#Override
public boolean longPressHelper(GeoPoint p) {
// write your code here
return false;
}
};
MapEventsOverlay OverlayEvents = new MapEventsOverlay(getBaseContext(), mReceive);
map.getOverlays().add(OverlayEvents);
source:https://github.com/osmdroid/osmdroid/issues/295
Finally i got solution for this problem. here is my answer
#Override
public boolean onSingleTapConfirmed(MotionEvent e, MapView mapView) {
Projection proj = mapView.getProjection();
p = (GeoPoint) proj.fromPixels((int) e.getX(), (int) e.getY());
proj = mapView.getProjection();
loc = (GeoPoint) proj.fromPixels((int) e.getX(), (int) e.getY());
String longitude = Double
.toString(((double) loc.getLongitudeE6()) / 1000000);
String latitude = Double
.toString(((double) loc.getLatitudeE6()) / 1000000);
Toast toast = Toast.makeText(getApplicationContext(),
"Longitude: "
+ longitude + " Latitude: " + latitude, Toast.LENGTH_SHORT);
toast.show();
return true;
}
private void addLocation(double lat, double lng) {
// ---Add a location marker---
p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
Drawable marker = getResources().getDrawable(
android.R.drawable.star_big_on);
int markerWidth = marker.getIntrinsicWidth();
int markerHeight = marker.getIntrinsicHeight();
marker.setBounds(0, markerHeight, markerWidth, 0);
ResourceProxy resourceProxy = new DefaultResourceProxyImpl(
getApplicationContext());
myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(myItemizedOverlay);
mapView.invalidate();
}

HowTo OnTouch on a paint overlay (Google maps)?

I paint a overlay on my Google maps view (closed polygon, filled). But now I don't know how to pop up a toast when I tap on the overlay. The most examples which I found work with marker and looks very different to my code.
Main Activity:
public class BOSLstItemDetail extends MapActivity{
ArrayList<HashMap<String, Object>> boslst;
MapView mapView;
MapController mapcontrol;
GeoPoint p;
Polygon polygon;
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.boslst_item_detail);
String coordinates[] = {"48.098056", "9.788611"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
MapView mapView = (MapView) findViewById(R.id.mapview);
mapcontrol = mapView.getController();
mapcontrol.animateTo(p);
mapcontrol.setZoom(10);
mapView.setBuiltInZoomControls(true);
ArrayList<GeoPoint> points = new ArrayList<GeoPoint>();
try{
InputStream koord = getAssets().open("gps.txt");
if (koord != null) {
InputStreamReader input = new InputStreamReader(koord);
BufferedReader buffreader = new BufferedReader(input);
String line;
while (( line = buffreader.readLine()) != null) {
String[] point_t = line.split(",");
double y = Double.parseDouble(point_t[0]);
double x = Double.parseDouble(point_t[1]);
points.add(new GeoPoint((int)(x*1e6), (int)(y*1e6)));
}
koord.close();
polygon = new Polygon(points);
}
}catch (Exception e) {
Log.e("APP","Failed", e);
}
mapView.getOverlays().clear();
mapView.getOverlays().add(polygon);
mapView.invalidate();
}
}
Polygon.java
public class Polygon extends Overlay {
ArrayList<GeoPoint> geoPoints;
public Polygon(ArrayList<GeoPoint> points){
geoPoints = points;
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow){
//Set the color and style
Paint paint = new Paint();
paint.setColor(Color.parseColor("#88ff0000"));
paint.setAlpha(50);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
//Create path and add points
Path path = new Path();
Point firstPoint = new Point();
mapView.getProjection().toPixels(geoPoints.get(0), firstPoint);
path.moveTo(firstPoint.x, firstPoint.y);
for(int i = 1; i < geoPoints.size(); ++i){
Point nextPoint = new Point();
mapView.getProjection().toPixels(geoPoints.get(i), nextPoint);
path.lineTo(nextPoint.x, nextPoint.y);
}
//Close polygon
path.lineTo(firstPoint.x, firstPoint.y);
path.setLastPoint(firstPoint.x, firstPoint.y);
canvas.drawPath(path, paint);
super.draw(canvas, mapView, shadow);
}
}
gps.txt:
9.34669876098644,48.2405319213867
9.36384963989269,48.2296714782715
9.3639497756958,48.2259712219238
9.87827968597418,48.2786293029785
9.87261867523205,48.2822494506837
9.87254810333263,48.2859611511232
9.88368034362787,48.2898597717285
9.8835382461549,48.2972793579102
9.72781181335461,47.9827613830566
9.72225093841558,47.9826812744141
9.72232818603527,47.9789619445801
9.71129894256597,47.9750900268555
9.70574092864985,47.9750099182129
9.70557022094732,47.9824409484864
9.69992923736572,47.9860801696778
9.69436073303234,47.9860000610352
9.33546066284174,48.2403602600099
9.34669876098644,48.2405319213867
If you're extending Overlay, you can override the OnTap method:
protected boolean onTap(final int index)
{
OverlayItem item = mOverlays.get(index);
if(item != null){
Toast.makeText(mContext, textToShow, Toast.LENGTH_SHORT).show();
}
//return true to indicate we've taken care of it
return true;
}

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.

loading map issue

I have captured a screenshot of my current location from a mapview and import it to my application frm sd card.I integrated the map using a map view.So wen my application is ran and when the map is loaded some square boxes are coming in my map.after capturing the image.when open the image that crsses are coming.why its happening like that.anyone has an idea.my sample screen shot and code is mentioned below.
![public void onClick(View v) {
getMapImage();
saveMapImage();
}
});
// enable Street view by default
mapView.setStreetView(true);
// enable to show Satellite view
// mapView.setSatellite(true);
// enable to show Traffic on map
// mapView.setTraffic(true);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(16);
}
private Bitmap getMapImage() {
/* Position map for output */
MapController mc = mapView.getController();
// mc.setCenter(SOME_POINT);
mc.setZoom(16);
/* Capture drawing cache as bitmap */
mapView.setDrawingCacheEnabled(true);
Bitmap bmp = Bitmap.createBitmap(mapView.getDrawingCache());
mapView.setDrawingCacheEnabled(false);
return bmp;
}
private void saveMapImage() {
String filename = "foo.png";
File f = new File("/sdcard/", filename);
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp = getMapImage();
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
private class GPSLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
/* Toast.makeText(getBaseContext(),
"Latitude: " + location.getLatitude() +
" Longitude: " + location.getLongitude(),
Toast.LENGTH_SHORT).show();*/
mapController.animateTo(point);
mapController.setZoom(16);
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
String address = ConvertPointToLocation(point);
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
mapView.invalidate();
}
}
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
return address;
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
class MapOverlay extends Overlay
{
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw(
) {
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.red);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null); // 24 is the height of image
return true;
}
}][1]
may you try mapView.setStreetView(false); , I once had the same issue and found out that it was because of setting the street view with true.

Android Map with current location

i have got the following codes but my gps is not getting the current location, showing me the address on touch and no overlay. I got the latitude and longitude as 0.0. Basically only the map is showing up. Help is greatly appreciated. Thank you!
public class Map extends MapActivity{
MapView mapView;
MapController mc;
GeoPoint p;
private LocationManager lm;
private LocationListener locationListener;
Button btn_send;
int lat, lng;
class MapOverlay extends com.google.android.maps.Overlay
{
#Override
public boolean draw(Canvas canvas, MapView mapView,
boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
//---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(
getResources(), R.drawable.pin);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6,
p.getLongitudeE6() / 1E6, 1);
String add = "";
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();
i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
else
return false;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
MapController mc = mapView.getController();
switch (keyCode)
{
case KeyEvent.KEYCODE_3:
mc.zoomIn();
break;
case KeyEvent.KEYCODE_1:
mc.zoomOut();
break;
}
return super.onKeyDown(keyCode, event);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, new GeoUpdateHandler());
Button btnSend = (Button) findViewById(R.id.btn_send);
btnSend.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent new_intent = new Intent("net.learn2develop.SendSMS");
startActivity(new_intent);
}
});
mapView = (MapView) findViewById(R.id.mapView);
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);
mapView.setSatellite(false);
mapView.setStreetView(true);
mc = mapView.getController();
String latitude = Integer.toString(lat);
String longitude = Integer.toString(lng);
String coordinates[] = {latitude, longitude};
double lati = Double.parseDouble(coordinates[0]);
double lngi = Double.parseDouble(coordinates[1]);
System.out.println("lat" + lati + "lng" + lngi );
p = new GeoPoint(
(int) (lati * 1E6),
(int) (lngi * 1E6));
mc.animateTo(p);
mc.setZoom(17);
mapView.invalidate();
//---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
lat = (int) (location.getLatitude() * 1E6);
lng = (int) (location.getLongitude() * 1E6);
System.out.println("lat shld b smth " + lat + "lng smth " +lng);
//GeoPoint point = new GeoPoint(lat, lng);
//mc.animateTo(point); // mapController.setCenter(point);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
If you want to display the current location of the user, you might be better off using the MyLocationOverlay. You can also subclass it and override onLocationChanged, to insert custom code.
Enable it by calling enableMyLocation onResume() and disableMyLocation onPause().
It take 2 to 15 minutes to get a satellite GPS fix. You should move the code for rendering the point to onLocationChanged()

Categories

Resources