I have captured a screenshot of my current location from a mapview and import it to my application frm sd card.I integrated the map using a map view.So wen my application is ran and when the map is loaded some square boxes are coming in my map.after capturing the image.when open the image that crsses are coming.why its happening like that.anyone has an idea.my sample screen shot and code is mentioned below.
![public void onClick(View v) {
getMapImage();
saveMapImage();
}
});
// enable Street view by default
mapView.setStreetView(true);
// enable to show Satellite view
// mapView.setSatellite(true);
// enable to show Traffic on map
// mapView.setTraffic(true);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(16);
}
private Bitmap getMapImage() {
/* Position map for output */
MapController mc = mapView.getController();
// mc.setCenter(SOME_POINT);
mc.setZoom(16);
/* Capture drawing cache as bitmap */
mapView.setDrawingCacheEnabled(true);
Bitmap bmp = Bitmap.createBitmap(mapView.getDrawingCache());
mapView.setDrawingCacheEnabled(false);
return bmp;
}
private void saveMapImage() {
String filename = "foo.png";
File f = new File("/sdcard/", filename);
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp = getMapImage();
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
private class GPSLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
/* Toast.makeText(getBaseContext(),
"Latitude: " + location.getLatitude() +
" Longitude: " + location.getLongitude(),
Toast.LENGTH_SHORT).show();*/
mapController.animateTo(point);
mapController.setZoom(16);
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
String address = ConvertPointToLocation(point);
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
mapView.invalidate();
}
}
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
return address;
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
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);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.red);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null); // 24 is the height of image
return true;
}
}][1]
may you try mapView.setStreetView(false); , I once had the same issue and found out that it was because of setting the street view with true.
Related
I am using OSM maps in my App. I am using 3.0.8 jar file for osmdroid. i have an issue with when i draw custom marker on Map it draw after 2-3 seconds. I goggled it find a solution that use library 3.0.5 osmdroid. when i tried it gives error that android dependencies failed. so please give me way that can i solve this problem.
here is my code for draw a custom marker.
public class Map extends Activity {
GoogleMap gMap;
static int loginCheck = 0;
ConnectionDetector conDec;
ArrayList<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
SharedPreferences prefs;
LatLng latLng;
MarkerOptions markerOptions;
LinearLayout botlay;
EditText desc;
MyItemizedOverlay myItemizedOverlay = null;
MyLocationOverlay myLocationOverlay = null;
ArrayList<OverlayItem> anotherOverlayItemArray, overlayItemArray;
GeoPoint p, loc, currentLocationPixels, t;
GeoPoint myPoint1;
Projection proj;
GPSTracker gps;
double my_Latitude, my_Longitude;
private MapView mapView;
private MapController myMapController;
public int count = 0;
EditText ed1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map1);
ed1 = (EditText) findViewById(R.id.descr);
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
mapView = (MapView) findViewById(R.id.mapViewosm);
mapView.setBuiltInZoomControls(true);
mapView.setMultiTouchControls(true);
myMapController = mapView.getController();
myMapController.setZoom(15);
ScaleBarOverlay myScaleBarOverlay = new ScaleBarOverlay(this);
mapView.getOverlays().add(myScaleBarOverlay);
Drawable marker = getResources().getDrawable(
android.R.drawable.star_big_on);
int markerWidth = marker.getIntrinsicWidth();
int markerHeight = marker.getIntrinsicHeight();
marker.setBounds(0, markerHeight, markerWidth, 0);
ResourceProxy resourceProxy = new DefaultResourceProxyImpl(
getApplicationContext());
myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy);
// add overlay for current location..RAJ
MyCurrentItemizedOverlay myCurrentLocationOverlay = new MyCurrentItemizedOverlay(
marker, resourceProxy);
mapView.getOverlays().add(myCurrentLocationOverlay);
mapView.getOverlays().add(myItemizedOverlay);
// mapView.postInvalidate();
gps = new GPSTracker(Map.this);
// check if GPS enabled
if (gps.canGetLocation()) {
while (gps.getLatitude() == 0.0 || gps.getLongitude() == 0.0) {
gps.canGetLocation();
}
my_Latitude = gps.getLatitude();
my_Longitude = gps.getLongitude();
// \n is for new line
// Toast.makeText(getApplicationContext(),
// "Your Location is - \nLat: " + my_Latitude + "\nLong: " +
// my_Longitude, Toast.LENGTH_LONG).show();
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
// set the current loaction for clicked location..
p = new GeoPoint((int) (my_Latitude * 1E6), (int) (my_Longitude * 1E6));
// add overlay for current location..RAJ
currentLocationPixels = new GeoPoint((int) (my_Latitude * 1E6),
(int) (my_Longitude * 1E6));
// its mine..
Toast.makeText(
getApplicationContext(),
"Your Location is - \nLat: " + my_Latitude + "\nLong: "
+ my_Longitude, Toast.LENGTH_LONG).show();
// ConvertPointToLocation(currentLocationPixels);
myLocationOverlay = new MyLocationOverlay(this, mapView);
// mapView.getOverlays().add(myLocationOverlay);
// myLocationOverlay.enableMyLocation();
// myLocationOverlay.getMyLocation();
mapView.invalidate();
// String coordinates[] = {
// myLocationOverlay.getMyLocation().getLatitudeE6()+"",
// myLocationOverlay.getMyLocation().getLatitudeE6()+"" };
// double lat = (double)
// myLocationOverlay.getMyLocation().getLatitudeE6();
// double lng = (double)
// myLocationOverlay.getMyLocation().getLongitudeE6();
// //
// //
// p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
// mapView.postInvalidate();
// double lat = (double) loc.getLatitudeE6();
// double lng = (double) loc.getLongitudeE6();
// addLocation(my_Latitude, my_Longitude);
// myLocationOverlay.runOnFirstFix(new Runnable() {
// public void run() {
// mapView.getController().animateTo(
// myLocationOverlay.getMyLocation());
// }
// });
// mapView.getOverlays().add(touchOverlay);
}
// private void addLocation(double lat, double lng) {
// // ---Add a location marker---
//
// p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
//
// Drawable marker = getResources().getDrawable(
// android.R.drawable.star_big_on);
// int markerWidth = marker.getIntrinsicWidth();
// int markerHeight = marker.getIntrinsicHeight();
// marker.setBounds(0, markerHeight, markerWidth, 0);
//
// ResourceProxy resourceProxy = new DefaultResourceProxyImpl(
// getApplicationContext());
//
// myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy);
// mapView.getOverlays().add(myItemizedOverlay);
//
// List<Overlay> listOfOverlays = mapView.getOverlays();
// listOfOverlays.clear();
// listOfOverlays.add(myItemizedOverlay);
// mapView.invalidate();
// }
#Override
protected void onResume() {
super.onResume();
myLocationOverlay.enableMyLocation();
myLocationOverlay.enableFollowLocation();
}
#Override
protected void onPause() {
super.onPause();
myLocationOverlay.disableMyLocation();
myLocationOverlay.disableFollowLocation();
}
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> overlayItemList = new ArrayList<OverlayItem>();
public MyItemizedOverlay(Drawable pDefaultMarker,
ResourceProxy pResourceProxy) {
super(pDefaultMarker, pResourceProxy);
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean arg2) {
super.draw(canvas, mapView, arg2);
// ---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
// ---add the marker---
if (count == 1) {
int caller = getIntent().getIntExtra("button", 0);
switch (caller) {
case R.id.btMap:
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_annotation_darkblue);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 50, null);
break;
case R.id.imageButton1:
Bitmap bmp1 = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_annotation_green);
canvas.drawBitmap(bmp1, screenPts.x, screenPts.y - 50, null);
break;
case R.id.imageButton2:
Bitmap bmp2 = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_annotation_bue);
canvas.drawBitmap(bmp2, screenPts.x, screenPts.y - 50, null);
break;
case R.id.imageButton3:
Bitmap bmp3 = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_annotation_light);
canvas.drawBitmap(bmp3, screenPts.x, screenPts.y - 50, null);
break;
case R.id.imageButton4:
Bitmap bmp4 = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_annotation_purple);
canvas.drawBitmap(bmp4, screenPts.x, screenPts.y - 50, null);
break;
case R.id.imageButton5:
Bitmap bmp5 = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_annotation_red);
canvas.drawBitmap(bmp5, screenPts.x, screenPts.y - 50, null);
break;
case R.id.imageButton6:
Bitmap bmp6 = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_annotation_yellow);
canvas.drawBitmap(bmp6, screenPts.x, screenPts.y - 50, null);
break;
}
}
// Bitmap bmp = BitmapFactory.decodeResource(getResources(),
// R.drawable.pin_annotation_green);
// if (count == 1) {
// canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 50, null);
// }
}
public void addItem(GeoPoint p, String title, String snippet) {
OverlayItem newItem = new OverlayItem(title, snippet, p);
overlayItemList.add(newItem);
populate();
}
#Override
public boolean onSnapToItem(int arg0, int arg1, Point arg2,
IMapView arg3) {
return false;
}
#Override
protected OverlayItem createItem(int arg0) {
return overlayItemList.get(arg0);
}
#Override
public int size() {
return overlayItemList.size();
}
#Override
public boolean onLongPress(MotionEvent e, MapView mapView) {
proj = mapView.getProjection();
loc = (GeoPoint) proj.fromPixels((int) e.getX(), (int) e.getY());
ConvertPointToLocation(loc);
return true;
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e, MapView mapView) {
count = 1;
Projection proj = mapView.getProjection();
p = (GeoPoint) proj.fromPixels((int) e.getX(), (int) e.getY());
// ConvertPointToLocation(p);
return true;
}
}
public class MyCurrentItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> overlayItemList = new ArrayList<OverlayItem>();
public MyCurrentItemizedOverlay(Drawable pDefaultMarker,
ResourceProxy pResourceProxy) {
super(pDefaultMarker, pResourceProxy);
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean arg2) {
super.draw(canvas, mapView, arg2);
// ---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(currentLocationPixels, screenPts);
// ---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.pin_annotation_current_location);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 50, null);
}
public void addItem(GeoPoint p, String title, String snippet) {
OverlayItem newItem = new OverlayItem(title, snippet, p);
overlayItemList.add(newItem);
populate();
}
#Override
public boolean onSnapToItem(int arg0, int arg1, Point arg2,
IMapView arg3) {
return false;
}
#Override
protected OverlayItem createItem(int arg0) {
return overlayItemList.get(arg0);
}
#Override
public int size() {
return overlayItemList.size();
}
}
// Method for convert the lat & long into Address
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6, point.getLongitudeE6() / 1E6,
1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0)
.getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT)
.show();
} catch (IOException e) {
e.printStackTrace();
}
return address;
}
public void btHome(View v) {
startActivity(new Intent(Map.this, JamInfo.class));
}
public void btMap(View v) {
}
public void btReport(View v) {
startActivity(new Intent(Map.this, Report.class));
}
public void btSetting(View v) {
startActivity(new Intent(Map.this, Setting.class));
}
}
The first thing I would try to is to stop allocating Bitmaps every draw cycle. Your draw() methods should be as fast as possible and allocating objects in that method will surely slow things down - especially if the garbage collector has to run. You should create all those Bitmaps in the constructor and store them in variables. Also it is recommended that you don't call toPixels() every draw cycle if you can avoid it - call it only when the location changes and store it (and update it if the zoom level changes).
Take a look at the sample application OpenStreetMapViewer for some well-crafted examples of how to use osmdroid.
public class MainActivity extends MapActivity {
LocationManager locmang;
static MapController mcon;
GeoPoint geo;
static GeoPoint point;
static MapView myMap;
MyLocationOverlay comp;
static double lat =0;
static double loni =0;
private LocationManager locManager;
private LocationListener locListener;
List<Overlay>mapOverlays;
Drawable drawable;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myMap= (MapView)findViewById(R.id.mapview);
myMap.displayZoomControls(true);
myMap.setBuiltInZoomControls(true);
mcon=myMap.getController();
myMap.setSatellite(false);
geo = new GeoPoint((int)(lat*1E6),(int)(loni*1E6));
mcon.setCenter(geo);
mcon=myMap.getController();
mcon.animateTo(geo);
comp = new MyLocationOverlay(this, myMap);
myMap.getOverlays().add(comp);
LocationManager lm =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,10, 100, (LocationListener) this);
mapOverlays = myMap.getOverlays();
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = myMap.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
myMap.invalidate();
Intent startService = new Intent(getApplicationContext(),ServiceLocation.class);
startService(startService);
}
public static void updateMap() {
if(ServiceLocation.curLocation!=null){
lat = ServiceLocation.curLocation.getLatitude();
loni = ServiceLocation.curLocation.getLongitude();
if(myMap!=null){
point = new GeoPoint((int)(lat*1e6),(int)(loni*1e6));
mcon.animateTo(point);
myMap.invalidate();
}
}
}
public void createAndShowMyItemizedOverlay(Location newLocation) {
List<Overlay> overlays = myMap.getOverlays();
if (overlays.size() > 0) {
for (Iterator<Overlay> iterator = overlays.iterator(); iterator.hasNext();) {
iterator.next();
iterator.remove();
}
}
GeoPoint geopoint = new GeoPoint(
(int) (newLocation.getLatitude() * 1E6), (int) (newLocation
.getLongitude() * 1E6));
Drawable icon = getResources().getDrawable(R.drawable.image19);
icon.setBounds(0, 0, icon.getIntrinsicWidth(), icon
.getIntrinsicHeight());
myMap.getController().animateTo(geopoint);
myMap.postInvalidate();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public class MapOverlay extends Overlay {
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
if(!shadow){
Point screenPts = new Point();
if(lat==0 && loni==0)
mapView.getProjection().toPixels(geo, screenPts);
else{
mapView.getProjection().toPixels(point, screenPts);
}
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.image19);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
}
return true;
}
}
}`
Allocate your place Latitude and longitude by default and check it may work
this is worked for me :-)
Context ctx;
double LATITUDE = ; //your static latitude
double LONGITUDE = ; //your static longitude
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_landing);
ctx = this;
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder();
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
tvAddress.setText(strReturnedAddress.toString());
}
else {
tvAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tvAddress.setText("Canont get Address!");
}
I have written the code for google maps it is working fine and showing locations also.Now i am trying for reverse geocoding so that i can get the address of the lattitude & longitude coordinates but it is not working.
My code is
public class SelectLocation extends MapActivity {
MapView mapView;
MapController mc;
GeoPoint p;
String coordinates[];
class MapOverlay extends com.google.android.maps.Overlay
{
private GeoPoint p;
public MapOverlay(GeoPoint p){
this.p = p;
}
#Override
public boolean draw(Canvas canvas, MapView mapView,
boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
//---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(
getResources(), R.drawable.pushpin);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
return true;
}
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6,
p.getLongitudeE6() / 1E6, 1);
String add = "";
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();
i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
mapView.getOverlays().clear();
mapView.invalidate();
mapView.getOverlays().add(new MapOverlay(p));
Intent i=new Intent(SelectLocation.this,SetLocat.class);
startActivity(i);
return false;
}
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.selectlocation);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
String coordinates[] = {"1.352566007", "103.78921587"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.animateTo(p);
mc.setZoom(17);
MapOverlay mapOverlay = new MapOverlay(p);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
}
/*protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}*/
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
//
// Write the location name.
//
try {
Geocoder geo = new Geocoder(this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
if (addresses.isEmpty()) {
addres.setText("Waiting for Location");
}
else {
if (addresses.size() > 0) {
addres.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
//Toast.makeText(getApplicationContext(), "Address:- " + addresses.get(0).getFeatureName() + addresses.get(0).getAdminArea() + addresses.get(0).getLocality(), Toast.LENGTH_LONG).show();
}
}
}
catch (Exception e) {
e.printStackTrace(); // getFromLocation() may sometimes fail
}
I have written this code in my project and it works fine.
Compare this with your code. Hope this will help you....
I'm making a Google Map app. I want to get the address of a point when I click on my screen, but when I click on the screen, it doesn't run, nothing happens. How can I fix this?
This my code:
package app.googlemap;
public class GoogleMapActivity extends MapActivity {
MapView mapView;
View zoomView;
MapController mc;
GeoPoint p;
private List<Overlay> mapOverlays;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView=(MapView)findViewById(R.id.simple_map);
LinearLayout zoomLayout=(LinearLayout)findViewById(R.id.zoom);
zoomView = mapView.getZoomControls();
zoomLayout.addView(zoomView, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mapView.displayZoomControls(true);
mapView.setTraffic(true);
String coordinates[]={"21.036074","105.833636"};
double latiTude=Double.parseDouble(coordinates[0]);
double longiTude=Double.parseDouble(coordinates[1]);
p=new GeoPoint((int)(latiTude*1E6), (int)(longiTude*1e6));
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mc=mapView.getController();
mc.animateTo(p);
mc.setZoom(17);
mapView.invalidate();
}
public void draw(GeoPoint g,int a ){
mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(a);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable);
OverlayItem overlayitem = new OverlayItem(p, "", "");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
public class MapOverlay extends com.google.android.maps.Overlay{
private Bitmap bmp;
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);
bmp=BitmapFactory.decodeResource(getResources(), R.drawable.t5);
canvas.drawBitmap(bmp, screenPts.x,screenPts.y-50, null);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6,
p.getLongitudeE6() / 1E6, 1);
String add = "";
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
else
return false;
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
call this method onTap of Map.
/**
* Method to getAddress from particular latitude and longitude.
* */
public static String getAddressFromLocation(double latitude,
double longitude, Context context) {
String locationAddress = "";
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(latitude,
longitude, 1);
if (addresses != null && !addresses.isEmpty()) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder(
"Address:\n");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress
.append(returnedAddress.getAddressLine(i)).append(
"\n");
}
locationAddress = strReturnedAddress.toString();
locationAddress = locationAddress.replace("Address:", "");
}
} catch (IOException e) {
e.printStackTrace();
}
return locationAddress;
}
i have got the following codes but my gps is not getting the current location, showing me the address on touch and no overlay. I got the latitude and longitude as 0.0. Basically only the map is showing up. Help is greatly appreciated. Thank you!
public class Map extends MapActivity{
MapView mapView;
MapController mc;
GeoPoint p;
private LocationManager lm;
private LocationListener locationListener;
Button btn_send;
int lat, lng;
class MapOverlay extends com.google.android.maps.Overlay
{
#Override
public boolean draw(Canvas canvas, MapView mapView,
boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
//---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(
getResources(), R.drawable.pin);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6,
p.getLongitudeE6() / 1E6, 1);
String add = "";
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();
i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
else
return false;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
MapController mc = mapView.getController();
switch (keyCode)
{
case KeyEvent.KEYCODE_3:
mc.zoomIn();
break;
case KeyEvent.KEYCODE_1:
mc.zoomOut();
break;
}
return super.onKeyDown(keyCode, event);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, new GeoUpdateHandler());
Button btnSend = (Button) findViewById(R.id.btn_send);
btnSend.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent new_intent = new Intent("net.learn2develop.SendSMS");
startActivity(new_intent);
}
});
mapView = (MapView) findViewById(R.id.mapView);
LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();
zoomLayout.addView(zoomView,
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mapView.displayZoomControls(true);
mapView.setSatellite(false);
mapView.setStreetView(true);
mc = mapView.getController();
String latitude = Integer.toString(lat);
String longitude = Integer.toString(lng);
String coordinates[] = {latitude, longitude};
double lati = Double.parseDouble(coordinates[0]);
double lngi = Double.parseDouble(coordinates[1]);
System.out.println("lat" + lati + "lng" + lngi );
p = new GeoPoint(
(int) (lati * 1E6),
(int) (lngi * 1E6));
mc.animateTo(p);
mc.setZoom(17);
mapView.invalidate();
//---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
lat = (int) (location.getLatitude() * 1E6);
lng = (int) (location.getLongitude() * 1E6);
System.out.println("lat shld b smth " + lat + "lng smth " +lng);
//GeoPoint point = new GeoPoint(lat, lng);
//mc.animateTo(point); // mapController.setCenter(point);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
If you want to display the current location of the user, you might be better off using the MyLocationOverlay. You can also subclass it and override onLocationChanged, to insert custom code.
Enable it by calling enableMyLocation onResume() and disableMyLocation onPause().
It take 2 to 15 minutes to get a satellite GPS fix. You should move the code for rendering the point to onLocationChanged()