Linking MainActivity and Overlay class - android

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

Related

Android MapView Overlay Image not displaying

I'm trying to write a simple MapView using Google Maps API v1 (Targeting Gingerbread devices)
Just tried following the example hello-mapview and it all works apart from the image does not get displayed on the map.
There is an overlay, as the touch even works and displays the text, how ever no image appears with it.
Can anyone spot what I have missed?
MyMapView.java
public class MyMapView extends MapActivity {
private MapView mapView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = getResources().getDrawable(R.drawable.androidmarker);
NewOverlay itemizedoverlay = new NewOverlay(drawable, this);
GeoPoint point = new GeoPoint(19240000,-99120000);
OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
NewOverlay.java
public class NewOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public NewOverlay(Drawable defaultMarker, Context context) {
super(defaultMarker);
mContext = context;
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
public void removeOverlays(){
mOverlays.clear();
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;
}
}

Issue while using 2 map fragments in One application

I am trying to use two different Map Fragment in two different Fragment Activities. And as per the SupportMapFragment design, I am keeping the map key in the META TAG of the appilcation properties in Manifest file.
However my Map view is not clearing, it is showing same map with old points in the second Fragment eventhough I am calling "getMap().clear()". Please suggest
This is working fine untill and unless I dont use new MapFragment in a separate Activity, If I use new Mapfragment, it is taking the same map view, so the map view is not clearing.
Code :
MAP FRAGMENT
public class DisplayMapFragment extends SupportMapFragment implements
OnMarkerClickListener,OnInfoWindowClickListener {
View mMapViewContainer;
MapView mMapView;
private Utill utilClass = Utill.getInstance(false);
private View v;
private MapView mapView;
private GeoPoint p;
private MapController mc;
private String latstr = "";
private String lonstr = "";
private String name, address;
private double lat;
private double lng;
ArrayList<NearByItem> NearByList=new ArrayList<NearByItem>();
private LatLng mPosFija;
private ArrayList<Double> mlat, mlong;
private ViewGroup parent;
Utill utilclass=Utill.getInstance(false);
Bitmap bmp;
ImageView ivIcon;
StringBuilder sbc=new StringBuilder();
ProgressBar progressbar;
public ImageLoader imageLoader;
public DisplayMapFragment() {
super();
}
public static DisplayMapFragment newInstance(LatLng posicion) {
DisplayMapFragment frag = new DisplayMapFragment();
frag.mPosFija = posicion;
return frag;
}
#Override
public void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
NearByList=NearByMapActivity.fltrdNearByLists;
imageLoader=new ImageLoader(this.getActivity().getApplicationContext());
}
#Override
public View onCreateView(LayoutInflater arg0, ViewGroup arg1, Bundle arg2) {
View v = super.onCreateView(arg0, arg1, arg2);
mlat = new ArrayList<Double>();
mlong = new ArrayList<Double>();
parent=arg1;
if(NearByMapActivity.fltrdNearByLists!=null && !NearByMapActivity.fltrdNearByLists.isEmpty())
NearByList.addAll(NearByMapActivity.fltrdNearByLists);
else
NearByList.addAll(Utill.NearbyList);
NearByMapActivity parentActivity = (NearByMapActivity) getActivity();
return v;
}
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items;
private Drawable marker;
public MyItemizedOverlay(Drawable defaultMarker) {
super(defaultMarker);
items = new ArrayList<OverlayItem>();
marker = defaultMarker;
}
#Override
protected OverlayItem createItem(int index) {
return items.get(index);
}
#Override
public int size() {
return items.size();
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, shadow);
boundCenterBottom(marker);
}
public void addItem(OverlayItem item) {
items.add(item);
}
public void populateNow() {
populate();
}
#Override
protected boolean onTap(int index) {
return true;
}
}
private void initMap() {
UiSettings settings = getMap().getUiSettings();
settings.setAllGesturesEnabled(true);
// settings.setMyLocationButtonEnabled(true);
settings.isZoomControlsEnabled();
getMap().setTrafficEnabled(true);
getMap().getMaxZoomLevel();
// getMap().setMyLocationEnabled(true);
if(NearByMapActivity.fltrdNearByLists!=null && !NearByMapActivity.fltrdNearByLists.isEmpty())
getMap().moveCamera(
CameraUpdateFactory.newLatLngZoom(
new LatLng(Double.parseDouble(NearByMapActivity.fltrdNearByLists.get(0).getLocationLat()),
Double.parseDouble(NearByMapActivity.fltrdNearByLists.get(0).getLocationLong())), 14));
getMap().isTrafficEnabled();
// getMap().addGroundOverlay(new GroundOverlayOptions().)
getMap().setOnMarkerClickListener(this);
getMap().setOnInfoWindowClickListener(this);
marker=new MarkerOptions()
.position(
new LatLng(
Double.parseDouble(item.getLocationLat()),
Double.parseDouble(item.getLocationLong())))
.title(""+item.getStoreTitle())
.icon(bitmapLoyalty
).snippet(sbc.toString());
else
marker=new MarkerOptions()
.position(
new LatLng(
Double.parseDouble(item.getLocationLat()),
Double.parseDouble(item.getLocationLong())))
.title(""+item.getStoreTitle())
.icon(bitmapIconNearBy
).snippet(sbc.toString());
Marker marker1=getMap().addMarker(marker);
PopupWindowAdapter view1=new PopupWindowAdapter();
this.getMap().setInfoWindowAdapter(view1);
// .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.orgr_icon);
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
initMap();
getMap().addMarker(new MarkerOptions().position(new
LatLng(36.865814,-119.758399)).icon(BitmapDescriptorFactory.fromResource(R.drawable.red_pin)));
//getMap().addGroundOverlay(new GroundOverlay(null));
/* getMap().addGroundOverlay(new GroundOverlayOptions()
.image(image)
.positionFromBounds(bounds)
.transparency(0.5));
*/ }
#Override
public void onPause() {
super.onPause();
//getMap().clear();
}
public void onResume(){
super.onResume();
if(NearByMapActivity.mainMapView!=null)
//if(NearByMapActivity.mainMapView.getVisibility()==View.GONE)
NearByMapActivity.mainMapView.setVisibility(View.VISIBLE);
}
#Override
public boolean onMarkerClick(Marker arg0) {
// TODO Auto-generated method stub
Log.e("cleared", "");
return false;
}
}
public void onStop(){
super.onStop();
//getMap().clear();
}
}
MAP ACTIVITY : Activity class to start Fragment.
public class NearByMapActivity extends FragmentActivity{
onCreate(){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Fragment frag=new DisplayMapFragment();
transaction.add(R.id.middle_view, frag);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
transaction.addToBackStack(null);
transaction.commit();
}
}
You are probably affected by this bug:
https://code.google.com/p/gmaps-api-issues/issues/detail?id=5027&thanks=5027&ts=1362071369
Thank u so much!!!!!!!!!!!!!
I try this, and its work like a charm :)
public void hideStupidMaps() {
mMapView.getLayoutParams().height = 1;
mMapView.getLayoutParams().width = 1;
mMapView.invalidate();
mMapView.requestLayout();
}

Android : Back button is acting odd

I have a strange problem and really dont know where to start debug. I have 2 activities one that holds a googlemap view and when the user taps the marker on the view i start a new activity that shows a detailed description of that marker. If i hit the back buttton on my detalied activity it returns me to the map activity, so far so good. BUT if i tap a new (or same) marker i get to the detailed activity again (all fine) if i try to hit the back button again i get returned to the detailed activity that i tapped the very first time, and i can hit back once more and finaly get to the map activity again.
if i keep debugggin i can get up to 10 activities that i have to push back on before i finaly get to the map activity again
what the heck is going on ? does android forget history or something due to i implement the map activity instead of activity ?
anyone that has an idea of where to start looking for the problem
Here comes a lot of code:
map activity
public class SpotGuideMapActivity extends MapActivity
{
protected MapView mapView;
protected MapController mapController;
protected List<Overlay> mapOverlays;
protected Drawable overlayIcon;
protected SpotGuideOverlay spotsOverlay;
protected MyLocationOverlay myLocOverlay;
protected ArrayList<SpotItem> _spots;
protected Button ButtonHome;
protected Button ButtonPreferences;
protected Intent _intent = null;
private SpotGuideDbAdapter _spotDbAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.spot_map);
_intent = getIntent();
ActivityHelper.createInstance(this).setTopBarTitle("Spot kortet");
ButtonPreferences = (Button)findViewById(R.id.btnPreferences);
ButtonPreferences.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivity(new Intent(getApplicationContext(), GlobalPreferencesActivity.class));
overridePendingTransition(R.anim.slide_right_in,R.anim.slide_right_out);
}
});
ButtonHome = (Button)findViewById(R.id.btnHome);
ButtonHome.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivity(new Intent(getApplicationContext(), HomeActivity.class));
overridePendingTransition(R.anim.slide_left_in,R.anim.slide_left_out);
}
});
//mapView.invalidate();
}
#Override
protected void onResume()
{
super.onResume();
if(_intent.hasExtra("latitude") && _intent.hasExtra("longitude"))
{
String latitude = _intent.getStringExtra("latitude");
String longitude = _intent.getStringExtra("longitude");
double lat = Double.parseDouble(latitude);
double lon = Double.parseDouble(longitude);
GeoPoint point = new GeoPoint((int)(lat * 1E6) , (int)(lon * 1E6));
initMapView(point);
}
else
{
initMapView(null);
}
drawSpotMarkers();
}
#Override
protected void onPause()
{
super.onPause();
myLocOverlay.disableCompass();
myLocOverlay.disableMyLocation();
}
protected void initMapView(GeoPoint centerPoint)
{
mapView = (MapView)findViewById(R.id.spotGuideMap);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
//current location overlayer
myLocOverlay = new MyLocationOverlay(this, mapView);
myLocOverlay.enableCompass();
myLocOverlay.enableMyLocation();
mapView.getOverlays().add(myLocOverlay);
GeoPoint point = null;
if(centerPoint == null)
{
point = myLocOverlay.getMyLocation();
if(point == null)
{
point = new GeoPoint((int)(55.5616508394963 * 1E6) , (int)(12.563638687133789 * 1E6));
}
}
else
{
point = centerPoint;
}
//get the last know location, be fresh so use last fix
//Location location = myLocOverlay.getLastFix();
//GeoPoint locationPoint;
//locationPoint = new GeoPoint((int)(location.getLatitude() * 1E6) , (int)(location.getLongitude() * 1E6));
mapController.animateTo(point);
mapController.setZoom(10);
}
protected void drawSpotMarkers()
{
mapOverlays = mapView.getOverlays();
overlayIcon = getResources().getDrawable(R.drawable.map_icon_pink);
spotsOverlay = new SpotGuideOverlay(overlayIcon, this);
_spotDbAdapter = new SpotGuideDbAdapter(this).Open();
_spots = _spotDbAdapter.getAllSpots();
for (SpotItem spot : _spots)
{
double lat = Double.parseDouble(spot.getLatitude());
double lon = Double.parseDouble(spot.getLongitude());
GeoPoint point = new GeoPoint((int)(lat * 1E6) , (int)(lon * 1E6));
OverlayItem overlayitem = new OverlayItem(point, spot.getSpotTitle(), Integer.toString(spot.getId()));
spotsOverlay.addOverlay(overlayitem);
}
mapOverlays.add(spotsOverlay);
}
#Override
protected boolean isRouteDisplayed()
{
return false;
}
}
detailed activity
public class SpotGuideDescriptionActivity extends BaseActivity
{
private SpotGuideDbAdapter _spotDbAdapter;
protected Button ButtonHome;
protected Button ButtonPreferences;
protected Button ButtonBacktoMap;
protected TextView tvSpotTitle;
protected TextView tvSpotType;
protected TextView tvWindDirection;
protected TextView tvContent;
protected Intent _intent = null;
protected SpotItem item;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.spot_description);
_intent = getIntent();
this.getActivityHelper().setTopBarTitle("Spot beskrivelse");
tvSpotTitle = (TextView)findViewById(R.id.spotDescTitle);
tvSpotType = (TextView)findViewById(R.id.spotDescType);
tvWindDirection = (TextView)findViewById(R.id.spotDescWind);
tvContent = (TextView)findViewById(R.id.spotDescContent);
ButtonBacktoMap = (Button)findViewById(R.id.btnBackToMap);
ButtonBacktoMap.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(getApplicationContext(), SpotGuideMapActivity.class);
intent.putExtra("latitude", item.getLatitude());
intent.putExtra("longitude", item.getLongitude());
startActivity(intent);
overridePendingTransition(R.anim.slide_left_in,R.anim.slide_left_out);
}
});
ButtonPreferences = (Button)findViewById(R.id.btnPreferences);
ButtonPreferences.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivity(new Intent(getApplicationContext(), GlobalPreferencesActivity.class));
overridePendingTransition(R.anim.slide_right_in,R.anim.slide_right_out);
}
});
ButtonHome = (Button)findViewById(R.id.btnHome);
ButtonHome.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivity(new Intent(getApplicationContext(), HomeActivity.class));
overridePendingTransition(R.anim.slide_left_in,R.anim.slide_left_out);
}
});
init();
}
private void init()
{
if(_intent.hasExtra("spot_id"))
{
int id = _intent.getIntExtra("spot_id", 0);
_spotDbAdapter = new SpotGuideDbAdapter(this).Open();
item = _spotDbAdapter.getSpot(id);
tvSpotTitle.setText(item.getSpotTitle());
tvSpotType.setText(item.getSpotType());
tvWindDirection.setText(item.getWindDirections());
tvContent.setText(item.getSpotDescription());
}
}
}
And i init the tap in my OverlayItem like this
public boolean onTap(int index)
{
OverlayItem item = mOverlays.get(index);
Intent descIntent = new Intent(currentContext.getApplicationContext(), SpotGuideDescriptionActivity.class);
descIntent.putExtra("spot_id", item.getSnippet());
currentContext.startActivity(descIntent);
return false;
}
it is not the BackToMap button that i use, it is the back button on all phones
I haven't worked with maps, so I may be off my rocker. But the fact that you are calling initMapView() in OnResume() might be creating two markers one on top of the other (and again, every time you go back). So when you think you are taping on one marker, you are actually taping on multiple markers.
That's just off the top of my head, and can be total malarkey.
A quick solution would be to #Override onBackPressed() to open the map activity back up. This might lead to you having to do it to navigate the entire app, though. If it's just that map page and the overlay with more info, you can easily just have this on the page that is duplicating:
#Override
onBackPressed(){
Intent i = new Intent(this, Activity.class);
startActivity(i);
}
then on the activity with the mapview
#Override
onBackPressed(){
moveTaskToBack(true);
}

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

adding single marker on map, Android, Google API

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

Categories

Resources