My task is to show the current location of the user as an overlay on the map.
So far I found that the best way to do it, when GPS is enabled, is like this:
public class MyMapActivity extends MapActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
final MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
Log.d("location", "locationchanged: " + location.getLatitude() + ", " + location.getLongitude());
List<Overlay> mapOverlays = mapView.getOverlays();
GeoPoint point = new GeoPoint((int)location.getLatitude(), (int)location.getLongitude());
OverlayItem overlayitem2 = new OverlayItem(point, "title", "hello home!");
Drawable drawable = CouponsMapActivity.this.getResources().getDrawable(R.drawable.androidmarker);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, CouponsMapActivity.this);
itemizedoverlay.addOverlay(overlayitem2);
mapOverlays.add(itemizedoverlay);
// mapView.postInvalidate();
mapView.invalidate();
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
I put a debug point in
Log.d("location", "locationchanged: " + location.getLatitude() + ", " + location.getLongitude());
The location there is correct.
I know that I'm rounding the coordinates and this gives me a somewhat wrong result (it's a quick fix for GeoPoint accepting only int) - but this is not the issue, since the overlay also doesn't appear on the wrong location. It doesn't appear at all.
Edit: Here is HelloItemizedOverlay:
public class HelloItemizedOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public HelloItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
#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;
}
Note: the overlays work when I set the points manually in the main thread like this:
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
final HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
GeoPoint point2 = new GeoPoint(35410000, 139460000);
OverlayItem overlayitem2 = new OverlayItem(point2, "Sekai, konichiwa!", "I'm in Japan!");
itemizedoverlay.addOverlay(overlayitem2);
mapOverlays.add(itemizedoverlay);
So the problem is somewhere else.
I had the same issue some time ago and it was somehow related to the drawable bounds. Try using this method when you're setting the drawable parameter on the constructor of HelloItemizedOverlay.
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(boundCenterBottom(drawable), CouponsMapActivity.this);
private Drawable boundCenterBottom(Drawable marker) {
marker.setBounds((-marker.getIntrinsicWidth()) / 2, -marker.getIntrinsicHeight(),
marker.getIntrinsicWidth() / 2, 0);
return marker;
}
Related
i've created a map, but when on the phone, it doesn't move to my location (taken from gps). why?
Because i need to retrieve the user location, and in case i've found it, animate the map to that point and refresh it (to take the pin from the db). in negative case, i put the center to Milano.
public class Mappa extends MapActivity {
private MapView mapView;
double latitudine=0;
double longitudine=0;
int kilometri=20;
#Override
protected boolean isRouteDisplayed() {
return false;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mappa);
mapView = (MapView) findViewById(R.id.mapview);
MapController mapController = mapView.getController();
final MyLocationOverlay myLocationOverlay;
mapView.setBuiltInZoomControls(true);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.pin_bioscalin);
MyOverlays itemizedoverlay = new MyOverlays(drawable, this);
// milano
latitudine = 45.464164;
longitudine = 9.190321;
GeoPoint mio_point = new GeoPoint((int)(latitudine*1E6), (int)(longitudine*1E6));
mapController.setCenter(mio_point);
mapController.animateTo(mio_point);
mapController.setZoom(11);
// GPS
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
// farmacie
Database_mio db=new Database_mio(this);
db.openDataBase();
Cursor data=db.elenco_negozi_mappa(latitudine,longitudine,kilometri);
data.moveToFirst();
do {
String id_farmacia = data.getString(data
.getColumnIndex("_id"));
String ragione_farmacia = data.getString(data
.getColumnIndex("ragione"));
String indirizzo_farmacia = data.getString(data
.getColumnIndex("ragione"));
int latitude_farmacia = (int) (data.getDouble(data
.getColumnIndex("lat")) * 1E6);
int longitude_farmacia = (int) (data.getDouble(data
.getColumnIndex("lng")) * 1E6);
GeoPoint point = new GeoPoint(latitude_farmacia,longitude_farmacia);
OverlayItem overlayitem = new OverlayItem(point,ragione_farmacia,indirizzo_farmacia);
itemizedoverlay.addOverlay(overlayitem);
} while (data.moveToNext());
mapOverlays.add(itemizedoverlay);
// disclamer
ImageView img = (ImageView) findViewById(R.id.image_mia_map);
img.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent disclamer = new Intent(getParent(), Disclamer.class);
disclamer.putExtra("da_dove", "Mappa");
TabGroupActivity parentActivity = (TabGroupActivity)getParent();
parentActivity.startChildActivity("Disclamer", disclamer);
}
});
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc){
loc.getLatitude();
loc.getLongitude();
String Text = "La mia posizione: "+"Latitudine = "+loc.getLatitude()+"Longitudine = "+loc.getLongitude();
GeoPoint mio_point = new GeoPoint((int)(loc.getLatitude()*1E6), (int)(loc.getLongitude()*1E6));
mapView.getController().setCenter(mio_point);
mapView.getController().animateTo(mio_point);
Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider){
Toast.makeText( getApplicationContext(),"Gps disabilitato",Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider){
Toast.makeText( getApplicationContext(),"Gps abilitato",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
}
}
thanks to all.
I'm using this codes to view the current location of the user. But I also need to put a marker on it. I already saw a few tutorial regarding this but I still don't get it.
Here's my Activity
public class MapViewActivity extends MapActivity {
#Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
setContentView(R.layout.mapview);
//------------Start Displaying Map View--------------//
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint test= new GeoPoint(
lat,lng);
MapView mapview = (MapView) findViewById(R.id.mvmap);
MapController mapcontrol = mapview.getController();
mapcontrol.animateTo(test);
mapcontrol.setZoom(10);
mapview.setStreetView(true);
mapview.setSatellite(true);
mapview.setBuiltInZoomControls(true);
}
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
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
use this class for ItemizedOverlay.
public class CustomItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
public CustomItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public CustomItemizedOverlay(Drawable defaultMarker, Context context) {
this(defaultMarker);
this.context = context;
}
#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);
Log.e(" on tap item value ", "" + mapOverlays.get(index) + " Index "
+ index);
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
this.populate();
}
public void removeOverlay() {
mapOverlays.clear();
// this.populate();
}
}
In your MapViewActivity ,declare ,
CustomItemizedOverlay itemizedOverlay;
List<Overlay> mapOverlays;
mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
itemizedOverlay = new CustomItemizedOverlay(drawable, this);
OverlayItem overlayitem = new OverlayItem(test," "," ");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
First of all, I apologize for the English, I don't know how to write english very well.
I am creating an application that should show the user's location on the map. As per the documentation, I've created my listener and added an overlay with my location.
In all other Android devices my application works fine, including the Motorola Defy (MB525), but in (MB526) apparently it does not receive a differente coordinate.
public class TesteMapActivity extends MapActivity {
private LocationManager locationManager;
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
MapView mapView = (MapView) findViewById(R.id.mapview);
MapController mapController = mapView.getController();
mapView.setSatellite(false);
mapView.setStreetView(false);
mapView.setBuiltInZoomControls(true);
mapController.setZoom(16);
}
private LocationListener locationListener = new LocationListener() {
int i = 0;
#Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
#Override
public void onProviderEnabled(String provider) { }
#Override
public void onProviderDisabled(String provider) { }
#Override
public void onLocationChanged(Location location) {
i++;
animeTo(location, i);
}
};
public void animeTo(Location location, int i) {
TextView txtCoordenadas = (TextView) findViewById(R.id.txtCoordenadas);
txtCoordenadas.setText(i + " " + location.getLatitude() + ", " + location.getLongitude());
MapView mapView = (MapView) findViewById(R.id.mapview);
MapController mapController = mapView.getController();
if (mapView.getOverlays().size() >= 1) {
mapView.getOverlays().removeAll(mapView.getOverlays());
}
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = getResources().getDrawable(R.drawable.ponto);
OtemizedOverlay itemizedoverlay = new OtemizedOverlay(drawable, TesteMapActivity.this);
Double lat = location.getLatitude() * 1E6;
Double log = location.getLongitude() * 1E6;
GeoPoint point = new GeoPoint(lat.intValue(), log.intValue());
OverlayItem overlayitem = new OverlayItem(point, "Minha Localização", "Latitude: " + lat + " Longitude: " + log);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
mapController.animateTo(point);
}
}
public class OtemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public OtemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
public OtemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
#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;
}
}
Can anyone help me?
Thank you.
Defy+ Hardware/Default Configuration has a bug.
You can have a solution for your device on this link.
If you are developing an app for this device only, the best way to think is forget it. Defy+ is a mess, and useless piece of junk.
I suggest not kill the Listener directly, It will mess with the location, and will make other devices work bad. So it's better have 1% of problems, than 100% working bad.
First of all, David and Kaneto, Paulo I thanks you that help me a lot.
I found a solution, if you have a same problem use this to resolve.
change your method animeTo to a AsyncTask().
public void animeTo(Location location) {
new AsyncTask() {
protected Object doInBackground(Object... params) {
//your code
return null;
}
}.execute(new Void[0]);
}
This works fine on my tests.
Again I apologize for the English, I don't know how to write english very well.
I am working on a project that has one feature to display (animate to) current user location and one hard coded location(given latitude and longitude). So far I have the hardcoded location working but I can't figure out how to get the user location. I've tried the location listener but my application keeps crashing after I run it. Does anybody have any advice on it? Much appreciated. Here's the code:
public class LocationsActivity extends MapActivity implements LocationListener {
MapView mapView;
MapController mc;
GeoPoint p;
LocationListener locListener;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
mapView = (MapView)findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
String coordinates[] = {"52.67596","-8.64910"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint((int)(lat*1E6),(int)(lng*1E6));
OverlayItem overlayitem = new OverlayItem(p, "Limerick Institute of
Technology", "Moylish");
mc.animateTo(p);
mc.setZoom(17);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.pushpin);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable,
this);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
mapView.invalidate();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
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
}
}
if you are using MapActivity then you can use following code:
/**
* Set current location using MyLocationOverlay
*/
public void setCurrentLocation() {
myLocationOverlay.runOnFirstFix(new Runnable() {
#Override
public void run() {
if (null != myLocationOverlay.getMyLocation()) {
/**
* Put extra sleep to avoid concurrentModicationException
*/
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
map.getController().animateTo(
myLocationOverlay.getMyLocation());
map.getOverlays().add(myLocationOverlay);
}
}
});
}
If you are using MapFragment then inside activity:
1. mapFragment.getMap().setMyLocationEnabled(true);
then call
private void moveMapToMyLocation() {
LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
Location loc = locMan.getLastKnownLocation(locMan.getBestProvider(crit,
false));
CameraPosition camPos = new CameraPosition.Builder()
.target(new LatLng(loc.getLatitude(), loc.getLongitude()))
.zoom(12.8f)
.build();
CameraUpdate camUpdate = CameraUpdateFactory.newCameraPosition(camPos);
mapFragment.getMap().moveCamera(camUpdate);
}
I am building an app in ICS with a mapview within a Fragment.
After initializing the mapView in the activity class I pass it to the mapFragment which is the fragment that is used to display the map.
This is some of the code in my activity class :
mapView = new MapView(this, getString(R.string.mapsAPI));
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(this.myLocationOverlay);
mapView.postInvalidate();
public void calculateLocation() {
setLocationManager();
setLocation();
setGeoPoint(location);
}
public void setGeoPoint(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
geoPoint = new GeoPoint((int)( latitude * 1E6), (int)( longitude * 1E6 ));
}
public void setLocation() {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
public void setLocationManager() {
locationManager = ((LocationManager)getSystemService(Context.LOCATION_SERVICE));
}
and this is the code in my mapFragment class :
public class MapFragment extends Fragment
{
MapView gMap = null;
GeoPoint gPoint = null;
Location location = null;
public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) {
gMap = ((NFCDemoActivity)getActivity()).getMapView();
return this.gMap;
}
public void onActivityCreated(Bundle paramBundle) {
super.onActivityCreated(paramBundle);
((NFCDemoActivity)getActivity()).calculateLocation();
gPoint = ((NFCDemoActivity)getActivity()).getGeoPoint();
gMap.setClickable(true);
gMap.setBuiltInZoomControls(true);
gMap.getController().setZoom(18);
gMap.getController().setCenter(gPoint);
}
public void onDestroy() {
super.onDestroy();
}
}
This will give you the user's current location.
i have taken one radio button as GPS.
now i want to show my current location when i clicked on that radio button..
how to achieve it?
please give me some sample code for the same...
Thanks in Advance---
use this code in radiobutton onclick event.....
Location location;
protected LocationManager locationManager;
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
Toast.makeText(LbsGeocodingActivity.this, message,
Toast.LENGTH_LONG).show();
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(
R.drawable.new3pin);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(
drawable, LbsGeocodingActivity.this);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
} else {
Toast.makeText(LbsGeocodingActivity.this, "No Location Found",
Toast.LENGTH_LONG).show();
}
second HelloItemizedOverlay.java class..
public class HelloItemizedOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Context mContext;
#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();
}
public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
}
i have pasted the sample code Here
Crete one interface to notify when location is obtained.. put code in OnClick event(or onSelected) of your Radio button
LocProvider locProvider = LocProvider.getInstance();
locProvider.init(this);
locProvider.initializeLocationSearch();
locProvider.setLocationCallbackListener(<crete ownlistener and assign here>);