Hey this is what i have written to get the radius as well as the current location point. but it does not center and show. what have i done wrong?
as shown as bellow
please be kind enough to help me with the cording. thank you
public class MappingActivity extends MapActivity {
/** Called when the activity is first created. */
MapController mControl;
GeoPoint GeoP;
MapView mapV;
Drawable d;
List<Overlay> overlaylist;
public double lat;
public double lng;
Button checkin, addplace;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in
// Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 10000; // in
// Milliseconds
protected LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapV = (MapView) findViewById(R.id.mapview);
checkin = (Button) findViewById(R.id.check);
addplace = (Button) findViewById(R.id.addp);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
lat = 6;//location.getLatitude();
lng = 77.6;//location.getLongitude();
}
Button check = (Button) findViewById(R.id.check);
Button addplace = (Button) findViewById(R.id.addp);
Button nearby = (Button) findViewById(R.id.point);
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
TextView result = (TextView) findViewById(R.id.result);
result.setText("Checked the Plce");
}
});
addplace.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
TextView result = (TextView) findViewById(R.id.result);
result.setText("Added the Plce");
}
});
nearby.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
TextView result = (TextView) findViewById(R.id.result);
result.setText("Nearby the Plce");
}
});
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
String message = String.format("You are Here");
Toast.makeText(MappingActivity.this, message, Toast.LENGTH_LONG)
.show();
GeoP = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mControl = mapV.getController();
mControl.animateTo(GeoP);
mControl.setZoom(19);
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapV.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapV.invalidate();
}
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
}
class MapOverlay extends com.google.android.maps.Overlay
{
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, shadow);
Projection projection = mapView.getProjection();
Point pt = new Point();
projection.toPixels(GeoP ,pt);
float circleRadius = projection.metersToEquatorPixels(50);
Paint innerCirclePaint;
innerCirclePaint = new Paint();
innerCirclePaint.setColor(Color.BLUE);
innerCirclePaint.setAlpha(25);
innerCirclePaint.setAntiAlias(true);
innerCirclePaint.setStyle(Paint.Style.FILL);
Paint CirclePaint;
CirclePaint = new Paint();
CirclePaint.setColor(Color.BLUE);
CirclePaint.setAlpha(100);
CirclePaint.setAntiAlias(true);
//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(
getResources(), R.drawable.point);
canvas.drawBitmap(bmp, pt.x, pt.y-bmp.getHeight(), CirclePaint);
super.draw(canvas,mapView,shadow);
canvas.drawCircle((float)pt.x, (float)pt.y, circleRadius, innerCirclePaint);
}
}
}
}
Your sample code works fine for me but I used it a little differently
public class Map extends MapActivity{
private double latitude, longitude, accuracy;
private int centerLatitude, centerLongitude;
private MyLocationOverlay userLocationOverlay;
private MapView mapView;
private GeoPoint point, center;
private MapController mapController;
private CountDownTimer timer;
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.map_view);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(false);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.dotpin);
MyItemizedOverlay itemizedoverlay = new MyItemizedOverlay(drawable, this);
//Open Database
DbHelper dbHelper = new DbHelper(getApplicationContext());
SQLiteDatabase db = dbHelper.getReadableDatabase();
//Get Values
String[] Labels = {DbHelper.Latitude, DbHelper.Longitude, DbHelper.Accuracy};
Cursor cursor = db.query(DbHelper.TABLE_NAME, Labels, null, null, null, null, null);
if(cursor.moveToFirst()){
do{
latitude = cursor.getDouble(cursor.getColumnIndex(Labels[0])) *1000000;
longitude = cursor.getDouble(cursor.getColumnIndex(Labels[1])) *1000000;
accuracy = cursor.getDouble(cursor.getColumnIndex(Labels[2]));
}while(cursor.moveToNext());
}
//Close Database
cursor.close();
db.close();
dbHelper.close();
//User Location Overlay
userLocationOverlay = new MyLocationOverlay(getApplicationContext(), mapView);
//Set Location Overlay
point = new GeoPoint((int)(latitude),(int)(longitude));
OverlayItem overlayitem = new OverlayItem(point, "Radius", String.format("%.0f m", accuracy));
itemizedoverlay.addOverlay(overlayitem);
//Add overlays
MapOverlay mapOverlay = new MapOverlay();
mapOverlays.add(mapOverlay);
mapOverlays.add(userLocationOverlay);
mapOverlays.add(itemizedoverlay);
}
#Override
protected void onResume() {
super.onResume();
userLocationOverlay.enableMyLocation();
//Pan to location
mapController = mapView.getController();
//Update the map view
zoomUpdate();
//Refresh view
mapView.postInvalidate();
}
#Override
protected void onPause() {
super.onPause();
userLocationOverlay.disableMyLocation();
if(timer!=null)
timer.cancel();
}
protected void zoomUpdate(){
if(timer != null)
timer.cancel();
timer = new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished){}
public void onFinish() {
if(userLocationOverlay.getMyLocation() != null)
zoomInOnPoints(point, userLocationOverlay.getMyLocation());
else
Toast.makeText(getApplicationContext(), "Waiting for location", Toast.LENGTH_SHORT).show();
zoomUpdate();
}
};
timer.start();
}
#SuppressWarnings("deprecation")
private void zoomInOnPoints(GeoPoint setLocation, GeoPoint userLocation) {
int x_pixels = getWindowManager().getDefaultDisplay().getWidth();
int y_pixels = getWindowManager().getDefaultDisplay().getHeight();
boolean set = false;
int latSpan, longSpan, rightEdge, leftEdge, topEdge, bottomEdge;
boolean setIsIn, userIsIn;
center = new GeoPoint((point.getLatitudeE6() + userLocationOverlay.getMyLocation().getLatitudeE6())/2,(point.getLongitudeE6() + point.getLongitudeE6())/2);
centerLatitude = center.getLatitudeE6();
centerLongitude = center.getLongitudeE6();
mapController.animateTo(center);
while(!set){
latSpan = mapView.getLatitudeSpan();
longSpan = mapView.getLongitudeSpan();
rightEdge = centerLongitude+longSpan/2;
leftEdge = centerLongitude-longSpan/2;
topEdge = centerLatitude+latSpan/2;
bottomEdge = centerLatitude-latSpan/2;
setIsIn = setLocation.getLatitudeE6() > bottomEdge && setLocation.getLatitudeE6() < topEdge && setLocation.getLongitudeE6() < rightEdge && setLocation.getLongitudeE6() > leftEdge;
userIsIn = userLocation.getLatitudeE6() > bottomEdge && userLocation.getLatitudeE6() < topEdge && userLocation.getLongitudeE6() < rightEdge && userLocation.getLongitudeE6() > leftEdge;
if(setIsIn && userIsIn && mapView.getZoomLevel() < mapView.getMaxZoomLevel()){
mapController.zoomInFixing(x_pixels/2, y_pixels/2);
mapController.animateTo(center);
mapView.postInvalidate();
}
else{
while(!set){
latSpan = mapView.getLatitudeSpan();
longSpan = mapView.getLongitudeSpan();
rightEdge = centerLongitude+longSpan/2;
leftEdge = centerLongitude-longSpan/2;
topEdge = centerLatitude+latSpan/2;
bottomEdge = centerLatitude-latSpan/2;
setIsIn = setLocation.getLatitudeE6() > bottomEdge && setLocation.getLatitudeE6() < topEdge && setLocation.getLongitudeE6() < rightEdge && setLocation.getLongitudeE6() > leftEdge;
userIsIn = userLocation.getLatitudeE6() > bottomEdge && userLocation.getLatitudeE6() < topEdge && userLocation.getLongitudeE6() < rightEdge && userLocation.getLongitudeE6() > leftEdge;
if(!(setIsIn && userIsIn) && mapView.getZoomLevel() > 1){
mapController.zoomOutFixing(x_pixels/2, y_pixels/2);
mapController.animateTo(center);
mapView.postInvalidate();
}
else{
set = true;
}
}
}
}
}
public class MyItemizedOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public MyItemizedOverlay(Drawable arg0, Context context) {
super(boundCenter(arg0));
mContext = context;
// TODO Auto-generated constructor stub
}
#Override
protected OverlayItem createItem(int arg0) {
return mOverlays.get(arg0);
}
#Override
public int size() {
// TODO Auto-generated method stub
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;
}
}
class MapOverlay extends com.google.android.maps.Overlay
{
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, shadow);
Projection projection = mapView.getProjection();
Point pt = new Point();
projection.toPixels(point ,pt);
float circleRadius = projection.metersToEquatorPixels((float)accuracy);
Paint innerCirclePaint;
innerCirclePaint = new Paint();
innerCirclePaint.setColor(Color.BLUE);
innerCirclePaint.setAlpha(25);
innerCirclePaint.setAntiAlias(true);
innerCirclePaint.setStyle(Paint.Style.FILL);
Paint CirclePaint;
CirclePaint = new Paint();
CirclePaint.setColor(Color.BLUE);
CirclePaint.setAlpha(100);
CirclePaint.setAntiAlias(true);
canvas.drawCircle((float)pt.x, (float)pt.y, circleRadius, innerCirclePaint);
}
}
}
Related
I want to add an info window on top of Each marker set when user tap on a marker. Here is my code. The marker is fine i need only the infowindow appears on top of it. how can i achieve this, here is my code
public class MainActivity extends MapActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
Drawable makerDefault = this.getResources().getDrawable(R.drawable.marker_default);
MyItemizedOverlay itemizedOverlay = new MyItemizedOverlay(makerDefault);
Drawable windmill = getResources().getDrawable(R.drawable.windmill);
Drawable bigBen = getResources().getDrawable(R.drawable.big_ben);
Drawable eiffelTower = getResources().getDrawable(R.drawable.eiffel_tower);
itemizedOverlay.addOverlayItem(52372991, 4892655, "Amsterdam", windmill);
itemizedOverlay.addOverlayItem(51501851, -140623, "London", bigBen);
itemizedOverlay.addOverlayItem(48857522, 2294496, "Paris", eiffelTower);
mapView.getOverlays().add(itemizedOverlay);
MapController mc = mapView.getController();
mc.setCenter(new GeoPoint(51035349, 2370987)); // Dunkerque, Belgium
mc.zoomToSpan(itemizedOverlay.getLatSpanE6(), itemizedOverlay.getLonSpanE6());
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
private class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public MyItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public void addOverlayItem(int lat, int lon, String title, Drawable altMarker) {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem, altMarker);
}
public void addOverlayItem(OverlayItem overlayItem) {
mOverlays.add(overlayItem);
populate();
}
public void addOverlayItem(OverlayItem overlayItem, Drawable altMarker) {
overlayItem.setMarker(boundCenterBottom(altMarker));
addOverlayItem(overlayItem);
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
#Override
protected boolean onTap(int index) {
Toast.makeText(MainActivity.this, getItem(index).getTitle(), Toast.LENGTH_LONG).show();
return true;
}
}
}
SitesOverlay.class
private class SitesOverlay extends ItemizedOverlay<CustomItem> {
private List<CustomItem> items;
private View view = null;
public SitesOverlay() {
super(null);
items = new ArrayList<CustomItem>();
items.add(new CustomItem(pt, busName, "Bendigo", marker));
boundCenter(marker);
populate();
}
#Override
protected CustomItem createItem(int i) {
return (items.get(i));
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
if (!shadow) {
super.draw(canvas, mapView, false);
}
}
#Override
public int size() {
return (items.size());
}
public void refresh() {
populate();
}
public void clear() {
items.clear();
resetLastFocuesIndex();
}
public void resetLastFocuesIndex() {
setLastFocusedIndex(-1);
}
#Override
protected boolean onTap(final int index) {
if (view != null) {
view.setVisibility(View.GONE);
getMapView().removeView(view);
getMapView().invalidate();
view = null;
}
view = getLayoutInflater().inflate(R.layout.balloon_overlay, null);
LinearLayout layout = (LinearLayout) view
.findViewById(R.id.balloon_main_layout);
layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
view.setBackgroundResource(R.drawable.balloon_overlay_bg_selector);
ImageView image = (ImageView) view
.findViewById(R.id.balloon_disclosure);
TextView text = (TextView) view
.findViewById(R.id.balloon_item_title);
text.setText(items.get(index).getTitle());
Projection projection = getMapView().getProjection();
Point point = new Point();
projection.toPixels(items.get(index).getPoint(), point);
int x = (int) (view.getWidth() / 2f);
int y = -marker.getIntrinsicHeight() - 3;
MapView.LayoutParams lp = new MapView.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, items.get(index)
.getPoint(), x, y + 50,
MapView.LayoutParams.BOTTOM_CENTER);
getMapView().removeView(view);
getMapView().invalidate();
getMapView().addView(view, lp);
getMapView().invalidate();
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (!items.isEmpty()) {
if (view != null) {
view.setVisibility(View.GONE);
getMapView().invalidate();
// Intent intent=new Intent(MapLocationActivity.this,);
}
}
getMapView().invalidate();
}
});
return true;
}
}
class CustomItem extends OverlayItem {
Drawable marker = null;
CustomItem(GeoPoint pt, String name, String snippet, Drawable marker) {
super(pt, name, snippet);
this.marker = marker;
}
#Override
public Drawable getMarker(int stateBitset) {
Drawable result = marker;
setState(result, stateBitset);
return (result);
}
}
set Overlay mapview.getOverlays().add(new SitesOverlay());
if there is multiple marker then
for (int i = 0; i < arrayList.size(); i++) {
slat = Double.parseDouble(arrayList.get(i).getLat());
vlong = Double.parseDouble(arrayList.get(i).getvLong());
pt = new GeoPoint((int) (slat * 1E6), (int) (vlong * 1E6));
Log.e("lat long", "--- "+slat);
MapviewActivity.this.mc.animateTo(pt);
items.add(new CustomItem(pt, arrayList.get(i).getBuissnessName(), "Bendigo", marker));
boundCenter(marker);
}
In the CustomMap.java class below, i want to customised the code so that i can add arrays of geopoints, multiple itemisedOvelay as in CustomMap Part 2.
public class CustomMap extends MapActivity {
MapView mapView;
List<Overlay> mapOverlays;
Drawable drawable;
Drawable drawable2;
CustomItemizedOverlay<CustomOverlayItem> itemizedOverlay;
CustomItemizedOverlay<CustomOverlayItem> itemizedOverlay2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
// first overlay
drawable = getResources().getDrawable(R.drawable.marker);
itemizedOverlay = new CustomItemizedOverlay<CustomOverlayItem>(drawable, mapView);
GeoPoint point = new GeoPoint((int)(51.5174723*1E6),(int)(-0.0899537*1E6));
CustomOverlayItem overlayItem = new CustomOverlayItem(point, "Tomorrow Never Dies (1997)",
"(M gives Bond his mission in Daimler car)",
"http://ia.media-imdb.com/images/M/MV5BMTM1MTk2ODQxNV5BMl5BanBnXkFtZTcwOTY5MDg0NA##._V1._SX40_CR0,0,40,54_.jpg");
itemizedOverlay.addOverlay(overlayItem);
GeoPoint point2 = new GeoPoint((int)(51.515259*1E6),(int)(-0.086623*1E6));
CustomOverlayItem overlayItem2 = new CustomOverlayItem(point2, "GoldenEye (1995)",
"(Interiors Russian defence ministry council chambers in St Petersburg)",
"http://ia.media-imdb.com/images/M/MV5BMzk2OTg4MTk1NF5BMl5BanBnXkFtZTcwNjExNTgzNA##._V1._SX40_CR0,0,40,54_.jpg");
itemizedOverlay.addOverlay(overlayItem2);
mapOverlays.add(itemizedOverlay);
// second overlay
drawable2 = getResources().getDrawable(R.drawable.marker2);
itemizedOverlay2 = new CustomItemizedOverlay<CustomOverlayItem>(drawable2, mapView);
GeoPoint point3 = new GeoPoint((int)(51.513329*1E6),(int)(-0.08896*1E6));
CustomOverlayItem overlayItem3 = new CustomOverlayItem(point3, "Sliding Doors (1998)",
"(interiors)", null);
itemizedOverlay2.addOverlay(overlayItem3);
GeoPoint point4 = new GeoPoint((int)(51.51738*1E6),(int)(-0.08186*1E6));
CustomOverlayItem overlayItem4 = new CustomOverlayItem(point4, "Mission: Impossible (1996)",
"(Ethan & Jim cafe meeting)",
"http://ia.media-imdb.com/images/M/MV5BMjAyNjk5Njk0MV5BMl5BanBnXkFtZTcwOTA4MjIyMQ##._V1._SX40_CR0,0,40,54_.jpg");
itemizedOverlay2.addOverlay(overlayItem4);
mapOverlays.add(itemizedOverlay2);
final MapController mc = mapView.getController();
mc.animateTo(point2);
mc.setZoom(16);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
Code Part 2:
This is not the code but a little logic of how i want the change to be made. To sum up, i try to make CustomMap.java flexible so that i can add multiple points and information to it throught arrays.
public class CustomMap extends MapActivity {
MapView mapView;
List<Overlay> mapOverlays;
Drawable drawable;
Drawable drawable2;
CustomItemizedOverlay<CustomOverlayItem> itemizedOverlay[];
CustomItemizedOverlay<CustomOverlayItem> itemizedOverlay2[];
double[]lat,lon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
// first overlay
drawable = getResources().getDrawable(R.drawable.marker);
itemizedOverlay = new CustomItemizedOverlay<CustomOverlayItem>(drawable, mapView);
GeoPoint point[] = new GeoPoint((int)(lat*1E6),(int)(lon*1E6));
CustomOverlayItem overlayItem = new CustomOverlayItem(point, "Tomorrow Never Dies (1997)",
"(M gives Bond his mission in Daimler car)",
"http://ia.media-imdb.com/images/M/MV5BMTM1MTk2ODQxNV5BMl5BanBnXkFtZTcwOTY5MDg0NA##._V1._SX40_CR0,0,40,54_.jpg");
itemizedOverlay.addOverlay(overlayItem);
mapOverlays.add(itemizedOverlay);
final MapController mc = mapView.getController();
mc.animateTo(point2);
mc.setZoom(16);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
set Overlay mapview.getOverlays().add(new SitesOverlay());
for custom popup
SitesOverlay.class
private class SitesOverlay extends ItemizedOverlay<CustomItem> {
private List<CustomItem> items;
private View view = null;
public SitesOverlay() {
super(null);
items = new ArrayList<CustomItem>();
items.add(new CustomItem(pt, busName, "Bendigo", marker));
boundCenter(marker);
populate();
}
#Override
protected CustomItem createItem(int i) {
return (items.get(i));
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
if (!shadow) {
super.draw(canvas, mapView, false);
}
}
#Override
public int size() {
return (items.size());
}
public void refresh() {
populate();
}
public void clear() {
items.clear();
resetLastFocuesIndex();
}
public void resetLastFocuesIndex() {
setLastFocusedIndex(-1);
}
#Override
protected boolean onTap(final int index) {
if (view != null) {
view.setVisibility(View.GONE);
getMapView().removeView(view);
getMapView().invalidate();
view = null;
}
view = getLayoutInflater().inflate(R.layout.balloon_overlay, null);
LinearLayout layout = (LinearLayout) view
.findViewById(R.id.balloon_main_layout);
layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
view.setBackgroundResource(R.drawable.balloon_overlay_bg_selector);
ImageView image = (ImageView) view
.findViewById(R.id.balloon_disclosure);
TextView text = (TextView) view
.findViewById(R.id.balloon_item_title);
text.setText(items.get(index).getTitle());
Projection projection = getMapView().getProjection();
Point point = new Point();
projection.toPixels(items.get(index).getPoint(), point);
int x = (int) (view.getWidth() / 2f);
int y = -marker.getIntrinsicHeight() - 3;
MapView.LayoutParams lp = new MapView.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, items.get(index)
.getPoint(), x, y + 50,
MapView.LayoutParams.BOTTOM_CENTER);
getMapView().removeView(view);
getMapView().invalidate();
getMapView().addView(view, lp);
getMapView().invalidate();
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (!items.isEmpty()) {
if (view != null) {
view.setVisibility(View.GONE);
getMapView().invalidate();
// Intent intent=new Intent(MapLocationActivity.this,);
}
}
getMapView().invalidate();
}
});
return true;
}
}
class CustomItem extends OverlayItem {
Drawable marker = null;
CustomItem(GeoPoint pt, String name, String snippet, Drawable marker) {
super(pt, name, snippet);
this.marker = marker;
}
#Override
public Drawable getMarker(int stateBitset) {
Drawable result = marker;
setState(result, stateBitset);
return (result);
}
}
if there is multiple marker then
for (int i = 0; i < arrayList.size(); i++) {
slat = Double.parseDouble(arrayList.get(i).getLat());
vlong = Double.parseDouble(arrayList.get(i).getvLong());
pt = new GeoPoint((int) (slat * 1E6), (int) (vlong * 1E6));
Log.e("lat long", "--- "+slat);
MapviewActivity.this.mc.animateTo(pt);
items.add(new CustomItem(pt, arrayList.get(i).getBuissnessName(), "Bendigo", marker));
boundCenter(marker);
}
in SitesOverlay() constructor do this.
I have this MapActivity class below showing a map and putting a pin of the user's current location.
In the other hand I have an Object class VideoLocation which has latitude and longitude of some places which are extracted from a JSON file from the server. I also wanna have the locations are drawn with pins on the map.
How am I able to do that? What do I need to add on my Class below?
FYI this is how I call the object's latitude and longitude on my ListActivity:
VideoLocation vidLocation = videoLocations[position];
double lat2 = vidLocation.latitude;
double lng2 = vidLocation.longitude;
This the class:
public class MyMapActivity extends MapActivity implements OnClickListener {
public static final String TAG = "GoogleMapsActivity";
private MapView mapView;
private LocationManager locationManager;
Geocoder geocoder;
Location location;
LocationListener locationListener;
CountDownTimer locationtimer;
MapController mapController;
MapOverlay mapOverlay = new MapOverlay();
private VideoLocation[] videoLocations = null;
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.my_map_activity);
initComponents();
JsonDB dbhelper = new JsonDB(MyMapActivity.this);
SQLiteDatabase db = dbhelper.getWritableDatabase();
db.beginTransaction();
videoLocations = dbhelper.getVideoLocations(db);
db.setTransactionSuccessful();//end transaction
db.endTransaction();
db.close();
final ImageButton refresh = (ImageButton) findViewById(R.id.btn_nav_impressum);
refresh.setOnClickListener(this);
final ImageButton search =(ImageButton) findViewById(R.id.btn_nav_locater);
search.setOnClickListener(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager == null) {
Toast.makeText(MyMapActivity.this,
"Location Manager Not Available", Toast.LENGTH_SHORT)
.show();
return;
}
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
animateMap(location);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
}
locationListener = new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onLocationChanged(Location l) {
location = l;
locationManager.removeUpdates(this);
if (l.getLatitude() == 0 || l.getLongitude() == 0) {
} else {
double lat = l.getLatitude();
double lng = l.getLongitude();
showAddress(lat,lng);
}
}
};
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 10f, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000, 10f, locationListener);
locationtimer = new CountDownTimer(30000, 5000) {
#Override
public void onTick(long millisUntilFinished) {
if (location != null)
locationtimer.cancel();
}
#Override
public void onFinish() {
if (location == null) {
}
}
};
locationtimer.start();
}
public void animateMap(Location location){
double lat = location.getLatitude();
double lng = location.getLongitude();
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
GeoPoint point2 = new GeoPoint((int) (lat2 * 1E6), (int) (lng2 * 1E6));
mapController.animateTo(point, new Message());
mapOverlay.setPointToDraw(point);
}
public MapView getMapView() {
return this.mapView;
}
private void initComponents() {
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(16);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class MapOverlay extends Overlay {
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_normal);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);
return true;
}
adding ItemizedOverlay class would be better if you want to add pin (or images) on top of your map.
package com.android.testandroidmap;
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 HelloItemizedOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
mContext = context;
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return mOverlays.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
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;
}
}
I get this code from Android Developer Official Guide, and with this class on your code, you can add the overlays.
Add all the things you need (container, image for pins, and the pin+coordinate overlay)
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
for your icons to be recognized by the class before, and also instantiate the coordinate, add the coordinate to an overlayItem + register the overlayItem with the HelloItemizedOverlay you made before
GeoPoint point = new GeoPoint(19240000,-99120000);
OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
itemizedoverlay.addOverlay(overlayitem);
finish with adding the overlay to the mapOverlay, which is a collection of overlays.
mapOverlays.add(itemizedoverlay);
This displays a pin on top of my map, which can be customized by any image you want. If you want to also use different images for each location, just instantiate another Drawable with your image and register that Drawable to other HelloItemizedOverlay.
In my code I have one textbox and one button. Whatever place you type into the textbox, that place has to get searched from Google maps on clicking the button. And an icon has to be shown to the searched place.
In my code I am getting the map, but I am not able to search for the location. Please help.
public class MapActivity extends com.google.android.maps.MapActivity implements
OnClickListener {
/** Called when the activity is first created. */
MapView view;
Button search;
EditText location;
MapController controller;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = (MapView) findViewById(R.id.themap);
location = (EditText) findViewById(R.id.editText1);
search = (Button) findViewById(R.id.search);
search.setOnClickListener(this);
view.setBuiltInZoomControls(true);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == search) {
Geocoder geo = new Geocoder(getApplicationContext(),
Locale.getDefault());
try {
List<Address> addresses = geo.getFromLocationName(location
.getText().toString(), 5);
if (addresses.size() > 0) {
GeoPoint p = new GeoPoint((int) (addresses.get(0)
.getLatitude() * 1E6), (int) (addresses.get(0)
.getLongitude() * 1E6));
controller.animateTo(p);
controller.setZoom(12);
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> lisOverlays = view.getOverlays();
lisOverlays.clear();
lisOverlays.add(mapOverlay);
} else {
AlertDialog.Builder adb = new AlertDialog.Builder(
MapActivity.this);
adb.setTitle("Google Map");
adb.setMessage("please provide proper place");
adb.setPositiveButton("Close", null);
adb.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
MapOverlay.java
public class MapOverlay extends com.google.android.maps.Overlay
{
Context context;
public boolean draw(Canvas canvas,MapView mapView,boolean shadow,long when)
{
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
GeoPoint p = null;
mapView.getProjection().toPixels(p, screenPts);
Bitmap bitmap=BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
return true;
}
}
When I compile this, I am getting an error in the line: controller.animateTo(p);
In oncreate() instantiate the Mapcontroller as below so that you will not get an error in animateTo method.
controller= view.getController();
also GeoPioint p =null; so replace the MAp overlay class with below
MapOverlay.java
public class MapOverlay extends com.google.android.maps.Overlay
{
GeoPoint p;
Context context;
public MyOverLay(Context context,GeoPoint p) // GeoPoint is a int. (6E)
{
this.p = p;
this.context = context;
}
public boolean draw(Canvas canvas,MapView mapView,boolean shadow,long when)
{
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
Bitmap bitmap=BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
return true;
}
then in your main code pass geopoint like below it will solve your problem....
MapOverlay mapOverlay = new MapOverlay(getApplicationContext(),p);
I can view the map in android mobile now i put one edit text for search area. And create one button for search the place
enter code here
public class MapActivity extends com.google.android.maps.MapActivity implements
OnClickListener {
/** Called when the activity is first created. */
MapView view;
Button search;
EditText location;
MapController controller;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = (MapView) findViewById(R.id.themap);
location = (EditText) findViewById(R.id.editText1);
search = (Button) findViewById(R.id.search);
search.setOnClickListener(this);
view.setBuiltInZoomControls(true);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == search) {
Geocoder geo = new Geocoder(getApplicationContext(),
Locale.getDefault());
try {
List<Address> addresses = geo.getFromLocationName(location
.getText().toString(), 5);
if (addresses.size() > 0) {
GeoPoint p = new GeoPoint((int) (addresses.get(0)
.getLatitude() * 1E6), (int) (addresses.get(0)
.getLongitude() * 1E6));
controller.animateTo(p);
controller.setZoom(12);
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> lisOverlays = view.getOverlays();
lisOverlays.clear();
lisOverlays.add(mapOverlay);
} else {
AlertDialog.Builder adb = new AlertDialog.Builder(
MapActivity.this);
adb.setTitle("Google Map");
adb.setMessage("please provide proper place");
adb.setPositiveButton("Close", null);
adb.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Mapoverlay.java
public class MapOverlay extends com.google.android.maps.Overlay {
Context context;
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
GeoPoint p = null;
mapView.getProjection().toPixels(p, screenPts);
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_launcher);
canvas.drawBitmap(bitmap, screenPts.x, screenPts.y, null);
return true;
}
}
My log cat shows error in controller.animateTo(p);
How can i solve the error in the above line.
How do i provide search option in the map.
Could someone tell me where the mistake is in the above code?
In oncreate() instantiate the Mapcontroller as below so that you will not get an error in animateTo method.
controller= view.getController();