I'm trying to create an application that uses OSMDroid and mapoverlays with geoPoints from the xml file, but i have a problem. Code editor doesn't show me an error or warning but when i run the application in emulator it shows that application has stopped working.
This the code of mapActivity:
public class MapsActivity extends Activity implements LocationListener, MapViewConstants {
private MapView mapView;
private MapController mapController;
private LocationManager mLocMgr;
static final String URL = "data/data/com.siroki.brijeg/data.xml";
// XML node keys
static final String KEY_ITEM = "object"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_LON = "lon";
static final String KEY_LAT = "lat";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.copymain);
mapView = (MapView) this.findViewById(R.id.mapview);
mapView.setTileSource(TileSourceFactory.MAPNIK);
mapView.setBuiltInZoomControls(true);
mapView.setMultiTouchControls(true);
mapController = this.mapView.getController();
mapController.setZoom(14);
GeoPoint point2 = new GeoPoint(43.3803, 17.5981);
mapController.setCenter(point2);
mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 100, this);
mapView.invalidate();
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable marker = this.getResources().getDrawable(R.drawable.ic_launcher);
ObjectsOverlay itemizedOverlay = new ObjectsOverlay(marker, null);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL);
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_LON, "Rs." + parser.getValue(e, KEY_LON));
map.put(KEY_LAT, parser.getValue(e, KEY_LAT));
// adding HashList to ArrayList
menuItems.add(map);
GeoPoint geo = new GeoPoint(Double.parseDouble(parser.getValue(e, KEY_LAT)), Double.parseDouble(parser.getValue(e, KEY_LON)));
OverlayItem overlayitem = new OverlayItem("Hellow", "World", geo);
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
}
}
public void onLocationChanged(Location location) {
double lat = 43.3803;
double lng = 17.5981 ;
GeoPoint gpt = new GeoPoint(lat, lng);
mapController.setCenter(gpt);
mapView.invalidate();
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
ObjectsOverlay.java :
public class ObjectsOverlay extends ItemizedOverlay<OverlayItem> {
public ObjectsOverlay(Drawable pDefaultMarker, ResourceProxy pResourceProxy) {
super(pDefaultMarker, pResourceProxy);
// TODO Auto-generated constructor stub
}
private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
#Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
#Override
public int size() {
return mapOverlays.size();
}
protected boolean onTap(int index) {
OverlayItem item = mapOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
this.populate();
}
#Override
public boolean onSnapToItem(int arg0, int arg1, Point arg2, IMapView arg3) {
// TODO Auto-generated method stub
return false;
}
}
And XML file data.xml:
<?xml version="1.0" encoding="UTF-8"?>
<objects>
<object>
<id>1</id>
<name>Siroki</name>
<lon>17.602985</lon>
<lat>43.374276</lat>
</object>
</objects>
I didn't wrote the imports code becouse they take alot of space. :D
First, the context defined in your ObjectsOverlay is never being set. You should add a Context parameter in the constructor:
public ObjectsOverlay(Drawable pDefaultMarker, ResourceProxy pResourceProxy, Context context) {
super(pDefaultMarker, pResourceProxy);
this.context = context;
}
so that the DialogBuilder used in onTap can have a context to create the dialog on. Without this your app will most probably crash when tapping an item.
Next, you wrongly initialized the GeoPoint, it should be done like this:
GeoPoint point = new GeoPoint(19240000,-99120000);
OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
GeoPoint coordinates are not double, like Location coordinates. They are int equal to coordinate * 1E6. Use it like this:
int lon = (int)Math.round(lon_as_double*1E6)
And the last thing, you do
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
in the same for-loop. But you should actually just addOverlay in the loop, where you add one by one object by its coordinates, and add the complete itemizedOverlay to the map after the loop.
Oh and you could also add the overlay at the beginning (before the loop), and then populate it using addOverlay. The order does not matter, it only matters to add the overlay once with mapOverlays.add.
Fix that and see if errors still happen.
Regards.
Related
I am doing a project where the title and descriptions have to be displayed. But the issue is the text in the description is little lengthy which is not shown when we click on the marker. I want to size of the snippet to show the full description else need some other option?
#SuppressLint("NewApi") public class GoogleActivity extends
FragmentActivity implements LocationListener {
private LocationManager locationManager; private static final long
MIN_TIME = 700; private static final float MIN_DISTANCE = 800;
// Google Map private GoogleMap googleMap; LatLng myPosition;
// All static variables static final String URL =
"http://webersspot.accountsupport.com/gmaptrial/onedb/phpsqlajax_genxml.php";
// XML node keys
static final String KEY_PID = "pro"; // parent node static final
String KEY_NAME = "Name"; static final String KEY_DESCRIPTION =
"Description"; static final String KEY_LAT = "Latitude"; static
final String KEY_LONG = "Longitude";
ArrayList<HashMap<String, String storeMapData = new
ArrayList<HashMap<String, String (); private ShareActionProvider
mShareActionProvider;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = mapFragment.getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); // Hybrid for
satellite with place name
googleMap.setMyLocationEnabled(true); // enable user location
button. googleMap.setInfoWindowAdapter(null) ;
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setAllGesturesEnabled(true);
googleMap.setTrafficEnabled(true); // enable road
/*
// Get Location Manager and check for GPS & Network location
services
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
// Build the alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Location Services Not Active");
builder.setMessage("Please enable Location Services and GPS");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
// Show location settings when the user acknowledges the alert dialog
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
Dialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
} */
new LongOperation().execute(""); new
MapOperation().execute(googleMap);
locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME, MIN_DISTANCE, this); //You can also use
LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER
}
public List<HashMap<String, String prepareData(){
ArrayList<HashMap<String, String menuItems = new
ArrayList<HashMap<String, String (); //List<HashMap<String,
String menuItems = new ArrayList<HashMap<String, String ();
XmlParser parser = new XmlParser(); String xml =
parser.getXmlFromUrl(URL); // getting XML Document doc =
parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_PID); // looping
through all item nodes <item for (int i = 0; i < nl.getLength();
i++) { // creating new HashMap HashMap<String, String map = new
HashMap<String, String (); Element e = (Element) nl.item(i);
System.out.println("OOOOOOOOOOOOOOOOOOO :::
"+e.getAttribute(KEY_NAME)); // adding each child node to HashMap
key = value
map.put(KEY_NAME, e.getAttribute(KEY_NAME).toString());
map.put(KEY_DESCRIPTION
,e.getAttribute(KEY_DESCRIPTION).toString()); map.put(KEY_LAT,
e.getAttribute(KEY_LAT).toString()); map.put(KEY_LONG
,e.getAttribute(KEY_LONG).toString());
// adding HashList to ArrayList menuItems.add(map);
storeMapData = menuItems;
} return menuItems;
}
public void onMapReady(final GoogleMap map) {
ArrayList<HashMap<String, String processData = storeMapData;
System.out.println( "kjkasdc "+processData);
for (int i=0; i< processData.size(); i++){
final double lat =
Double.parseDouble(processData.get(i).get(KEY_LAT));
System.out.println("MAP LAT ::::::::::::::::::::::::: "+lat);
final double lon =
Double.parseDouble(processData.get(i).get(KEY_LONG));
System.out.println("MAP LON ::::::::::::::::::::::::: "+lon);
final String address = processData.get(i).get(KEY_DESCRIPTION);
System.out.println("MAP ADDRESS :::::::::::::::::::::::::
"+address); final String name = processData.get(i).get(KEY_NAME);
System.out.println("MAP ADDRESS ::::::::::::::::::::::::: "+name);
runOnUiThread(new Runnable() {
#Override
public void run() {
final LatLng MELBOURNE = new LatLng(lat, lon);
Marker melbourne = map.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title(name)
.snippet(address)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
melbourne.showInfoWindow();
// map.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title(name).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
} });
} }
#SuppressLint("NewApi") #Override public boolean
onCreateOptionsMenu(Menu menu) {
/** Inflating the current activity's menu with res/menu/items.xml */
getMenuInflater().inflate(R.menu.share_menu, menu);
mShareActionProvider = (ShareActionProvider)
menu.findItem(R.id.menu_item_share).getActionProvider();
/** Setting a share intent */
mShareActionProvider.setShareIntent(getDefaultShareIntent());
return super.onCreateOptionsMenu(menu);
}
/** Returns a share intent */ private Intent
getDefaultShareIntent(){ Intent intent = new
Intent(Intent.ACTION_SEND); intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT,"Download");
intent.putExtra(Intent.EXTRA_TEXT,"Download Hill Top Beauty Parlour
App - Maroli from Google Play Store:
https://play.google.com/store/apps/details?id=beauty.parlour.maroli");
return intent; }
private class LongOperation extends AsyncTask<String, Void, String {
#Override protected String doInBackground(String... params) {
prepareData(); return "Executed"; } #Override protected void onPostExecute(String result) {
System.out.println("Executed"); } #Override protected void
onPreExecute() { System.out.println("Execution started");
} #Override protected void onProgressUpdate(Void... values) {
System.out.println(" -- -- -- "+values); } }
private class MapOperation extends AsyncTask<GoogleMap, Void, String
{ #Override protected String doInBackground(GoogleMap... params) {
GoogleMap map = params[0]; onMapReady(map); return
"Executed"; } #Override protected void onPostExecute(String
result) { System.out.println(result); } #Override
protected void onPreExecute() {
System.out.println("Execution started"); } #Override
protected void onProgressUpdate(Void... values) {
System.out.println(" -- -- -- "+values); } }
class MyInfoWindowAdapter implements InfoWindowAdapter{
private final View myContentsView;
MyInfoWindowAdapter(){ myContentsView =
getLayoutInflater().inflate(R.layout.custom_info_contents, null); }
#Override public View getInfoContents(Marker marker) {
TextView tvTitle =
((TextView)myContentsView.findViewById(R.id.title));
tvTitle.setText(marker.getTitle()); TextView tvSnippet =
((TextView)myContentsView.findViewById(R.id.snippet));
tvSnippet.setText(marker.getSnippet());
return myContentsView; }
#Override public View getInfoWindow(Marker marker) { // TODO
Auto-generated method stub return null;
}
}
#Override public void onLocationChanged(Location location) { //
TODO Auto-generated method stub LatLng latLng = new
LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate =
CameraUpdateFactory.newLatLngZoom(latLng, 10);
googleMap.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
#Override public void onStatusChanged(String provider, int status,
Bundle extras) { // TODO Auto-generated method stub
}
#Override public void onProviderEnabled(String provider) { // TODO
Auto-generated method stub
}
#Override public void onProviderDisabled(String provider) { //
TODO Auto-generated method stub
}
}
<?xml version="1.0" encoding="utf-8"?>
<Relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="300dp"
android:layout_gravity="center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textStyle="bold" />
<TextView
android:id="#+id/snippet"
android:marqueeRepeatLimit="5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10sp" />
</Relativelayout>
You can add custom popup instead of snippet, something like this,
private void showPopup(final Activity context, String address) {
LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.pop_up_layout, viewGroup);
TextView textView = (TextView) layout.findViewById(R.id.txt_address);
textView.setText(address);
// Creating the PopupWindow
final PopupWindow popup = new PopupWindow(context);
popup.setContentView(layout);
popup.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
popup.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
popup.setFocusable(true);
// Clear the default translucent background
popup.setBackgroundDrawable(new BitmapDrawable());
// Displaying the popup at the specified location, + offsets.
popup.showAtLocation(layout, Gravity.NO_GRAVITY, mPoint.x, mPoint.y + 50 );
}
for demonstration install and check here
I am trying to add the marker dynamically (not static). Dynamically meaning, adding markers as and when I get updates from server.
So, following is my code for ItemizedOverlay:
private class VehicleItemizedOverlay extends ItemizedOverlay<OverlayItem>{
private ArrayList<OverlayItem> mOverlayItems = new ArrayList<OverlayItem>();
public VehicleItemizedOverlay(Drawable pDefaultMarker, ResourceProxy pResourceProxy) {
super(pDefaultMarker, pResourceProxy);
}
#Override
public boolean onSnapToItem(int arg0, int arg1, Point arg2, IMapView arg3) {
return false;
}
#Override
protected OverlayItem createItem(int pos) {
return mOverlayItems.get(pos);
}
#Override
public int size() {
if(mOverlayItems!=null) return mOverlayItems.size();
else return 0;
}
public void addOverlayItem(double longitude, double latitude, Bitmap bitmap){
if(Preferences.DEBUG) Log.d("MapActivity", "Latitude: "+latitude+" Longitude: "+longitude);
MarkerDrawable drawable = new MarkerDrawable(MapActivity.this, bitmap);
OverlayItem item = new OverlayItem("a", "a", new GeoPoint((int)(latitude*1e6), (int)(longitude*1e6)));
item.setMarker(drawable);
item.setMarkerHotspot(HotspotPlace.CENTER);
mOverlayItems.add(item);
populateNow();
}
public void populateNow(){
populate();
}
}
Following is the way, I am creating ItemizedOverlay & adding it to MapView in my activity onCreate():
mResourceProxy = new DefaultResourceProxyImpl(getApplicationContext());
mVehicleOverlay = new VehicleItemizedOverlay(getResources().getDrawable(R.drawable.stub), mResourceProxy);
mMapView.getOverlays().add(mOverlay);
Now, whenever I get response from server, I am creating & adding overlayItems to ItemizedOverlay.
//onResponse is callback I received on receiving response. Vehicle is my vehicle object
public void onResponse(ArrayList<Vehicle> aVehicles) {
for(int i=0;i<mVehicles.size();i++){
final int lat = (int)(mVehicles.get(i).getLatitude()*1e6);
final int lon = (int)(mVehicles.get(i).getLongitude()*1e6);
mVehicleOverlay.addOverlayItem(lon, lat, bitmap);
}
}
But all overlay items are overlapped over each other at center point of the map. Am I missing anything?
Also, if I add some static overlay items to mVehicleOverlay before adding it then it work properly.
mVehicleOverlay = new VehicleItemizedOverlay(getResources().getDrawable(R.drawable.stub), mResourceProxy);
final int lat = (int)(STATIC_LATITUDE*1e6);
final int lat = (int)(STATIC_LONGITUDE*1e6);
mOverlay.addOverlayItem(lon, lat, bitmap);
mMapView.getOverlays().add(mVehicleOverlay);
In OSMDroid, after adding custom itemized overlay, should I not add & populate overlayItems to it like we do in case of Google API v1? Or I am missing anything here?
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"/>
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
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);