Location change and put Marker on Click in openstreetmap - android

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();
}

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();
}

Marker on OpenStreetMap is draw slow

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.

google map android marker always point on a same position?

i want to display my location and destination location at map. the problem is that the destination location always point at same location even if i change another destination long and lat...
here is the code
protected void tampilkanPosisikeMap(Location newLocation) {
List<Overlay> overlays = mapView.getOverlays();
if (overlays.size() > 0) {
for (Iterator iterator = overlays.iterator(); iterator.hasNext();) {
iterator.next();
iterator.remove();
}
}
GeoPoint geopoint = new GeoPoint(
(int) (newLocation.getLatitude() * 1E6), (int) (newLocation
.getLongitude() * 1E6));
GeoPoint myposition = geopoint;
Location locationA = new Location("point A");
Location locationB = new Location("point B");
locationA.setLatitude(geopoint.getLatitudeE6() / 1E6);
locationA.setLongitude(geopoint.getLongitudeE6() / 1E6);
Drawable icon1 = getResources().getDrawable(R.drawable.user);
icon1.setBounds(0, 0, icon1.getIntrinsicWidth(), icon1
.getIntrinsicHeight());
MyItemizedOverlay overlay1 = new MyItemizedOverlay(icon1, this);
OverlayItem item1 = new OverlayItem(geopoint, "Posisi Anda", "Lat:"
+ locationA.getLatitude() + "\nLng:" + locationA.getLongitude());
overlay1.addItem(item1);
mapView.getOverlays().add(overlay1);
String lat2,longi2;
String nama_rs;String alamat_rs;
nama_rs = getIntent().getExtras().getString("namarsakit");
alamat_rs = getIntent().getExtras().getString("alamatrsakit");
lat2 = getIntent().getExtras().getString("lat");
longi2 = getIntent().getExtras().getString("longi");
Double lintang_rs = Double.parseDouble(lat2);
Double bujur_rs = Double.parseDouble(longi2);
GeoPoint geopoint1 = new GeoPoint(
(int) (lintang_rs * 1E6),
(int) (bujur_rs * 1E6));
locationB.setLatitude(geopoint1.getLatitudeE6() / 1E6);
locationB.setLongitude(geopoint1.getLongitudeE6() / 1E6);
DecimalFormat formatData = new DecimalFormat("#.#");
float distance = (float) locationA.distanceTo(locationB) / 1000;
String jarak;
jarak = String.valueOf(formatData.format(distance));
Drawable icon = getResources().getDrawable(R.drawable.marker); //
icon.setBounds(0, 0, icon.getIntrinsicWidth(), icon
.getIntrinsicHeight());
MyItemizedOverlay overlay = new MyItemizedOverlay(icon, this); //
OverlayItem item = new OverlayItem(geopoint1, nama_rs, //
alamat_rs
+ "\n\nJarak dari Posisi Anda : " + jarak + " km");
overlay.addItem(item);
mapView.getOverlays().add(overlay);
Toast.makeText(MapDetailActivity.this,"nama = "+nama_rs+"lat tujuan= "+lintang_rs+"long tujuan = "+bujur_rs, Toast.LENGTH_SHORT).show();
mapView.getController().animateTo(geopoint1);
}
this is the destination code from above :
String lat2,longi2;
String nama_rs;String alamat_rs;
nama_rs = getIntent().getExtras().getString("namarsakit");
alamat_rs = getIntent().getExtras().getString("alamatrsakit");
lat2 = getIntent().getExtras().getString("lat");
longi2 = getIntent().getExtras().getString("longi");
Double lintang_rs = Double.parseDouble(lat2);
Double bujur_rs = Double.parseDouble(longi2);
GeoPoint geopoint1 = new GeoPoint(
(int) (lintang_rs * 1E6),
(int) (bujur_rs * 1E6));
locationB.setLatitude(geopoint1.getLatitudeE6() / 1E6);
locationB.setLongitude(geopoint1.getLongitudeE6() / 1E6);
DecimalFormat formatData = new DecimalFormat("#.#");
float distance = (float) locationA.distanceTo(locationB) / 1000;
String jarak;
jarak = String.valueOf(formatData.format(distance));
Drawable icon = getResources().getDrawable(R.drawable.marker); //
icon.setBounds(0, 0, icon.getIntrinsicWidth(), icon
.getIntrinsicHeight());
MyItemizedOverlay overlay = new MyItemizedOverlay(icon, this); //
OverlayItem item = new OverlayItem(geopoint1, nama_rs, //
alamat_rs
+ "\n\nJarak dari Posisi Anda : " + jarak + " km");
overlay.addItem(item);
mapView.getOverlays().add(overlay);
Toast.makeText(MapDetailActivity.this,"nama = "+nama_rs+"lat tujuan= "+lintang_rs+"long tujuan = "+bujur_rs, Toast.LENGTH_SHORT).show();
mapView.getController().animateTo(geopoint1);
For You to be able to show your Current location you must tap on to GPS location provider or Network Location provider. Looking at your code I cannot see any of this. Please note on emulator DDMS will default to a specific location. unless you supply one yourself

Android google maps show geo points which are closest to current location

Is there any way If I have like 100 geo points added in my MapActivity and I want to show only these which are like 1000m away from my current location. The other ones should not be visible on the map.
Any suggestions?
Ok, here is the example. You can subclass Overlay class and override draw method. Whenever the Overlay is invalidated, you should check if your points are within 1000m from your location. Off course, you should know your location within your overlay class. The flowing is the example:
public class MyMapOverlay extends Overlay {
Bitmap bmp;
Context context;
public MyMapOverlay()
{
bmp = BitmapFactory.decodeResource(MyApplication.getContext().getResources(), R.drawable.myplace);
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
for(int i = 0;i<points.size(); i++)
{
GeoPoint point = points.get(i);
Location locationA = new Location("point " + String.valueOf(i));
locationA.setLatitude(point.getLatitudeE6());
locationA.setLongitude(point.getLongitudeE6());
float distance = myLocation.distanceTo(locationA);
if(distance < 1000.0)
{
mapView.getProjection().toPixels(p, screenPts);
canvas.drawBitmap(bmp, screenPts.x-bmp.getWidth()/2, screenPts.y-bmp.getHeight(), null);
}
}
return true;
}
With some help of the first answer I find this solution :
if(location != null){
Location locA = new Location("gps");
GeoPoint myLoc = new GeoPoint((int)(location.getLatitude() * 1E6), (int)(location.getLongitude() * 1E6));
mapController.animateTo(myLoc);
String sqlbars = "SELECT DISTINCT id, latitude, longitude, address, " +
" (SELECT category FROM bars_categories WHERE bar_id=bars.id) AS category " +
" FROM bars WHERE is_active=1";
Cursor curBars = dbHelper.executeSQLQuery(sqlbars);
if(curBars != null){
if(curBars.getCount() > 0){
for(curBars.move(0);curBars.moveToNext();curBars.isAfterLast()){
double latitude = curBars.getDouble(curBars.getColumnIndex("latitude"));
double longitude = curBars.getDouble(curBars.getColumnIndex("longitude"));
final List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = SofiaLiveNearbyActivity.this.getResources().getDrawable(R.drawable.pin_map_icon);
int markerWidth = drawable.getIntrinsicWidth();
int markerHeight = drawable.getIntrinsicHeight();
drawable.setBounds(0, markerHeight, markerWidth, 0);
final HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, SofiaLiveNearbyActivity.this);
GeoPoint point = new GeoPoint((int)(latitude * 1E6),(int)(longitude *1E6));
OverlayItem overlayitem = new OverlayItem(point, "Type: "+category+"\n----------------\nAddress: "+address, id);
locA.setLatitude(latitude);
locA.setLongitude(longitude);
float distance = location.distanceTo(locA);
if(distance < 1000.0){
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
}
}
curBars.close();
}
and it worked.

I m trying to use google maps in my Android App. If I click on any position in the map, i want the search editbox to dispay its location

I m trying to use google maps in my Android App. If I click on any position in the map, i want the search editbox to dispay its location but somehow its not getting updated. I can dispaly a toast bt not the text in my Search box.Please tell me what I am doing wrong. Any help will be highly appreciated. Thanks in advance.
Here is my code
public class GooglemapsActivity extends MapActivity
{
EditText txtSearch;
MapView mapView;
MapController mc;
GeoPoint p;
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
//EditText name = (EditText) this.findViewById(R.id.travelNameText);
// name.setText(txtSearch.getText().toString());
}
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.icon);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
//---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;
}
}
/** Called when the activity is first created. */
#Override
protected boolean isRouteDisplayed()
{
return false;
}
public void changeMap(String area)
{
mapView = (MapView) findViewById(R.id.mapview);
MapController mc=mapView.getController();
GeoPoint myLocation=null;
double lat = 0;
double lng = 0;
try
{
Geocoder g = new Geocoder(this, Locale.getDefault());
java.util.List<android.location.Address> result=g.getFromLocationName(area, 1);
if(result.size()>0){
Toast.makeText(GooglemapsActivity.this, "country: " +
String.valueOf(result.get(0).getCountryName()), Toast.LENGTH_SHORT).show();
lat = result.get(0).getLatitude();
lng = result.get(0).getLongitude();
EditText name = (EditText) this.findViewById(R.id.txtMapSearch);
name.setText("country: " +
String.valueOf(result.get(0).getCountryName()).toString());
}
else{
Toast.makeText(GooglemapsActivity.this, "record not found"
,Toast.LENGTH_SHORT).show();
return;
}
}
catch(IOException io)
{
Toast.makeText(GooglemapsActivity.this, "Connection Error"
, Toast.LENGTH_SHORT).show();
}
myLocation = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
//Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
mc.animateTo(myLocation);
mc.setZoom(10);
mapView.invalidate();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
Button btnSearch=(Button) findViewById(R.id.btnSearch);
//txtSearch=(EditText)findViewById(R.id.c);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtSearch=(EditText)findViewById(R.id.txtMapSearch);
String area=txtSearch.getText().toString();
GooglemapsActivity.this.changeMap(area);
}
});
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);
mc = mapView.getController();
String coordinates[] = {"1.352566007", "103.78921587"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.animateTo(p);
mc.setZoom(17);
mapView.invalidate();
mc.animateTo(p);
mc.setZoom(17);
//---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
}
use:
EditText name = (EditText) GooglemapsActivity.this.findViewById(R.id.txtMapSearch);
instead of
EditText name = (EditText) this.findViewById(R.id.txtMapSearch);
I got a solution to the problem. In the OnTouchEvent where i am creating the toast, i needed to set the text in my edit box at that position. Thanks for trying though.
here is the code:
public class GooglemapsActivity extends MapActivity
{
EditText txtSearch;
EditText TravelFrom;
MapView mapView;
MapController mc;
GeoPoint p;
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.icon);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
//---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; <addresses.get(0).getMaxAddressLineIndex();
i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
txtSearch = (EditText) GooglemapsActivity.this.
findViewById(R.id.txtMapSearch);
txtSearch.setText(add);
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
else
return false;
}
}
/** Called when the activity is first created. */
#Override
protected boolean isRouteDisplayed()
{
return false;
}
public void changeMap(String area)
{
mapView = (MapView) findViewById(R.id.mapview);
MapController mc=mapView.getController();
GeoPoint myLocation=null;
double lat = 0;
double lng = 0;
try
{
Geocoder g = new Geocoder(this, Locale.getDefault());
java.util.List<android.location.Address> result=g.getFromLocationName(area, 1);
if(result.size()>0){
Toast.makeText(GooglemapsActivity.this, "country: " + String.
valueOf(result.get(0).getCountryName()), Toast.LENGTH_SHORT).show();
lat = result.get(0).getLatitude();
lng = result.get(0).getLongitude();
//EditText name = (EditText) this.findViewById(R.id.txtMapSearch);
txtSearch = (EditText)GooglemapsActivity.this.findViewById(R.id.txtMapSearch);
txtSearch.setText("country: " + String.valueOf(result.get(0).
getCountryName()).toString());
}
else{
Toast.makeText(GooglemapsActivity.this,"record not
found", Toast.LENGTH_SHORT).show();
return;
}
}
catch(IOException io){
Toast.makeText(GooglemapsActivity.this,"ConnectionError",
Toast.LENGTH_SHORT).show();
}
myLocation = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
// Drawable drawable = this.getResources().getDrawable(R.drawable.bubble);
mc.animateTo(myLocation);
mc.setZoom(10);
mapView.invalidate();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
Button btnSearch=(Button) findViewById(R.id.btnSearch);
//txtSearch=(EditText)findViewById(R.id.c);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtSearch=(EditText)findViewById(R.id.txtMapSearch);
String area=txtSearch.getText().toString();
GooglemapsActivity.this.changeMap(area);
}
});
Button btnDone=(Button) findViewById(R.id.btnDone);
//txtSearch=(EditText)findViewById(R.id.c);
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtSearch=(EditText)findViewById(R.id.txtMapSearch);
String area=txtSearch.getText().toString();
//GooglemapsActivity.this.changeMap(area);
TravelFrom=(EditText)findViewById(R.id.travelFromEntry);
TravelFrom.setText(area);
}
});
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);
mc = mapView.getController();
String coordinates[] = {"1.352566007", "103.78921587"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.animateTo(p);
mc.setZoom(17);
mapView.invalidate();
mc.animateTo(p);
mc.setZoom(17);
//---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
}

Categories

Resources