I have a class :
class MapItemizedOverlay extends com.google.android.maps.ItemizedOverlay<OverlayItem> {
private Context context;
private ArrayList items = new ArrayList();
public MapItemizedOverlay(Context aContext, Drawable marker) {
super(boundCenterBottom(marker));
context = aContext;
}
public void addOverlayItem(OverlayItem item) {
items.add(item);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return (OverlayItem) items.get(i);
}
#Override
public int size() {
return items.size();
}
#Override
protected boolean onTap(int index) {
OverlayItem item = (OverlayItem) items.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
#Override
public boolean onTap (final GeoPoint p, final MapView mapView) {
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(p.getLatitudeE6() / 1E6,
p.getLongitudeE6() / 1E6, 1);
String address = "";
if (addresses.size() > 0) {
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++)
address += addresses.get(0).getAddressLine(i) + "\n";
}
address.cancel();
address.setText(address);
address.show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
I add some overlays on the map with the function:
private void initialiseOverlays() {
// Create an ItemizedOverlay to display a list of markers
Drawable defaultMarker = getResources().getDrawable(R.drawable.marker);
MapItemizedOverlay mapItemizedOverlay = new MapItemizedOverlay(this, defaultMarker);
mapItemizedOverlay.addOverlayItem(new OverlayItem(new GeoPoint((int) (12.345678 * 1E6), (int) (23.456789 * 1E6)), "Point 1", "some-random-text"));
mapItemizedOverlay.addOverlayItem(new OverlayItem(new GeoPoint((int) (89.012345 * 1E6), (int) (67.890123 * 1E6)), "Point number 2", "more-random-text"));
// Add the overlays to the map
mapView.getOverlays().add(mapItemizedOverlay);
}
If only one of the onTap functions is defined everything works fine - I can either get the address if I click somewhere over the map or I can get a dialog with the place's title and content if I click on the icon over the place.
But I want to have both of the functions working together, the application to detect if the click was over an empty place on the map or over a marker(the drawable set) and show it's information. How can I achieve this?
Found the answer - had to include the:
if(super.onTap(p, mapView)) {
return true;
}
in the beginning of the public boolean onTap (final GeoPoint p, final MapView mapView) function.
you can use onTouch method
#Override
public boolean onTouchEvent(MotionEvent event, final MapView mapView) {
final int action=event.getAction();
final int x=(int)event.getX();
final int y=(int)event.getY();
result = false;
if (action==MotionEvent.ACTION_DOWN) {
downPressed = true;
drag = false;
/* here check for the items is null or not and then after get all the items
so if you click on map and on that place if the item on placed then it will
check for the item hit other it refer the user click on map not on marker
*/
if(items!=null){
for(int i=0;i<items.size();i++){
OverlayItem item = items.get(i);
Point mp=new Point(0,0);
mapView.getProjection().toPixels(item.getPoint(), mp);
xDragTouchOffset=x-mp.x;
yDragTouchOffset=y-mp.y;
if (hitTest(item, marker, x-(mp.x-(xDragImageOffset+xDragTouchOffset*2)), y-(mp.y-((yDragImageOffset/2)+yDragTouchOffset)))) {
result = true;
markerIndex = i;
task_id = Long.parseLong(item.getTitle());
downPressed = false;
markerPressed = true;
break;
}
}
}
}
else if (action==MotionEvent.ACTION_MOVE) {
// here user pressed and drag the downPressed set to false so it will indicate that user want to move the map and drag set to true;
downPressed = false;
drag=true;
}
else if (action==MotionEvent.ACTION_UP) {
// if user not drag then this downPressed is true and it will return the screen and map coordinate
if(downPressed){
tempPoint = mapView.getProjection().fromPixels(x, y);
markerLat = tempPoint.getLatitudeE6()/1e6;
markerLng = tempPoint.getLongitudeE6()/1e6;
mapView.invalidate();
}
drag = false;
downPressed = false;
}
return(result | super.onTouchEvent(event, mapView));
}
here i can do this way hope you get some idea
Related
I have to make an application with a marker on the center of a srceen and by moving the map
and not the marker get lat,lon of the point that the marker shows. I have search the internet for something like Drag Marker but I am
not sure if this is what I need.Any Solution?
In your mapActivity wrtie this.
Location l = new Location();
// Location class will be used to calculate distance moved by map
TimerTask tm;
GeoPoint oldCenterOfMap, newCenteOfMap;
// On your on resume method of activity do oldCenterOfMap = mapView.getMapCenter();
Handler mHandler = new Handler();
int isTouched = 0;
MapView mapview = (MapView) findViewById(R.id.yourmapview_from_xml);
mapView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
newCenteOfMap = mapView.getMapCenter();
if (mapchanged(oldCenterOfMap, newCenteOfMap)) {
isTouched++;
// Here is what would you do when you lift your finger fromt he map*****
newCenteOfMap =mapView.getMapCenter());
if (isTouched >= 1) {
if (isTouched > 1) {
mHandler.removeCallbacks(tm_circle);
isTouched = 1;
}
mHandler.postDelayed(tm_circle, 1200);
}
}
if (!mapchanged(oldCenterOfMap, newCenteOfMap))
mHandler.removeCallbacks(tm_circle);
}
return false;
}
});
tm_circle = new TimerTask() {
#Override
public void run() {
isTouched = 0;
// here is what you do after you touched a map moved after 1.2 seconds
oldCenterOfMap = mapView.getMapCenter();
}
};
public boolean mapchanged(GeoPoint oldCenter, GeoPoint newCenter) {
String distance = l.CalclauteDistance(oldCenter.getLongitudeE6() / 1E6,
oldCenter.getLatitudeE6() / 1E6,
newCenter.getLongitudeE6() / 1E6,
newCenter.getLatitudeE6() / 1E6);
if (Double.valueOf(distance) == 0.0)
return false;
else
return true;
}
Previous code would keep the track of the map movement.
Next code will respond in case of map movement.
In the comments present in the code above ( // here is what you do after you touched a map moved after 1.2 seconds AND // Here is what would you do when you lift your finger fromt he map*****) follow the instruction on my answer on another post.
Here Adding multiple overlays on mapview dynamically
Edit
public String CalclauteDistance(double long1, double lat1, double long2,
double lat2) {
String Result;
Point p1 = new Point(long1, lat1);
Point p2 = new Point(long2, lat2);
Result = p1.distanceTo(p2) + "";
return Result;
}
Here is the function (CalclauteDistance) from location class.
i am working with android program here i have two classes PlaceMapActivity and AddItemizedOverlay i want to send a string from PlaceMapActivity to the AddItemizedOverlay class can any one help me to solve this and here is my two classes
AddItemizedOverlay
public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
String reference;
private Activity activity;
String p_u_name;
String username;
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) {
OverlayItem item = mapOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(this.context);
dialog.setTitle(item.getTitle());
dialog.setMessage("Do you want ot park here ?");
reference = item.getSnippet();
dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences prefs = context.getSharedPreferences("myprefs", 0);
SharedPreferences.Editor editor =prefs.edit();
editor.putString("KEY_REFERENCE", reference);
editor.commit();
Intent intent = new Intent(context, SinglePlaceActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
// MainActivity.this.finish();
}
});
dialog.show();
return true;
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
}
public void populateNow(){
this.populate();
}
}
and the second class is here
PlacesMapActivity.java
public class PlacesMapActivity extends MapActivity {
// Nearest places
PlacesList nearPlaces;
// Map view
MapView mapView;
// Map overlay items
List<Overlay> mapOverlays;
AddItemizedOverlay itemizedOverlay;
GeoPoint geoPoint;
// Map controllers
MapController mc;
double latitude;
double longitude;
OverlayItem overlayitem,wma;
String p_u_name;
Place reference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_places);
// Getting intent data
Intent i = getIntent();
p_u_name = i.getExtras().getString("KEY_USERNAME");
// AddItemizedOverlay its_obj = new AddItemizedOverlay(null);
// its_obj.getstring(p_u_name);
System.out.println("place map activity :got username"+p_u_name);
reference = (Place) i.getSerializableExtra("place_reference");
// Users current geo location
String user_latitude = i.getStringExtra("user_latitude");
String user_longitude = i.getStringExtra("user_longitude");
System.out.println("sarath"+user_latitude + user_longitude);
// Nearplaces list
nearPlaces = (PlacesList) i.getSerializableExtra("near_places");
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
// Geopoint to place on map
geoPoint = new GeoPoint((int) (Double.parseDouble(user_latitude) * 1E6),(int) (Double.parseDouble(user_longitude) * 1E6));
// Drawable marker icon
Drawable drawable_user = this.getResources().getDrawable(R.drawable.mark_red);
itemizedOverlay = new AddItemizedOverlay(drawable_user, this);
// Map overlay item
overlayitem = new OverlayItem(geoPoint, "Your Location","That is you!");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
itemizedOverlay.populateNow();
// Drawable marker icon
Drawable drawable = this.getResources().getDrawable(R.drawable.mark_blue);
itemizedOverlay = new AddItemizedOverlay(drawable, this);
mc = mapView.getController();
// These values are used to get map boundary area
// The area where you can see all the markers on screen
int minLat = Integer.MAX_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int maxLong = Integer.MIN_VALUE;
// check for null in case it is null
if (nearPlaces.results != null) {
// loop through all the places
for (Place place : nearPlaces.results) {
latitude = place.geometry.location.lat; // latitude
longitude = place.geometry.location.lng; // longitude
// Geopoint to place on map
geoPoint = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
// Map overlay item
overlayitem = new OverlayItem(geoPoint,place.name,place.reference);
itemizedOverlay.addOverlay(overlayitem);
// calculating map boundary area
minLat = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
maxLat = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
}
mapOverlays.add(itemizedOverlay);
// showing all overlay items
itemizedOverlay.populateNow();
}
// Adjusting the zoom level so that you can see all the markers on map
mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
// Showing the center of the map
mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
mapView.postInvalidate();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
Semd String when you create AddItemizedOverlay class object.
Write this in your activity class
itemizedOverlay = new AddItemizedOverlay(drawable_user, this,StringData);
Write this in your OverLay class
private String StringData;
public AddItemizedOverlay(Drawable defaultMarker, Context context,String StringData) {
this(defaultMarker);
this.context = context;
this.StringData=StringData;
}
Try this way....
Thanks
So I've spent a good amount of time attempting to figure out how to speed this up, but I'm out of ideas now. I have a class, mapPopup in which a MapView is displayed over the entire screen. There is an array of an array of GeoPoint in mapPopup, and I want to draw lines between each GeoPoint in the 2nd dimensions of the array. I've accomplished this task already using a custom class, mapOverlay, that extends Overlay, but the problem I am having is that once all the map overlays are drawn, the map is extremely slow to zoom or pan. Once all the overlays are added to the map there are often over 2000, but they are all very small.
Thinking that the map would work more quickly if there were less overlays, I drew all the lines to three seperate overlays instead of a seperate overlay for each line. This actually resulted in SLOWER panning and zooming of the map, so I reverted back to the many small overlays.
I would appreciate some informative and easy to understand descriptions of a method that I could employ to make the map faster. Pseudocode or real code for the potential method would also help me to understand it better. My code is posted below. Once more, please note that my overlays and map display properly; I would just like a method that will allow faster panning and zooming.
mapOverlay class
public class mapOverlay extends Overlay {
private Projection projection;
private GeoPoint gp1;
private GeoPoint gp2;
private int color;
public mapOverlay(int color, MapView map, GeoPoint geo1, GeoPoint geo2) {
// super();
this.projection = map.getProjection();
this.gp1 = geo1;
this.gp2 = geo2;
this.color = color;
}
public void draw(Canvas canvas, MapView mapv, boolean shadow) {
super.draw(canvas, mapv, false);
Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(4);
mPaint.setColor(this.color);
Point p1 = new Point();
Point p2 = new Point();
Path path1 = new Path();
projection.toPixels(gp1, p1);
projection.toPixels(gp2, p2);
path1.moveTo(p1.x, p1.y);
path1.lineTo(p2.x, p2.y);
canvas.drawPath(path1, mPaint);
}
}
mapPopup class
public class mapPopup extends MapActivity {
public String[] trailNames;
public String tableName = "";
public int numTrails = 0;
public static GeoPoint[][] geoPoints;
public int[] colors = new int[] { Color.WHITE, Color.BLUE, Color.CYAN,
Color.RED, Color.YELLOW, Color.MAGENTA, Color.GRAY, Color.LTGRAY };
public int[] newColors;
// public Bitmap b;
public GeoPoint firstP;
public void loadMapData(Bitmap b, MapView map, int[] colors,
GeoPoint[][] GPAA, int ZoomLevel) {
// GPAA holds an array of an array of GeoPoint
Log.i("DEBUG", "starting loadMapDataTask");
map.setSatellite(true);
MapController mc = map.getController();
mapOverlay[][] mapOverlay = new mapOverlay[GPAA.length][];
Log.i("DEBUG", "length of GPAA is: " + GPAA.length);
// i cycles through the first dimension of GPAA
for (int i = 0; i < GPAA.length; i++) {
GeoPoint[] geoPoints = GPAA[i];
int length = geoPoints.length - 1;
mapOverlay[i] = new mapOverlay[length]; //
int pointCount = 0;
// z cycles through the second dimension of GPAA
for (int z = 0; z < length; z++) {
mapOverlay[i][z] = new mapOverlay(colors[i], map,
geoPoints[pointCount], geoPoints[pointCount + 1]);
pointCount++;
}
}
// Actually adds overlays to map
List<Overlay> mapOverlays = map.getOverlays();
for (int i = 0; i < mapOverlay.length; i++) {
int length = mapOverlay[i].length;
Log.i("DEBUG", "Adding map overlays for trail: " + i);
Log.i("DEBUG", "Length of mapOverlay[i] is: " + length);
for (int z = 0; z < length; z++) {
mapOverlays.add(mapOverlay[i][z]);
}
}
mc.animateTo(GPAA[0][0]);
mc.setZoom(ZoomLevel);
Rect r = new Rect();
map.getDrawingRect(r);
map.invalidate(r);
}
public static class runBGLoad extends
AsyncTask<bgLoadParam, Integer, GeoPoint[][]> {
public GeoPoint[][] geoPoints;
protected GeoPoint[] getGPa(Context context, String name, int ID) {
File file = context.getFileStreamPath(name);
if (file.exists() == false) {
Log.i("DEBUG", "Creating file");
InputStream is;
FileOutputStream fos;
try {
Log.i("DEBUG", "id is " + ID);
is = context.getResources().openRawResource(ID);
byte[] buffer = new byte[is.available()];
is.read(buffer);
fos = context.openFileOutput(name, Context.MODE_PRIVATE);
fos.write(buffer);
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.i("DEBUG", "File already exists");
}
// Log.i("DEBUG", "starting to get geopoints");
List<Location> gpsPoints = XMLParser.getPoints(file);
int i = 0;
int index = 0;
GeoPoint[] geoPoints = new GeoPoint[gpsPoints.size()];
// makes list of gpsPoints into GeoPoint[]
ListIterator<Location> it = gpsPoints.listIterator();
while (it.hasNext()) {
index = it.nextIndex();
Location loc = gpsPoints.get(index);
geoPoints[i] = new GeoPoint((int) (loc.getLatitude() * 1E6),
(int) (loc.getLongitude() * 1E6));
it.next();
i++;
}
return geoPoints;
}
#Override
protected GeoPoint[][] doInBackground(bgLoadParam... params) {
Context context = params[0].getContext();
int tNLength = params[0].getTNames().length;
geoPoints = new GeoPoint[tNLength][];
for (int i = 0; i < params[0].getTNames().length; i++) {
String modName = params[0].getTNames()[i].toLowerCase()
.replace(' ', '_');
int identifier = context.getResources().getIdentifier(modName,
"raw", context.getPackageName());
geoPoints[i] = getGPa(params[0].getContext(), modName
+ "_mapfile", identifier);
}
Log.i("DEBUG", "TEST");
mapPopup.geoPoints = geoPoints;
Log.i("DEBUG", "TEST2");
return geoPoints;
}
#Override
protected void onPostExecute(GeoPoint[][] result) {
Log.i("DEBUG", "The points are loaded.");
mapPopup.geoPoints = result;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String[] extras = intent.getStringArrayExtra("strings");
tableName = extras[1];
numTrails = Integer.parseInt(extras[2]);
trailNames = intent.getStringArrayExtra("trailNamesA");
super.onCreate(savedInstanceState);
setContentView(R.layout.map_popup_layout);
newColors = new int[numTrails];
for (int i = 0; i < numTrails; i++) {
newColors[i] = colors[i];
}
ViewGroup layout = (ViewGroup) findViewById(R.id.map_popup);
TextView[] tVs = new TextView[numTrails];
for (int i = 0; i < numTrails; i++) {
LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tVs[i] = new TextView(getApplicationContext());
tVs[i].setText(trailNames[i]);
tVs[i].setId(i + 700);
tVs[i].setTextColor(colors[i]);
tVs[i].setBackgroundColor(Color.BLACK);
if (i > 0) {
params.addRule(RelativeLayout.BELOW, (699 + i));
}
layout.addView(tVs[i], params);
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
MapView map = (MapView) findViewById(R.id.popupMV);
Bitmap b = Bitmap.createBitmap(map.getWidth(), map.getHeight(),
Bitmap.Config.RGB_565);
try {
trailsActivity.mapPreLoad.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
loadMapData(b, map, newColors, geoPoints, 17);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
I'm currently facing the same problematic, and I just found a workaround : prevent the overlays from drawing when zooming or panning. That's not perfect and I'm still looking for a better solution, but at least the map is usable without waiting 5 seconds for each pan or zoom.
Here is the code I used in my Overlay extension. It's not Java but C# (using Monodroid) - but it should be easily understandable.
public override bool OnTouchEvent (MotionEvent e, Android.GoogleMaps.MapView mapView)
{
if (e.Action == MotionEventActions.Down)
_mustDraw = false;
else if (e.Action == MotionEventActions.Up)
_mustDraw = true;
return base.OnTouchEvent (e, mapView);
}
public override void Draw (Android.Graphics.Canvas canvas, Android.GoogleMaps.MapView mapView, bool shadow)
{
if (shadow || !_mustDraw)
return;
// ...
}
That solution works for every map-touch based action, and now performs with a good speed, I just lack implementation of the same behaviour when zooming in or out using built-in zoom controls, but I first need to fight some of my bugs before doing this part, I'll come back on this part later.
Hi iam displaying mulitple markers in google map in android.while iam displaying, the markers are displaying in the google map one by one.Here i want to display more than 50 markers.But according to my code the markers are displaying one by one and to display 50 markers it is taking so much time.Below is my code which is in the same class.Any idea is appreciated.
public void displayMarkersOnMap(){
Runnable r=new Runnable(){
public void run(){
for (int i = 0; i < vector.size(); i++) {
try {
pinHM = (HashMap<String, Object>)vector.get(i);
mapView = (MapView)findViewById(R.id.mapView);
mapView.getController().setZoom(9);
Drawable marker;
else{
String status = pinHM.get("status").toString();
if (status.equals("ST_COMPLETE")) {
marker = getResources().getDrawable(R.drawable.pin_green);
}else if (status.equals("ST_IN_PROGRESS")) {
marker = getResources().getDrawable(R.drawable.pin_orange);
}else {
marker = getResources().getDrawable(R.drawable.pin_gray);
}
}
marker.setBounds((int) (-marker.getIntrinsicWidth() / 2),-marker.getIntrinsicHeight(),(int) (marker.getIntrinsicWidth() / 2), 0);
double latitude=Double.parseDouble(pinHM.get("latitude").toString());
double longitude=Double.parseDouble(pinHM.get("longitude").toString());
Geocoder geoCoder = new Geocoder(BaseMapActivity.this, Locale.getDefault());
List<Address> addresses = geoCoder.getFromLocationName(address,5);
if (addresses.size() > 0) {
GeoPoint point = new GeoPoint((int)(latitude*1E6),(int)(longitude*1E6));
funPlaces = new MyItemizedOverlay(point,marker,hmtostring,nameaddress,mapView);
mapView.getOverlays().add(funPlaces);
GeoPoint pt = funPlaces.getCenterPt();
int latSpan = funPlaces.getLatSpanE6();
int lonSpan = funPlaces.getLonSpanE6();
Log.v("Overlays", "Lat span is " + latSpan);
Log.v("Overlays", "Lon span is " + lonSpan);
MapController mc = mapView.getController();
mc.setCenter(pt);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}//end of run
};//end of Runnable
Thread thread = new Thread(r, "BaseMapActiviy");
thread.start();
}
public class MyItemizedOverlay extends BalloonItemizedOverlay {
private ArrayList<OverlayItem> m_overlays = new ArrayList<OverlayItem>();
#SuppressWarnings("unused")
private Context c;
private GeoPoint center = null;
public MyItemizedOverlay(GeoPoint point, Drawable marker,String hmtostring,String nameaddress,MapView mapView) {
super(boundCenter(marker), mapView);
c = mapView.getContext();
m_overlays.add(new OverlayItem(point,hmtostring,nameaddress));
populate();
}
public GeoPoint getCenterPt() {
if (center == null) {
int northEdge = -90000000;
int southEdge = 90000000;
int eastEdge = -180000000;
int westEdge = 180000000;
Iterator<OverlayItem> iter = m_overlays.iterator();
while (iter.hasNext()) {
GeoPoint pt = iter.next().getPoint();
if (pt.getLatitudeE6() > northEdge)
northEdge = pt.getLatitudeE6();
if (pt.getLatitudeE6() < southEdge)
southEdge = pt.getLatitudeE6();
if (pt.getLongitudeE6() > eastEdge)
eastEdge = pt.getLongitudeE6();
if (pt.getLongitudeE6() < westEdge)
westEdge = pt.getLongitudeE6();
}
center = new GeoPoint((int) ((northEdge + southEdge) / 2),
(int) ((westEdge + eastEdge) / 2));
}
return center;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
if (!shadow) {
super.draw(canvas, mapView, shadow);
}
return false;
}
public void addOverlay(OverlayItem overlay) {
m_overlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return m_overlays.get(i);
}
#Override
public int size() {
return m_overlays.size();
}
#Override
protected boolean onBalloonTap(int index) {
return true;
}
}
I just went through this myself. For your specific case define a new OverlayItem (not MyItemizedOverlay) with whatever then just add it to MyItemizedOverlay.
For your case it would be something like this.
OverlayItem anotherFunPlace = new OverlayItem(theGeoPointYouWantItAt,"Some string","Another String");
//Then you would use the following to add it
FunPlaces.add(anotherFunPlace);
Make sure to place those above lines before
mapView.getOverlays().add(funPlaces);
Hope that helps. Let me know if I missed something or if you have other problems.
I am overlaying custom radar weather tiles on top of Google Maps. I'd also like to add a location pin marker in accordance with city the user is viewing weather from. I can't figure out how to have the tiles AND a marker. I can do one or the other, but not both....any help?
I have a MapsItemizedOverlay class:
<pre><code>public class MapsItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private static final String DEBUG_TAG = "TurboWeather/MapsItemizedOverlay";
private ArrayList<OverlayItem> myOverlays = new ArrayList<OverlayItem>();
//private ArrayList<Drawable> mDrawables = new ArrayList<Drawable>();
//private ArrayList<GeoPoints> mGeoPoints = new ArrayList<GeoPoints>();
public MapsItemizedOverlay(Drawable defaultMarkers, Context context) {
super(boundCenterBottom(defaultMarkers));
//Log.i(DEBUG_TAG, "MapsItemizedOverlay constructor");
populate();
}
public void addOverlay(OverlayItem overlay){
//Log.i(DEBUG_TAG, "addOverlay");
myOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
//Log.i(DEBUG_TAG, "createItem");
return myOverlays.get(i);
}
// Returns present number of items in list
#Override
public int size() {
return myOverlays.size();
}
#Override
public void draw(Canvas canvas, MapView mapview, boolean shadow) {
super.draw(canvas, mapview, false);
}
}
And here is where I utilize the MapsItemizedOverlay class and am able to draw the custom radar image tiles to Google Maps:
private void addOverlay(Drawable drawable, int xTile, int yTile) {
OverlayItem overlayitem, locationOverlayitem;
GeoPoint geopoint, locGeopoint;
int x1 = 0, y1 = 0;
double lat[] = {0.0};
double lon[] = {0.0};
int x[] = {0};
int y[] = {0};
mCurrentProjection.fromPixels(x1, y1);
mMapOverlays = mMapView.getOverlays();
x = new int[] {xTile};
y = new int[] {yTile};
TileSystem.TileXYToPixelXY(xTile, yTile, x, y);
TileSystem.PixelXYToLatLong(x, y, mZoomLevel, lat, lon);
Log.i(DEBUG_TAG, "X: " + x[0] + " Y: " + y[0]);
//Log.i(DEBUG_TAG, "GeoPointX is " + lat[0] + ", GeoPointY is " + lon[0]);
geopoint = new GeoPoint((int)(lat[0] * 1E6), (int)(lon[0] * 1E6));
if (mMapOverlays.size() == 0) {
mItemizedOverlay = new MapsItemizedOverlay(drawable, mContext) {
public boolean onTouchEvent(MotionEvent event, com.google.android.maps.MapView mv) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
post(new Runnable() {
#Override
public void run() {
mMapView.getOverlays().clear();
getAccuWxTiles(mMapVars);
}
});
break;
}
return false;
}
};
} else {
mItemizedOverlay = new MapsItemizedOverlay(drawable, mContext);
}
overlayitem = new OverlayItem(geopoint, "", "");
mItemizedOverlay.addOverlay(overlayitem);
mMapOverlays.add(mItemizedOverlay);
mMapView.invalidate();
}