I need some way to move bus icon on a roads in mapview.
I have GeoPoint Array with all the Coordinates Longtitude and Latitude points where a bus needed to pass, Also i need to create some "Displacement Animation" along the route
I use Overlay class to setting a bus icon every 1 second
class BusOverlay extends ItemizedOverlay<OverlayItem> {
private Context context = null;
private List<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private MediaPlayer mediaPop;
public BusOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
this.context = context;
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
public void addOverlayItem(OverlayItem overlayItem) {
mOverlays.add(overlayItem);
populate();
}
public void addOverlayItem(int lat, int lon, String title) {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, title);
addOverlayItem(overlayItem);
}
public void removeOverlay(OverlayItem overlay) {
mOverlays.remove(overlay);
populate();
}
public void removeOverlayItem(int lat, int lon, String title) {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, title);
removeOverlay(overlayItem);
}
protected boolean onTap(int index) {
super.onTap(index);
return true;
}
}
In My Activity class i used with Runable methode
Drawable busLocationIcon = this.getResources().getDrawable(
R.drawable.bus_location);
final BusOverlay itemizedBusLocartionOverlay = new BusOverlay(
busLocationIcon, this);
int countBus = 0;
myRunnable = new Runnable() {
public void run() {
try {
itemizedBusLocartionOverlay.addOverlayItem((int) (Double
.parseDouble(Main.jsonArrayBus.getJSONObject(
countBus).getString("StopLat")) * 1000000),
(int) (Double.parseDouble(Main.jsonArrayBus
.getJSONObject(countBus).getString(
"StopLon")) * 1000000), "The Bus");
countBus++;
mapView.getOverlays().add(itemizedBusLocartionOverlay);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Hendler
h.postDelayed(myRunnable, 1000);
}
};
h.postDelayed(myRunnable, 1000);
But it is not working good..
please help me.
Related
i'm trying to make the google maps display a route from user current location to the overlay that user tap.
this's my overlay code
public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
public AddItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public AddItemizedOverlay(Drawable defaultMarker, Context context) {
this(defaultMarker);
this.context = context;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
if (event.getAction() == 1) {
GeoPoint geopoint = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
// latitude
double lat = geopoint.getLatitudeE6() / 1E6;
// longitude
double lon = geopoint.getLongitudeE6() / 1E6;
// Toast.makeText(context, "Lat: " + lat + ", Lon: "+lon, Toast.LENGTH_SHORT).show();
}
return false;
}
#Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
#Override
public int size() {
return mapOverlays.size();
}
#Override
protected boolean onTap(int index) {
final OverlayItem item = mapOverlays.get(0);
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.setPositiveButton("Arahkan", new OnClickListener() {
//arahkan atau direction
public void onClick(DialogInterface arg0, int arg1) {
// Getting intent data
Intent i = getIntent();
// Users current geo location
String user_latitude = i.getStringExtra("user_latitude");
String user_longitude = i.getStringExtra("user_longitude");
// Geopoint to place on map
//geoPoint = new GeoPoint((int) (Double.parseDouble(user_latitude) * 1E6),
// (int) (Double.parseDouble(user_longitude) * 1E6));
StringBuilder urlString = new StringBuilder();
String saddr = newLocation.getLatitude(user_latitude)+","+newLocation.getLongitude(user_longitude);
String daddr = (item.getPoint().getLatitudeE6()/1E6)+","+(item.getPoint().getLongitudeE6()/1E6);
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr="+saddr);
urlString.append("&daddr="+daddr);
Intent ii = new Intent(Intent.ACTION_VIEW, Uri.parse(urlString.toString()));
context.startActivity(i);
}
private Intent getIntent() {
// TODO Auto-generated method stub
return null;
}
});
dialog.show();
return true;
}
private MapView findViewById(int mapview2) {
// TODO Auto-generated method stub
return null;
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
}
public void populateNow(){
this.populate();
}
}
please give me your opinion, i'd appreciate it if there's some1 wanna fix my code problem.
thanks. :)
I've created my own custom map to show my current location and multiple points on map. it works fine,but now i would like to show a route from my current location to every point on the map.Can you give me some suggestions how i can do that? thx.
this is my customMap activity:
public class CustomMapActivity extends MapActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
String provider = "";
Criteria crit = new Criteria();
Location loc = new Location("");
LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
ItemizedOverlayedClass itemizedoverlay = new ItemizedOverlayedClass(drawable, this);
try
{
MyLocationOverlay mylocationOverlay = new MyLocationOverlay(this, mapView);
mylocationOverlay.enableMyLocation();
mapView.getOverlays().add(mylocationOverlay);
provider = mlocManager.getBestProvider(crit, false);
loc = mlocManager.getLastKnownLocation(provider);
}
catch(Exception ex)
{
//Toast.makeText(this, "Unable to retrive provider", Toast.LENGTH_LONG).show();
}
for (ServiceActivity activity : DataSources.ActivitiesList)
{
try
{
Location siteLocation = new Location("");
siteLocation.setLatitude(activity.SiteLatitude);
siteLocation.setLongitude(activity.SiteLongitude);
GeoPoint point = new GeoPoint((int)(activity.SiteLatitude * 1e6),(int)(activity.SiteLongitude * 1e6));
OverlayItem overlayitem = new OverlayItem(point, activity.SiteName+ " " + activity.SiteAddress, "Distance to this location: " + String.valueOf(loc.distanceTo(siteLocation)/1000) + " km");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
catch(Exception ex)
{
#SuppressWarnings("unused")
AlertDialogClass alert = new AlertDialogClass(this,ex.getMessage());
}
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//mylocationOverlay.enableMyLocation();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_map, menu);
return true;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
and this is the overlay class:
package com.example.srwebservice;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class ItemizedOverlayedClass extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Context mContext;
public ItemizedOverlayedClass(Drawable defaultMarker)
{
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public ItemizedOverlayedClass(Drawable defaultMarker, Context context)
{
super(boundCenterBottom(defaultMarker));
mContext = context;
}
#Override
protected OverlayItem createItem(int i)
{
// TODO Auto-generated method stub
return mOverlays.get(i);
}
#Override
public int size()
{
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;
}
}
This link have tutorial to draw route path on map in our app. this may help you and
use below to link with map app... this will take to you in google map application
String uri = "http://maps.google.com/maps?f=d&hl=en&saddr="+source_latitude+","+source_longitude+"&daddr="+destination_latitude+","+destination_longitude;
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
OR
refter this link how to display the driving routes
i found a simpler solution.I can use google maps intent directly, and i don't need to create a custom map activity anymore:
if(DataSources.ActivitiesList.length >0)
{
String address = "http://maps.google.com/maps?daddr=" + DataSources.ActivitiesList[0].SiteLatitude.toString() + "," + DataSources.ActivitiesList[0].SiteLongitude.toString();
for (int i= 1 ;i < DataSources.ActivitiesList.length ; i++)
{
if(DataSources.ActivitiesList[i].SiteLatitude != null)
address += "+to:" + DataSources.ActivitiesList[i].SiteLatitude + "," + DataSources.ActivitiesList[i].SiteLongitude;
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(address));
startActivity(intent);
break;
}
I have to make a multiple marker google map using JSON parsing. Any one having helping code of it. So that i can gain an idea on it. The activity i have made is not working exactly what i want.
This is my activity
public class MapsActivity extends MapActivity{
private MapController mapControll;
private GeoPoint geoPoint=null;
private MapView mapview;
private MyItemizedOverlay userPicOverlay;
private MyItemizedOverlay nearPicOverlay;
private Drawable userPic,atmPic;
private OverlayItem nearatms[] = new OverlayItem[50];
public static Context context;
public double latitude;
public double longitude;
private List<String> lat = new ArrayList<String>();
private List<String> lon = new ArrayList<String>();
private String[] get_lati;
private String[] get_long;
#Override
protected void onCreate(Bundle icicle) {
// TODO Auto-generated method stub
super.onCreate(icicle);
context = getApplicationContext();
setContentView(R.layout.map);
lat.clear();
lon.clear();
Intent in = getIntent();
if(in!=null){
get_lati = in.getStringArrayExtra("LAT_KEY");
get_long = in.getStringArrayExtra("LONG_KEY");
System.out.println("lat===="+get_lati.length+" lon==="+get_long.length);
}
for(int i = 0;i<get_lati.length;i++){
String lt = null;
String ln = null;
lt =get_lati[i];
ln =get_long[i];
System.out.println("lt=="+lt+"==ln=="+ln);
}
showMap();
}
public void showMap() {
// TODO Auto-generated method stub
try {
double lat_dbl = Double.parseDouble(get_lati[0]);
double lon_dbl = Double.parseDouble(get_long[0]);
geoPoint = new GeoPoint((int)(lat_dbl * 1E6),(int)(lon_dbl * 1E6));
mapview = (MapView)findViewById(R.id.mapView);
mapControll= mapview.getController();
mapview.setBuiltInZoomControls(true);
mapview.setStreetView(true);
mapControll.setZoom(16);
mapControll.animateTo(geoPoint);
userPic = this.getResources().getDrawable(R.drawable.pin);
userPicOverlay = new MyItemizedOverlay(userPic);
OverlayItem overlayItem = new OverlayItem(geoPoint, "I'm Here!!!", null);
userPicOverlay.addOverlay(overlayItem);
mapview.getOverlays().add(userPicOverlay);
atmPic = this.getResources().getDrawable(R.drawable.pin);
nearPicOverlay = new MyItemizedOverlay(atmPic);
for (int i = 0; i < 5; i++) {
nearatms[i] = new OverlayItem(new GeoPoint((int)((latitude) * 1E6), i),"Name", null);//just check the brackets i just made change here so....
nearPicOverlay.addOverlay(nearatms[i]);
}
mapview.getOverlays().add(nearPicOverlay);
//Added symbols will be displayed when map is redrawn so force redraw now
mapview.postInvalidate();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> myOverlays ;
public MyItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
myOverlays = new ArrayList<OverlayItem>();
populate();
}
public void addOverlay(OverlayItem overlay){
myOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return myOverlays.get(i);
}
// Removes overlay item i
public void removeItem(int i){
myOverlays.remove(i);
populate();
}
// Returns present number of items in list
#Override
public int size() {
return myOverlays.size();
}
public void addOverlayItem(OverlayItem overlayItem) {
myOverlays.add(overlayItem);
populate();
}
public void addOverlayItem(int lat, int lon, String title) {
try {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected boolean onTap(int index) {
// TODO Auto-generated method stub
String title = myOverlays.get(index).getTitle();
//Toast.makeText(MapActivity.this, title, Toast.LENGTH_LONG).show();
return super.onTap(index);
}
}
}
You are creating a geopoint with latitude but 'i' instead of longitude.
new GeoPoint((int)((latitude) * 1E6), i)
instead of:
new GeoPoint((int)((latitude) * 1E6), (int)((longitude) * 1E6)) // + some variation based on i
Thus all the points fall very near to each other.
I assume that you're using 'i' in order to create separate point near your location, and that in the final product you would use an ATM point DB. I suggest that you create a function that is supposed to retrieve ATM locations, and for testing purposes either return fixed (but real) locations, or randomize around your lat/lng. (This is also a better coding practice.)
For debug purposes, log the actual points you are creating, after you created them. if all lat/lng numbers look the same, you have a clue at what's going on. if only two points are logged... that's a different problem. :-)
So I put my connectivity tests in and stop my JSON call for map pins. However, even with this done if the user taps on the map the app crashes.
It seems to be calling a method in the Google API's maps.jar for touch events but I do not have access to these right?
so how do test for it or is there a better way to check for this?
public class Map_Activity extends MapActivity implements LocationListener {
/** Called when the activity is first created. */
MapView map;
private MyLocationOverlay me = null;
Drawable d;
List<Overlay> overlayList;
LocationManager lm;
String towers;
int lat;
int longi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_activity);
map = (MapView) findViewById(R.id.mapview);
Touchy t = new Touchy();
overlayList = map.getOverlays();
overlayList.add(t);
// //////////////////////////////////// Where the maps opens up to and
// zoom
map.getController().setCenter(getPoint(40.801531, -81.405661));
map.getController().setZoom(15);
Drawable marker = getResources().getDrawable(R.drawable.pin_yellow);
marker.setBounds(0, 0, marker.getIntrinsicWidth(),
marker.getIntrinsicHeight());
map.getOverlays().add(new SitesOverlay(marker));
me = new MyLocationOverlay(this, map);
map.getOverlays().add(me);
// d = getResources().getDrawable(R.drawable.pin_blue);
// Geo Location of phone
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Location location = lm.getLastKnownLocation(towers);
if (location != null) {
lat = (int) (location.getLatitude() * 1E6);
longi = (int) (location.getLongitude() * 1E6);
// GeoPoint ourLocation = new GeoPoint(lat, longi);
// OverlayItem overlayItem = new OverlayItem(ourLocation,
// "Quit hitting your self", "");
// CustomPinpoint custom = new CustomPinpoint(d, Map_Activity.this);
// custom.insertPinpoint(overlayItem);
// overlayList.add(custom);
} else {
// Toast.makeText(MapsActivity.this, "Couldn't get provider",
// Toast.LENGTH_SHORT).show();
}
initLocation();
}
private void initLocation() {
lm = (LocationManager) this.getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 500, this);
}
#Override
public void onResume() {
super.onResume();
me.enableCompass();
lm.requestLocationUpdates(towers, 500, 1, this);
}
#Override
public void onPause() {
super.onPause();
me.disableCompass();
lm.removeUpdates(this);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class Touchy extends Overlay {
public boolean onTouchEvent(MotionEvent e, MapView m) {
return false;
}
}
private GeoPoint getPoint(double lat, double lon) {
return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
}
private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items = new ArrayList<OverlayItem>();
public SitesOverlay(Drawable marker) {
super(marker);
if (isNetworkAvailable() == true) {
boundCenterBottom(marker);
// //////////////////////////////////////////////////////////////////////
String result = queryRESTurl("http://www.mywesite.com/json.json");
Log.e("Spot 1", "");
JSONObject json;
JSONObject json2;
// JSONObject data;
try {
json = new JSONObject(result);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
for (int i = 0; i < valArray.length(); i++) {
Log.e(nameArray.getString(i), valArray.getString(i));
json2 = new JSONObject(valArray.getString(i));
JSONArray nameArray2 = json2.names();
JSONArray valArray2 = json2.toJSONArray(nameArray2);
for (int a = 0; a < valArray2.length(); a++) {
// add to maps here
items.add(new OverlayItem(getPoint(
valArray2.getDouble(3),
valArray2.getDouble(2)), valArray2
.getString(1), valArray2.getString(0)));
Log.e(nameArray2.getString(a),
valArray2.getString(a));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Pin Locations
populate();
} else {
AlertDialog.Builder ad = new AlertDialog.Builder(
Map_Activity.this);
ad.setIcon(android.R.drawable.ic_dialog_alert);
ad.setTitle("OH NO!");
ad.setMessage("To view the latest information you need a data or wi-fi connection");
ad.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
ad.show();
}
}
#Override
protected OverlayItem createItem(int i) {
return (items.get(i));
}
#Override
protected boolean onTap(int i) {
// Toast.makeText(MapsActivity.this,
// items.get(i).getSnippet(),Toast.LENGTH_SHORT).show();
OverlayItem item = items.get(i);
AlertDialog.Builder dialog = new AlertDialog.Builder(
Map_Activity.this);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return (true);
}
#Override
public int size() {
return (items.size());
}
}
public void onLocationChanged(Location l) {
// TODO Auto-generated method stub
List<Overlay> overlays = map.getOverlays();
me = new MyLocationOverlay(this, map);
overlays.add(me);
me.enableMyLocation();
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public String queryRESTurl(String url) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
instream.close();
return result;
}
} catch (ClientProtocolException e) {
Log.e("REST", "There was a protocol based error", e);
} catch (IOException e) {
Log.e("REST", "There was an IO Stream related error", e);
}
return null;
}
/*
* Check for Connectivity
*/
public boolean isNetworkAvailable() {
Context context = getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
I'm using locationManager and ItemizedOverlay to draw My Location marker, the problem is when onLocationChanged is triggered I'm getting new marker drawed and not the last one moved to the new location, here is my onLocationChanged code :
public void onLocationChanged(Location location) {
myOverlay object1 = new myOverlay(getResources().getDrawable(R.drawable.arrow),MyMap);
if(location!=null){
MyMap.invalidate();
GeoPoint MyPos = new GeoPoint(microdegrees(location.getLatitude()),microdegrees(location.getLongitude()));
MyController.animateTo(MyPos);
object1.addPoint(MyPos,"Ma position","Ma position");
MyMap.getOverlays().add(object1);
}
}
Can you please help me solve this issue ?
Thanks a lot.
MapActivity :
public class Main extends MapActivity implements LocationListener {
/** Called when the activity is first created. */
MapView MyMap;
MapController MyController;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyMap=(MapView)findViewById(R.id.MyGMap);
MyMap.setBuiltInZoomControls(true);
try {
getEventsFromAnXML(this);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int j=0;
myOverlay object = new myOverlay(getResources().getDrawable(R.drawable.marker),MyMap);
while( j<agencies.size()){
GeoPoint point = new GeoPoint(microdegrees(agencies.get(j).getLatitude()),microdegrees(agencies.get(j).getLongitude()));
String Tit;
String Des;
Tit=agencies.get(j).getTspTitle();
Des=agencies.get(j).getTspTitle() + "\nAgence: " + agencies.get(j).getTitle() +
"\nTél: " + agencies.get(j).getPhone();
object.addPoint(point,Tit,Des);
j=j+1;
}
MyMap.getOverlays().add(object);
MyController=MyMap.getController();
MyController.setZoom(12);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);
}
private int microdegrees(double value){
return (int)(value*1000000);
}
boolean na=false;
List<Agency> agencies = new ArrayList<Agency>();
Agency agency=new Agency();
int i=0;
String TempTspTitle;
String TempTspPhone;
Boolean TempTspEnabled;
private String getEventsFromAnXML(Activity activity)
throws XmlPullParserException, IOException
{
StringBuffer stringBuffer = new StringBuffer();
Resources res = activity.getResources();
XmlResourceParser xpp = res.getXml(R.xml.hotels);
xpp.next();
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
if(eventType == XmlPullParser.START_DOCUMENT)
{
stringBuffer.append("--- Start XML ---");
}
else if(eventType == XmlPullParser.START_TAG)
{
if (xpp.getName().equals("DataBase")){
String name=xpp.getAttributeValue(null, "name");
agency.setTspTitle(name);
TempTspTitle=name;
na=true;
}
if (xpp.getName().equals("DataBaseEnabled")){
xpp.next();
agency.setTspEnabled(Boolean.parseBoolean(xpp.getText()));
TempTspEnabled=Boolean.parseBoolean(xpp.getText());
xpp.nextTag();
}
if (xpp.getName().equals("Title")){
xpp.next();
agency.setTitle(xpp.getText());
na=false;
xpp.nextTag();
}
if (xpp.getName().equals("Address")){
xpp.next();
agency.setAddress(xpp.getText());
xpp.nextTag();
}
if (xpp.getName().equals("Phone") && na==true){
xpp.next();
agency.setTspPhone(xpp.getText());
TempTspPhone=xpp.getText();
xpp.nextTag();
}else{
if (xpp.getName().equals("Phone") && na==false){
xpp.next();
agency.setPhone(xpp.getText());
xpp.nextTag();
}
}
if (xpp.getName().equals("Fax")){
xpp.next();
agency.setFax(xpp.getText());
xpp.nextTag();
}
if (xpp.getName().equals("e-Mail")){
xpp.next();
agency.setMail(xpp.getText());
xpp.nextTag();
}
if (xpp.getName().equals("Latitude")){
xpp.next();
agency.setLatitude(Double.parseDouble(xpp.getText()));
xpp.nextTag();
}
if (xpp.getName().equals("Longitude")){
xpp.next();
agency.setLongitude(Double.parseDouble(xpp.getText()));
}
}
else if(eventType == XmlPullParser.END_TAG)
{
if (xpp.getName().equals("DataBase") ){
agency = new Agency();
}else if (xpp.getName().equals("Agency")){
agencies.add(i,agency);
i=i+1;
agency = new Agency();
agency.setTspTitle(TempTspTitle);
agency.setTspPhone(TempTspPhone);
agency.setTspEnabled(TempTspEnabled);
}
}
eventType = xpp.next();
}
stringBuffer.append("\n" + "Size: " + agencies.size());
return stringBuffer.toString();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public void onLocationChanged(Location location) {
myOverlay object1 = new myOverlay(getResources().getDrawable(R.drawable.arrow),MyMap);
if(location!=null){
MyMap.getOverlays().remove(object1);
MyMap.invalidate();
GeoPoint MyPos = new GeoPoint(microdegrees(location.getLatitude()),microdegrees(location.getLongitude()));
MyController.animateTo(MyPos);
object1.addPoint(MyPos,"Ma position","Ma position");
MyMap.getOverlays().add(object1);
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
and myOverlay Class :
public class myOverlay extends ItemizedOverlay<OverlayItem>{
List<OverlayItem> points= new ArrayList<OverlayItem>();
private Drawable marker=null;
private Context c;
public myOverlay(Drawable marker, MapView mapView) {
super(marker);
this.marker=marker;
c=mapView.getContext();
}
#Override
protected OverlayItem createItem(int i) {
return (points.get(i));
}
public void draw(Canvas canvas,MapView mapView, boolean shadow){
super.draw(canvas, mapView, shadow);
boundCenterBottom(marker);
}
#Override
public int size() {
return points.size();
}
public void addPoint(GeoPoint point, String Titre, String Desc){
this.points.add(new OverlayItem(point,Titre,Desc));
populate();
}
public void removePoint(){
this.points.clear();
populate();
}
#Override
protected boolean onTap(int i){
Toast.makeText(c, points.get(i).getSnippet(), Toast.LENGTH_SHORT).show();
return (true);
}
}
}
according to Dave's suggestion this fixed the problem :
public void onLocationChanged(Location location) {
if(mMyOverlay == null) {
mMyOverlay = new myOverlay(getResources().getDrawable(R.drawable.arrow),MyMap);
MyMap.getOverlays().add(mMyOverlay);
}else{
MyMap.getOverlays().remove(mMyOverlay);
MyMap.invalidate();
mMyOverlay = new myOverlay(getResources().getDrawable(R.drawable.arrow),MyMap);
MyMap.getOverlays().add(mMyOverlay);
}
if(location!=null){
MyMap.invalidate();
GeoPoint MyPos = new GeoPoint(microdegrees(location.getLatitude()),microdegrees(location.getLongitude()));
MyController.animateTo(MyPos);
mMyOverlay.addPoint(MyPos,"Ma position","Ma position");
}
thanks..
getOverlays() returns the List of Overlay objects in your MapView. Each time the location is updated, your code is adding another overlay to this list. You need to do is remove the previous overlay, or empty the list entirely each time.
So, in your method call getOverlays().clear() before adding your new overlay.
Edit, alternatively maybe this will point you in the right direction? I don't know exactly how your myOverlay class works, so hopefully you can fill in the blanks!
protected myOverlay mMyOverlay;
public void onLocationChanged(Location location) {
if(mMyOverlay == null) {
mMyOverlay = new myOverlay(getResources().getDrawable(R.drawable.arrow),MyMap);
MyMap.getOverlays().add(mMyOverlay);
if(location!=null){
MyMap.invalidate();
GeoPoint MyPos = new GeoPoint(microdegrees(location.getLatitude()),microdegrees(location.getLongitude()));
MyController.animateTo(MyPos);
mMyOverlays.setPoint(MyPos,"Ma position","Ma position");
}
}
Use an ItemizedOverlay, and as Dave suggested, keep track of the one you want moved and then either delete the tracked OverlayItem and add a new one or take the tracked one, get its marker or MapPoint and reset its lat/lon coordinates to the new location coordinates. You may also have to call mapView.invalidate() to force a redraw.