i am working with android program here i have two classes PlaceMapActivity and AddItemizedOverlay i want to send a string from PlaceMapActivity to the AddItemizedOverlay class can any one help me to solve this and here is my two classes
AddItemizedOverlay
public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
String reference;
private Activity activity;
String p_u_name;
String username;
public AddItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public AddItemizedOverlay(Drawable defaultMarker, Context context) {
this(defaultMarker);
this.context = context;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
if (event.getAction() == 1) {
GeoPoint geopoint = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
// latitude
double lat = geopoint.getLatitudeE6() / 1E6;
// longitude
double lon = geopoint.getLongitudeE6() / 1E6;
//Toast.makeText(context, "Lat: " + lat + ", Lon: "+lon, Toast.LENGTH_SHORT).show();
}
return false;
}
#Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
#Override
public int size() {
return mapOverlays.size();
}
#Override
protected boolean onTap(int index) {
OverlayItem item = mapOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(this.context);
dialog.setTitle(item.getTitle());
dialog.setMessage("Do you want ot park here ?");
reference = item.getSnippet();
dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences prefs = context.getSharedPreferences("myprefs", 0);
SharedPreferences.Editor editor =prefs.edit();
editor.putString("KEY_REFERENCE", reference);
editor.commit();
Intent intent = new Intent(context, SinglePlaceActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
// MainActivity.this.finish();
}
});
dialog.show();
return true;
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
}
public void populateNow(){
this.populate();
}
}
and the second class is here
PlacesMapActivity.java
public class PlacesMapActivity extends MapActivity {
// Nearest places
PlacesList nearPlaces;
// Map view
MapView mapView;
// Map overlay items
List<Overlay> mapOverlays;
AddItemizedOverlay itemizedOverlay;
GeoPoint geoPoint;
// Map controllers
MapController mc;
double latitude;
double longitude;
OverlayItem overlayitem,wma;
String p_u_name;
Place reference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_places);
// Getting intent data
Intent i = getIntent();
p_u_name = i.getExtras().getString("KEY_USERNAME");
// AddItemizedOverlay its_obj = new AddItemizedOverlay(null);
// its_obj.getstring(p_u_name);
System.out.println("place map activity :got username"+p_u_name);
reference = (Place) i.getSerializableExtra("place_reference");
// Users current geo location
String user_latitude = i.getStringExtra("user_latitude");
String user_longitude = i.getStringExtra("user_longitude");
System.out.println("sarath"+user_latitude + user_longitude);
// Nearplaces list
nearPlaces = (PlacesList) i.getSerializableExtra("near_places");
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
// Geopoint to place on map
geoPoint = new GeoPoint((int) (Double.parseDouble(user_latitude) * 1E6),(int) (Double.parseDouble(user_longitude) * 1E6));
// Drawable marker icon
Drawable drawable_user = this.getResources().getDrawable(R.drawable.mark_red);
itemizedOverlay = new AddItemizedOverlay(drawable_user, this);
// Map overlay item
overlayitem = new OverlayItem(geoPoint, "Your Location","That is you!");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
itemizedOverlay.populateNow();
// Drawable marker icon
Drawable drawable = this.getResources().getDrawable(R.drawable.mark_blue);
itemizedOverlay = new AddItemizedOverlay(drawable, this);
mc = mapView.getController();
// These values are used to get map boundary area
// The area where you can see all the markers on screen
int minLat = Integer.MAX_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int maxLong = Integer.MIN_VALUE;
// check for null in case it is null
if (nearPlaces.results != null) {
// loop through all the places
for (Place place : nearPlaces.results) {
latitude = place.geometry.location.lat; // latitude
longitude = place.geometry.location.lng; // longitude
// Geopoint to place on map
geoPoint = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
// Map overlay item
overlayitem = new OverlayItem(geoPoint,place.name,place.reference);
itemizedOverlay.addOverlay(overlayitem);
// calculating map boundary area
minLat = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
maxLat = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
}
mapOverlays.add(itemizedOverlay);
// showing all overlay items
itemizedOverlay.populateNow();
}
// Adjusting the zoom level so that you can see all the markers on map
mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
// Showing the center of the map
mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
mapView.postInvalidate();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
Semd String when you create AddItemizedOverlay class object.
Write this in your activity class
itemizedOverlay = new AddItemizedOverlay(drawable_user, this,StringData);
Write this in your OverLay class
private String StringData;
public AddItemizedOverlay(Drawable defaultMarker, Context context,String StringData) {
this(defaultMarker);
this.context = context;
this.StringData=StringData;
}
Try this way....
Thanks
Related
I am new to Open Street Map map. I want to put the marker on map where i Tapped. I want to delete previous marker also. Please help me.
Thanks in advance. Here is my code
Overlay touchOverlay = new Overlay(this) {
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay = null;
#Override
protected void draw(Canvas arg0, MapView arg1, boolean arg2) {
}
#Override
public boolean onSingleTapConfirmed(final MotionEvent e,
final MapView mapView) {
Projection proj = mapView.getProjection();
GeoPoint 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);
ArrayList<OverlayItem> overlayArray = new ArrayList<OverlayItem>();
OverlayItem mapItem = new OverlayItem("", "", new GeoPoint(
(((double) loc.getLatitudeE6()) / 1000000),
(((double) loc.getLongitudeE6()) / 1000000)));
Drawable marker = null;
mapItem.setMarker(marker);
overlayArray.add(mapItem);
if (anotherItemizedIconOverlay == null) {
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(
getApplicationContext(), overlayArray, null);
mapView.getOverlays().add(anotherItemizedIconOverlay);
mapView.invalidate();
} else {
mapView.getOverlays().remove(anotherItemizedIconOverlay);
mapView.invalidate();
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(
getApplicationContext(), overlayArray, null);
mapView.getOverlays().add(anotherItemizedIconOverlay);
}
return true;
}
};
Finally i get solution of 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();
}
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();
}
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.
I am able to draw path between two sets of geo-coordinates from reference of
j2memaprouteprovider.
I am able to get current location latitude and longitude.
How do i implement these coordinates in the following class to get path drawn from current position to target position.
MapRouteActivity.java
public class MapRouteActivity extends MapActivity {
LinearLayout linearLayout;
MapView mapView;
private Road mRoad;
static Context context = null;
String GPSPROVIDER = LocationManager.GPS_PROVIDER;
private static final long MIN_GEOGRAPHIC_POOLING_TIME_PERIOD = 10000;
private static final float MIN_GEOGRAPHIC_POOLING_DISTANCE = (float) 5.0;
public LocationManager gpsLocationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
context = this;
/* Get a listener for GPS */
LocationListener gpsLocationListener = null;
gpsLocationListener = new GpsLocationListener(this);
/* Start Location Service for GPS */
gpsLocationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
/* Register GPS listener with Location Manager */
gpsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_GEOGRAPHIC_POOLING_TIME_PERIOD,
MIN_GEOGRAPHIC_POOLING_DISTANCE, gpsLocationListener);
if (gpsLocationManager == null) {
gpsLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_GEOGRAPHIC_POOLING_TIME_PERIOD,
MIN_GEOGRAPHIC_POOLING_DISTANCE, gpsLocationListener);
}
boolean isAvailableGps = gpsLocationManager
.isProviderEnabled(GPSPROVIDER);
if (isAvailableGps) {
Location loc = gpsLocationManager.getLastKnownLocation("gps");
if (loc != null) {
double lattitude = loc.getLatitude();
double longitude = loc.getLongitude();
Toast.makeText(
MapRouteActivity.this,
"Longitude iss " + lattitude + " Latitude iss "
+ longitude, Toast.LENGTH_LONG).show();
}
}
new Thread() {
#Override
public void run() {
double fromLat = 49.85, fromLon = 24.016667, toLat = 50.45, toLon = 30.523333;
String url = RoadProvider
.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
TextView textView = (TextView) findViewById(R.id.description);
textView.setText(mRoad.mName + " " + mRoad.mDescription);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
};
};
private InputStream getConnection(String url) {
InputStream is = null;
try {
URLConnection conn = new URL(url).openConnection();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public static class GpsLocationListener implements LocationListener {
private ImageView mCurrentPointer;
public GpsLocationListener(Context context) {
}
public void onLocationChanged(Location loc) {
if (loc != null) {
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
GeoPoint point = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
Toast.makeText(
context,
"Longitude is " + longitude + " Latitude is "
+ latitude, Toast.LENGTH_LONG).show();
}
}
#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 com.google.android.maps.Overlay {
Road mRoad;
ArrayList<GeoPoint> mPoints;
public MapOverlay(Road road, MapView mv) {
mRoad = road;
if (road.mRoute.length > 0) {
mPoints = new ArrayList<GeoPoint>();
for (int i = 0; i < road.mRoute.length; i++) {
mPoints.add(new GeoPoint((int) (road.mRoute[i][1] * 1000000),
(int) (road.mRoute[i][0] * 1000000)));
}
int moveToLat = (mPoints.get(0).getLatitudeE6() + (mPoints.get(
mPoints.size() - 1).getLatitudeE6() - mPoints.get(0)
.getLatitudeE6()) / 2);
int moveToLong = (mPoints.get(0).getLongitudeE6() + (mPoints.get(
mPoints.size() - 1).getLongitudeE6() - mPoints.get(0)
.getLongitudeE6()) / 2);
GeoPoint moveTo = new GeoPoint(moveToLat, moveToLong);
MapController mapController = mv.getController();
mapController.animateTo(moveTo);
mapController.setZoom(7);
}
}
#Override
public boolean draw(Canvas canvas, MapView mv, boolean shadow, long when) {
super.draw(canvas, mv, shadow);
drawPath(mv, canvas);
return true;
}
public void drawPath(MapView mv, Canvas canvas) {
int x1 = -1, y1 = -1, x2 = -1, y2 = -1;
Paint paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
for (int i = 0; i < mPoints.size(); i++) {
Point point = new Point();
mv.getProjection().toPixels(mPoints.get(i), point);
x2 = point.x;
y2 = point.y;
if (i > 0) {
canvas.drawLine(x1, y1, x2, y2, paint);
}
x1 = x2;
y1 = y2;
}
}
}
I want to assign current position lattiude and longitude value to fromLat and fronLon variable in above code here:
new Thread() {
#Override
public void run() {
double fromLat = 49.85, fromLon = 24.016667, toLat = 50.45, toLon = 30.523333;
String url = RoadProvider
.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
Help !!
Its very Simple---
Make your Activity like this:--
public class GoogleMapLocationActivity extends MapActivity {
private LocationManager myLocationManager;
private LocationListener myLocationListener;
private TextView myLongitude, myLatitude;
private MapView myMapView;
private MapController myMapController;
LinearLayout zoomLayout;
GeoPoint myLastPosition;
AddItemizedOverlay mapOvlay;
private void CenterLocatio(GeoPoint centerGeoPoint)
{
myMapController.animateTo(centerGeoPoint);
List<Overlay> mapOverlays = myMapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.map_point);
if(myLastPosition != null){
mapOvlay = new AddItemizedOverlay(myLastPosition ,centerGeoPoint,drawable );
OverlayItem overlayitem = new OverlayItem(centerGeoPoint,"","" );
mapOvlay.addOverlay(overlayitem);
mapOverlays.add(mapOvlay);
}
myLastPosition = centerGeoPoint;
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myMapView = (MapView)findViewById(R.id.mapview);
myLastPosition = null;
myMapController = myMapView.getController();
myMapController.setZoom(18); //Fixed Zoom Level
myLocationManager = (LocationManager)getSystemService(
Context.LOCATION_SERVICE);
myLocationListener = new MyLocationListener();
myLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
myLocationListener);
private class MyLocationListener implements LocationListener{
public void onLocationChanged(Location argLocation) {
GeoPoint myGeoPoint = new GeoPoint(
(int)(argLocation.getLatitude()*1000000),
(int)(argLocation.getLongitude()*1000000));
GeoPoint newGeoPoint = new GeoPoint(myGeoPoint.getLatitudeE6() ,myGeoPoint.getLongitudeE6());
CenterLocatio(newGeoPoint);
}
public void onProviderDisabled(String provider) {
Toast.makeText(getBaseContext(),"GPS Disabled" ,Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getBaseContext(),"GPS Enabled" ,Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider,
int status, Bundle extras) {
Toast.makeText(getBaseContext(),"GPS Unavailable" ,Toast.LENGTH_SHORT).show();
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
};
}
AddItemizedOverlay.class-----
public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
private GeoPoint mGpt1;
private GeoPoint mGpt2;
public AddItemizedOverlay(GeoPoint gp1,GeoPoint gp2, Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
mGpt1 = gp1;
mGpt2 = gp2;
}
public AddItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public AddItemizedOverlay(Drawable defaultMarker, Context context) {
this(defaultMarker);
this.context = context;
}
#Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
#Override
public int size() {
return mapOverlays.size();
}
#Override
protected boolean onTap(int index) {
Log.e("Tap", "Tap Performed");
return true;
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
this.populate();
}
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
Paint paint;
paint = new Paint();
paint.setColor(Color.RED);
paint.setAntiAlias(true);
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(2);
Point pt1 = new Point();
Point pt2 = new Point();
Projection projection = mapView.getProjection();
projection.toPixels(mGpt1, pt1);
projection.toPixels(mGpt2, pt2);
canvas.drawLine(pt1.x, pt1.y, pt2.x, pt2.y, paint);
return true;
}
}
Hope it will help you...
Use following, It will display direction on native map application,
final Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(
"http://maps.google.com/maps?" +
"saddr="+YOUR_START_LONGITUDE+","+YOUR_START_LATITUDE+"&daddr="YOUR_END_LONGITUDE+","+YOUR_END_LATITUDE));
intent.setClassName(
"com.google.android.apps.maps",
"com.google.android.maps.MapsActivity");
startActivity(intent);
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()