adding single marker on map, Android, Google API - android

On my application i receive coordinates from a remote server and i want to mark the location on the coordinates on a map, this happens on demand inside onClick method. The problem is that when i update the location i end up with multiple markers on the map instead of just one, the current location. is there any way to remove the previous marker before adding the next one?
I followed the steps in this tutorial : http://developer.android.com/resources/tutorials/views/hello-mapview.html
And my code goes like this :
public class AppTwoAndroid extends MapActivity {
private Button refreshButton;
double lat, lon;
ConnectionHandler conhandler;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
Log.i("AppTwo", "making connectionhandler object");
conhandler = new ConnectionHandler();
conhandler.execute();
Log.i("AppTwo", "making button");
this.refreshButton = (Button)this.findViewById(R.id.close);
final List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
final AppTwoAndroidItemizedOverlay itemizedoverlay = new AppTwoAndroidItemizedOverlay(drawable);
refreshButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i("AppTwo", "inside onclick");
if (mapOverlays.contains(itemizedoverlay) == true) {
mapOverlays.remove(itemizedoverlay);
}
conhandler.write();
lat = conhandler.retLat();
lon = conhandler.retLon();
lat = lat * 1e6;
lon = lon * 1e6;
int ilat = (int) lat;
int ilon = (int) lon;
GeoPoint point = new GeoPoint(ilat ,ilon);
OverlayItem overlayitem = new OverlayItem(point, null, "AppOne");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
Toast.makeText(getBaseContext(), "lat is: " + lat + " lon is: " + lon
, Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
and my AppTwoAndroidItemizedOverlay class is :
public class AppTwoAndroidItemizedOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Context mContext;
public AppTwoAndroidItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
#Override
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
public AppTwoAndroidItemizedOverlay(Drawable defaultMarker, Context context) {
super(defaultMarker);
mContext = context;
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
}

In the onClick method just give
mapOverlays.clear();
this should clear any existing markers.
Hope this works :)

In this part of code:
if (mapOverlays.contains(itemizedoverlay) == true) {
mapOverlays.remove(itemizedoverlay);
}
When your removing the Overlay from the mapOverlay structure you are not really clearing the overlay, so when you add other item and re-add it to the mapOverlay there will be 2 markers.
If you just want a single marker do an Overlay that has setOverlayItem instead of a list with an 'adding' logic. (meaning do a overlay with just an item that when you add another, just replaces the old one)
Hope it helped! :D

Add this statement before the code....
mMap.clear();
mMap.clear();
LatLng latLng = new LatLng(gps.getLatitude(), gps.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new
LatLng(gps.getLatitude(), gps.getLongitude()), 15));
mMap.addMarker(new MarkerOptions().position(latLng).title(""));
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

Related

how to show marker detail on marker click in android osm?

I am new to use osm in android.I have successfully show OSM in android.But i have no idea " how to click on marker and show marker detail like google map v2 infowindow popup".
How to show marker details with image onclick marker openstreetmap android, same as Google map Infowindow show on marker click.
Please give me code or idea to implement marker click event in osm android.
Thank you in advance.
This is my code which i have implemented in android java
public class MainActivity extends Activity
{
private MapView mapView;
private MapController mapController;
LocationManager locationManager;
ArrayList<OverlayItem> overlayItemArray;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView)findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setMultiTouchControls(true);
mapView.setClickable(true);
//mapView.setUseDataConnection(false);
mapController = (MapController) mapView.getController();
mapController.setZoom(17);
//--- 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);
}
//Add Scale Bar
ScaleBarOverlay myScaleBarOverlay = new ScaleBarOverlay(this);
mapView.getOverlays().add(myScaleBarOverlay);
}
#Override
protected void onResume()
{
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, myLocationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, myLocationListener);
}
#Override
protected void onPause()
{
super.onPause();
locationManager.removeUpdates(myLocationListener);
}
private void updateLoc(Location loc)
{
GeoPoint locGeoPoint = new GeoPoint(loc.getLatitude(), loc.getLongitude());
mapController.setCenter(locGeoPoint);
mapController.animateTo(locGeoPoint);
setOverlayLoc(loc);
mapView.invalidate();
}
private void setOverlayLoc(Location overlayloc)
{
GeoPoint overlocGeoPoint = new GeoPoint(overlayloc);
//---
overlayItemArray.clear();
OverlayItem newMyLocationItem = new OverlayItem("My Location", "My Location", overlocGeoPoint);
overlayItemArray.add(newMyLocationItem);
//---
}
private LocationListener myLocationListener = new LocationListener()
{
#Override
public void onLocationChanged(Location location)
{
updateLoc(location);
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
private class MyItemizedIconOverlay extends ItemizedIconOverlay<OverlayItem>
{
public MyItemizedIconOverlay(List<OverlayItem> pList,org.osmdroid.views.overlay.ItemizedIconOverlay.OnItemGestureListener<OverlayItem> pOnItemGestureListener,
ResourceProxy pResourceProxy)
{
super(pList, pOnItemGestureListener, pResourceProxy);
}
#Override
public void draw(Canvas canvas, MapView mapview, boolean arg2)
{
super.draw(canvas, mapview, arg2);
if(!overlayItemArray.isEmpty())
{
//overlayItemArray have only ONE element only, so I hard code to get(0)
GeoPoint in = overlayItemArray.get(0).getPoint();
Point out = new Point();
mapview.getProjection().toPixels(in, out);
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
canvas.drawBitmap(bm,out.x - bm.getWidth()/2,out.y - bm.getHeight()/2,null);
}
}
#Override
public boolean onSingleTapUp(MotionEvent event, MapView mapView)
{
//return super.onSingleTapUp(event, mapView);
return true;
}
#Override
public boolean onSingleTapConfirmed(MotionEvent event, MapView mapView)
{
return true;
}
}
}
activity_main.xm
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<org.osmdroid.views.MapView
android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</org.osmdroid.views.MapView>
</LinearLayout>
All these features are available when using OSMBonusPack Marker class, whose purpose is to provide a Google Maps v2-like Marker to osmdroid.
I got Solution from this link
"http://code.google.com/p/osmdroid/issues/detail?id=245#makechanges"

Linking MainActivity and Overlay class

I am currently doing a MapView with mapquest and require adding overlays to locations. Currently my MapView is working however the overlay does not appear. Any ideas as to how it can be solved? Also is it possible to create an onClick on the overlay to bring me to a ListView?? Thanks is advance!! my main activity
public class QMapsActivity extends MapActivity {
protected MapView map;
AnnotationView annot;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutId());
init();
annot = new AnnotationView(map);
}
protected void init() {
// TODO Auto-generated method stub
this.setupMapView();
}
protected void setupMapView() {
// set the zoom level, center point and enable the default zoom controls
map = (MapView) findViewById(R.id.map);
map.getController().setZoom(16);
map.getController().setCenter(new GeoPoint(1.309503,103.777793));
map.setBuiltInZoomControls(true);
}
protected int getLayoutId() {
return R.layout.main;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
And my Overlay class
public class QPoiOverlay extends QMapsActivity{
protected void init() {
super.init();
setupMapView();
}
protected void addPoiOverlay() {
// TODO Auto-generated method stub
Drawable icon = getResources().getDrawable(R.drawable.location_marker);
final DefaultItemizedOverlay poiOverlay = new DefaultItemizedOverlay(icon);
OverlayItem loc1 = new OverlayItem(new GeoPoint (1.308763,103.777321), "area","area");
poiOverlay.addItem(loc1);
OverlayItem loc2 = new OverlayItem(new GeoPoint (1.309498,103.777101), "area","area");
poiOverlay.addItem(loc2);
OverlayItem loc3 = new OverlayItem(new GeoPoint (1.311531,103.778318), "area","area");
poiOverlay.addItem(loc3);
OverlayItem loc4 = new OverlayItem(new GeoPoint (1.308071,103.77841), "area","area");
poiOverlay.addItem(loc4);
poiOverlay.setOnFocusChangeListener(new ItemizedOverlay.OnFocusChangeListener() {
#Override
public void onFocusChanged(ItemizedOverlay Overlay, OverlayItem newFocus) {
// when focused item changes, recenter map and show info
map.getController().animateTo(newFocus.getPoint());
Toast.makeText(map.getContext().getApplicationContext(), newFocus.getTitle() + ": " +
newFocus.getSnippet(), Toast.LENGTH_SHORT).show();
int lastTouchedIndex = poiOverlay.getLastFocusedIndex();
if(lastTouchedIndex>-1){
OverlayItem tapped = poiOverlay.getItem(lastTouchedIndex);
annot.showAnnotationView(tapped);
}
}
});
map.getOverlays().add(poiOverlay);
map.invalidate();
}
}

Setting a location in Map View

I'm using a map view and what I want is to mark all the ex. starbucks that near me.
but I don't have any idea how to do this.
Right now all I can do is to view my current location.
Use ItemizedOverlay to display multiple markers in android, to understand how itemized overlay works, and what it is refer following links, and tutorials:
https://developers.google.com/maps/documentation/android/reference/com/google/android/maps/ItemizedOverlay
http://android-coding.blogspot.in/2011/06/using-itemizedoverlay-to-add-marker-on.html
https://github.com/commonsguy/cw-advandroid/tree/master/Maps/ILuvNooYawk/
Try this
public class MyMap extends MapActivity{
MapView mapView;
MapController mapController;
/* positon */
double latitude = Your latitude;
double longitude = Your longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.YourLayout);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(8);
GeoPoint pointRabat = new GeoPoint(microDegres(latitude),
microDegres(longitude));
mapController.setCenter(pointRabat);
}
private int microDegres(double value) {
return (int) (value * 1000000);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
for add overlay
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
GeoPoint pointRabat = new GeoPoint(microDegres(latitude),
microDegres(longitude));
OverlayItem overlayitem = new OverlayItem(point, "My Current Location", "My Current Location");
overlay.addOverlay(overlayitem);
mapOverlays.add(overlay);
}

Overlays not displaying in android maps

So I'm just trying to create a generic mapView in android and put a few geopoints in it. I've followed the instructions from the android developer website and had no success... can anyone help? here is my code.
public class HelloItemizedOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Context mContext;
public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
// defines the bounds for the overlayItems
super(boundCenterBottom(defaultMarker));
mContext = context;
}
#Override
protected OverlayItem createItem(int i) {
// returns the correct ArrayList position from int i
return mOverlays.get(i);
}
#Override
public int size() {
// returns number of items in ArrayList
return mOverlays.size();
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
#Override
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
}
//Here's my main class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maptastic);
((TextView)((FrameLayout)((LinearLayout)((ViewGroup) getWindow().getDecorView()).getChildAt(0)).getChildAt(0)).getChildAt(0)).setGravity(Gravity.CENTER);
setTitle("Field Trip");
Drawable drawable = this.getResources().getDrawable(R.drawable.supaaaa);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable,this);
//initControls();
MapView mapview = (MapView) findViewById(R.id.mapView);
mapview.setBuiltInZoomControls(true);
mcontroller = mapview.getController();
// Plot all geo points
for (Entry<Integer, FieldTripStop> cur : Statics.fieldTripStops.entrySet())
{
// get the FieldTripStop object from the current hash table entry
Statics.currentFTStop = cur.getValue();
// concatenate numbers before (all) and after (6) the decimal, since
// geopoints only accept 6 numbers past the decimal.
theLat = Statics.currentFTStop.latitude;
theLong = Statics.currentFTStop.longitude;
/*
* String manipulation method
*
* theLat = theLat.replace(".","");
* theLat = theLat.substring(0, 8);
* theLong = theLong.replace(".","");
* theLong = theLong.substring(0, 8);
* point = new GeoPoint((int)(Integer.valueOf(theLat)), (int)(Integer.valueOf(theLong)));
*/
theDLat = Double.parseDouble(theLat);
theDLong = Double.parseDouble(theLong);
//olay = new OverlayItem(point, "herp", "derp");
//olayitems.add(olay);
List<Overlay> mapOverlays = mapview.getOverlays();
point = new GeoPoint((int)(theDLat*1E6), (int)(theDLong*1E6));
OverlayItem overlayitem = new OverlayItem(point, "holda, Mundo!", "I'm in Mexico City~!");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
You need to a) use only a single HelloItemizedOverlay (instead one for each point) and b) add this overlay to the map before you add the markers (In your current code, the overlay is not yet associated with the map when populate is called, so the map does not receive any notification and doesn't refresh itself).
Some things to check:
Did you specify your api key for the MapView? *
*) How to specify your api key (in the layout resource for your activity):
<com.google.android.maps.MapView android:id="#+id/map"
...
android:apiKey="your-api-key-here"/>

OnTap() event on map is not fired

Hello i am unable to fire ontap() event
i want to add a marker whenever i tap on map, and when i tap on another geopoint the first marker should disappear and the marker should be added on new location...
till now i have come to this point..can anybody tell me where am i going wrong!!
thanks in advance
Source Code
public class GetLocation extends MapActivity implements OnClickListener {
MapView mapView;
MapController mc;
GeoPoint p;
int range;
String category;
Button view, traffic;
private static final String Tag = "GetLocation class";
ZoomControls zoomControls;
Canvas canvas;
MapOverlay itemizedoverlay;
List<Overlay> mapOverlays;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Tag","Inside onCreate");
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.myMapView1);
LinearLayout zoom = (LinearLayout)findViewById(R.id.zoom);
mapView.setReticleDrawMode(
MapView.ReticleDrawMode.DRAW_RETICLE_UNDER);
// Drawable drawable = this.getResources().getDrawable(R.drawable.mark);
view=(Button)findViewById(R.id.BtnView);
traffic=(Button)findViewById(R.id.BtnTraffic);
Bundle extra=getIntent().getExtras();
if(extra != null)
{
category=extra.getString("category");
range=extra.getInt("range");
}
view.setOnClickListener(this);
traffic.setOnClickListener(this);
zoomControls = (ZoomControls) findViewById(R.id.zoomcontrols);
zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mc.zoomIn();
}
});
zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mc.zoomOut();
}
});
mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.mark);
itemizedoverlay = new MapOverlay(drawable,this);
mc = mapView.getController();
mapView.invalidate();
mc.setZoom(17);
mapView.invalidate();
// mapView.setSatellite(true);
mapView.setStreetView(true);
// mapView.setOnClickListener(this);
Log.d("Tag","Exit onCreate");
}
class MapOverlay extends com.google.android.maps.ItemizedOverlay<OverlayItem>
{
private ArrayList<OverlayItem> mOverlay = new ArrayList<OverlayItem>();
private Context mContext;
private boolean isPinch = false;
public MapOverlay(Drawable defaultMarker,Context context) {
super(boundCenterBottom((defaultMarker)));
mContext = context;
// TODO Auto-generated constructor stub
}
public void addOverlayItem(OverlayItem overlayItem)
{
if(!mOverlay.contains(overlayItem)){
mOverlay.add(overlayItem);
}
populate();
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return null;
}
#Override
public int size() {
// TODO Auto-generated method stub
return mOverlay.size();
}
public boolean onTap(GeoPoint p, MapView map)
{
if ( isPinch )
{
Log.i("onTap","in if!");
return false;
}
else
{
Log.i("onTap","TAP!");
if ( p!=null )
{
OverlayItem overlayitem = new OverlayItem(p," ", " ");
itemizedoverlay.addOverlayItem(overlayitem);
mapOverlays.add(itemizedoverlay);
Toast.makeText(getBaseContext(),
p.getLatitudeE6() / 1E6 + ",on Tap" +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
Log.d("Tag","Exit TAp");
return true; // We handled the tap
}
else
{
return false; // Null GeoPoint
}
}
}
}
this is my code
hope you can get some idea
Point p1=new Point(0,0);
mapView.getProjection().toPixels(mapPoint, p1);// mapPoint is GeoPoint object
inDrag=item; // item get from List object and inDrag is an OverlayItem object
items.remove(inDrag); items is list object
populate();
GeoPoint pt=mapView.getProjection().fromPixels(p1.x+xDragImageOffset,p1.y);
OverlayItem toDrop=new OverlayItem(pt, inDrag.getTitle(),inDrag.getSnippet());
items.add(toDrop);
populate();
Have a look to this article: http://mobiforge.com/developing/story/using-google-maps-android
It has a part called: "Adding Markers"
Also, here you have another more advanced example:
https://github.com/commonsguy/cw-advandroid/blob/master/Maps/NooYawkTouch/src/com/commonsware/android/maps/NooYawk.java
Hope it helps you.
the function on tap in itemizedoverlay is basically fired when the user taps on a marker
u wil hav to create a class extending overlay to detect taps .
check this overlays example

Categories

Resources