Map View Marker in Current Location - android

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);

Related

Android Map zoom to overlay item

I am trying to use the Google maps API on my android app. I have set an overlay item at a particular geopoint co-ordinate. On opening the activity, it uses the default mapview of the google map with the correct location of the overlay item for that geotpoint. My question is, how do I set the view to be zoomed in for that geopoint so one would actually see the location in a better fashion rather than having to manually zoom in by tracing the overlay item. I wish to zoom it so I can see the local area so the user can at least derive useful information from it.
My code is as follows:
/---- HelloItemizedOverlay.java -------/
public class HelloItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Context mContext;
public void addOverlay(OverlayItem overlay)
{
mOverlays.add(overlay);
populate();
}
public HelloItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return mOverlays.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
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;
}
}
/*---- MainActivity.java ---- */
public class MainActivity extends MapActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MapView view = (MapView)findViewById(R.id.themap);
view.setBuiltInZoomControls(true);
final GeoPoint point = new GeoPoint(19240000,-99120000);
OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
GeoPoint point2 = new GeoPoint(35410000, 139460000);
OverlayItem overlayitem2 = new OverlayItem(point2, "Sekai, konichiwa!", "I'm in Japan!");
final MapController control = view.getController();
LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener listener = new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
control.setCenter(point);
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
List<Overlay> mapOverlays = view.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.ic_launcher);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
itemizedoverlay.addOverlay(overlayitem2);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
#noobcoder I have used the same example, and if i get your question right, you can use the following method to zoom to a particular point.
https://developers.google.com/maps/documentation/android/reference/com/google/android/maps/MapController#animateTo(com.google.android.maps.GeoPoint, java.lang.Runnable)
It worked at least for me.
view = (MapView)findViewById(R.id.themap);
mapController = view.getController();
point = new GeoPoint((int) (38.897089* 1E6), (int) (-77.051437* 1E6));
mapControler .animateTo(point );
mapControler .setZoom(17); //Set zoom level as you want..,.
Try this..,.

Getting user current location on google mapview

Hi I have been trying to get and pinpoint the location of the phone (user current location) however I have no luck. I hope somebody can help me with the code.
Just to add some more, I am receiving a "Couldn't get connection factory client" error. Does this have something to do with the ability to return the user location?
If it helps I have been following the tutorial by thenewboston.
Or does this have something to do with my API key? But I can receive the map properly, but cannot pinpoint the user's current location
The main code:
public class Map extends MapActivity implements LocationListener{
MapView map;
long start;
long stop;
MyLocationOverlay compass;
MapController controller;
int x,y;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;
LocationManager lm;
LocationListener ll;
String towers;
int lat = 0;
int longi = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = (MapView)findViewById(R.id.mapview);
map.setBuiltInZoomControls(true);
touch t = new touch();
overlayList = map.getOverlays();
overlayList.add(t);
compass = new MyLocationOverlay(Map.this, map);
overlayList.add(compass);
controller = map.getController();
GeoPoint point = new GeoPoint(832332,4121093);
controller.animateTo(point);
controller.setZoom(8);
d = getResources().getDrawable(R.drawable.pointer);
//placing location
lm =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Location loc = lm.getLastKnownLocation(towers);
if(loc != null){
lat = (int) (loc.getLatitude() *1E6);
longi = (int)(loc.getLongitude()*1E6);
GeoPoint location = new GeoPoint(lat, longi);
OverlayItem overlayitem = new OverlayItem(location , "wassup", "2nd string");
CustomPinPoint custom = new CustomPinPoint(d, Map.this);
custom.insertPinPoint(overlayitem);
overlayList.add(custom);
}else{
Toast.makeText(Map.this, "Location is null", Toast.LENGTH_LONG).show();
lm.requestLocationUpdates(towers, 1500, 1, this);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
compass.disableCompass();
super.onPause();
lm.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
compass.enableCompass();
super.onResume();
lm.requestLocationUpdates(towers, 500, 1, this);
}
I think you can ignore the alertdialog
public class touch extends Overlay {
public boolean onTouchEvent(MotionEvent e, MapView m){
if(e.getAction()== MotionEvent.ACTION_DOWN){
start = e.getEventTime();
x = (int) e.getX();
y = (int) e.getY();
touchedPoint = map.getProjection().fromPixels(x, y);
}
if(e.getAction()== MotionEvent.ACTION_UP){
stop = e.getEventTime();
}
if(stop-start >1200){
AlertDialog alert = new AlertDialog.Builder(Map.this).create();
alert.setTitle("Option");
alert.setMessage("Pick the option");
alert.setCanceledOnTouchOutside(true);
alert.setButton("Place pointer pinpoint",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
OverlayItem overlayitem = new OverlayItem(touchedPoint , "wassup", "2nd string");
CustomPinPoint custom = new CustomPinPoint(d, Map.this);
custom.insertPinPoint(overlayitem);
overlayList.add(custom);
}
});
alert.setButton2("Get address",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6()
/1E6, touchedPoint.getLongitudeE6() /1E6, 1);
if (address.size()>0){
String display = "";
for(int i=0 ; i<address.get(0).getMaxAddressLineIndex(); i++){
display +=address.get(0).getAddressLine(i) + "\n";
}
Toast t = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
t.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
}
}
});
alert.setButton3("Toggle View",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(map.isSatellite()){
map.setSatellite(false);
map.setStreetView(true);
}else{
map.setStreetView(false);
map.setSatellite(true);
}
}
});
alert.show();
return true;
}
return false;
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_map, menu);
return true;
}
#Override
public void onLocationChanged(Location l) {
// TODO Auto-generated method stub
lat = (int)(l.getLatitude()*1E6);
longi = (int)(l.getLongitude()*1E6);
GeoPoint location = new GeoPoint(lat, longi);
OverlayItem overlayitem = new OverlayItem(location , "wassup", "2nd string");
CustomPinPoint custom = new CustomPinPoint(d, Map.this);
custom.insertPinPoint(overlayitem);
overlayList.add(custom);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
The CustomPinPoint code :
public class CustomPinPoint extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> pinpoints = new ArrayList<OverlayItem>();
private Context c;
// tesst google code
public CustomPinPoint(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public CustomPinPoint(Drawable defaultMarker, Context context) {
// TODO Auto-generated constructor stub
this(defaultMarker); //original code
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return pinpoints.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return pinpoints.size();
}
public void insertPinPoint(OverlayItem item){
pinpoints.add(item);
// this.populate(); // original code
// test code
populate();
}
#Override
protected boolean onTap(int index){
OverlayItem item = pinpoints.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(c);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
public void addOverlay(OverlayItem overlay) {
// TODO Auto-generated method stub
pinpoints.add(overlay);
populate();
}
}
XML code:
<com.google.android.maps.MapView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/mapview"
android:enabled="true"
android:clickable="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="0t9rHfGlUPgisa8P9MRAsSxhRXTVCL0XJog7uiA"
/>
Here is the example how to do that easily, try to implement this logic into your project:
public class MyMapActivity extends MapActivity {
private MapView map;
private MapController controller;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mymap);
initMapView();
initMyLocation();
map.invalidate();
}
private void initMapView() {
map = (MapView) findViewById(R.id.map);
controller = map.getController();
map.setSatellite(true);
map.setBuiltInZoomControls(true);
}
private void initMyLocation() {
final MyLocationOverlay overlay = new MyLocationOverlay(this, map);
overlay.enableMyLocation();
//overlay.enableCompass(); // does not work in emulator
overlay.runOnFirstFix(new Runnable() {
public void run() {
// Zoom in to current location
controller.setZoom(15);
controller.animateTo(overlay.getMyLocation());
}});
}
}
Well this is embarrassing, it turns out that my code is correct and the problem was that the device's GPS wasn't turned on. Well I hope my code can help anyone in need. Cheers!

mapview.getoverlays() null pointer exception

Hi all I am trying to implement an overlay onto my google map. However I am receiving a fatal error at runtime and it seems to be some sort of NullPointerException. The app runs properly when I remove the "overlayList = mapView.getOverlays();" and "overlayList.add(t);" lines of code. Any help is greatly appreciated!
Main Activity:
public class CSActivity extends MapActivity implements LocationListener {
MapController mapController;
MapView mapView;
LocationManager locationManager;
MyLocationOverlay myLocationOverlay;
MyLocationOverlay compass;
private Button click_but;
private Button exit_but;
long start;
long stop;
int x,y;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;
String towers;
int lat;
int lng;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main); // bind the layout to the activity
click_but = new Button(this);
click_but = (Button)findViewById(R.id.clickBtn);
exit_but = new Button(this);
exit_but = (Button)findViewById(R.id.exitBtn);
d = getResources().getDrawable(R.drawable.markerblue);
Touchy t = new Touchy();
overlayList = mapView.getOverlays();
overlayList.add(t);
/*compass = new MyLocationOverlay(CSActivity.this, mapView);
overlayList.add(compass);*/
// Configure the Map
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(20); // Zoom 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
Criteria crit = new Criteria();
towers = locationManager.getBestProvider(crit, false);
Location L = locationManager.getLastKnownLocation(towers);
if (L != null){
lat = (int) (L.getLatitude()*1E6);
lng = (int) (L.getLongitude()*1E6);
GeoPoint ourLocation = new GeoPoint(lat, lng);
OverlayItem overlayItem = new OverlayItem(ourLocation, "What's up", "2nd String");
MyItemizedOverlay custom = new MyItemizedOverlay(d, CSActivity.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}else{
Toast.makeText(CSActivity.this, "Couldn't get provider", Toast.LENGTH_SHORT).show();
}
final CSActivity home = this;
exit_but.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setClass(home, homeActivity.class);
startActivity(intent);
}
});
click_but.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
}
});
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
protected void onResume() {
super.onResume();
myLocationOverlay.enableMyLocation();
myLocationOverlay.enableCompass();
locationManager.requestLocationUpdates(towers, 500, 1, this);
}
#Override
protected void onPause() {
super.onResume();
myLocationOverlay.disableMyLocation();
myLocationOverlay.disableCompass();
locationManager.removeUpdates(this);
}
class Touchy extends Overlay {
public boolean onTouchEvent(MotionEvent e, MapView m){
if (e.getAction() == MotionEvent.ACTION_DOWN){
start = e.getEventTime();
x = (int) e.getX();
y = (int) e.getY();
touchedPoint = mapView.getProjection().fromPixels(x, y);
}
if (e.getAction() == MotionEvent.ACTION_UP){
stop = e.getEventTime();
}
if (stop - start > 1000){
//Perform action
AlertDialog alert = new AlertDialog.Builder(CSActivity.this).create();
alert.setTitle("Pick an Option");
alert.setMessage("I said pick!");
alert.setButton("place a pinpoint", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
OverlayItem overlayItem = new OverlayItem(touchedPoint, "What's up", "2nd String");
MyItemizedOverlay custom = new MyItemizedOverlay(d, CSActivity.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}
});
alert.setButton2("get address", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6() / 1E6, touchedPoint.getLongitudeE6() / 1E6, 1);
if (address.size() > 0){
String display = "";
for (int i = 0; i<address.get(0).getMaxAddressLineIndex(); i++){
display += address.get(0).getAddressLine(i) + "\n";
}
Toast t = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
t.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
}
}
});
alert.show();
return true;
}
return false;
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
lat = (int) (location.getLatitude() *1E6);
lng = (int) (location.getLongitude()*1E6);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Itemized Overlay Activity:
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> pinpoints = new ArrayList<OverlayItem>();
private Context c;
public MyItemizedOverlay(Drawable defaultMarker) {
super(boundCenter(defaultMarker));
// TODO Auto-generated constructor stub
}
public MyItemizedOverlay(Drawable m, Context context) {
// TODO Auto-generated constructor stub
this(m);
c = context;
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return pinpoints.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return pinpoints.size();
}
public void insertPinpoint(OverlayItem item) {
pinpoints.add(item);
this.populate();
}
}
Main XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center" >
<com.google.android.maps.MapView
android:id="#+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:apiKey="(key here)"
android:clickable="true"
android:enabled="true" />
<Button
android:id="#+id/clickBtn"
style="#style/ButtonText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#drawable/blue"
android:text="Click" />
<Button
android:id="#+id/exitBtn"
style="#style/ButtonText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#drawable/red"
android:text="Home" />
</RelativeLayout>
mapView is null so get NPE first give refrences from xml file
mapView = (MapView) findViewById(R.id.mapView);
then get overlays
overlayList = mapView.getOverlays();
and
if(null!=overlayList&&overlayList.size()!=0){
overlayList.add(t);
}
Why NullPointerException ?
You are getting Overlay of mapview before define MapView so, you will got null pointer expection..
So first define mapview control after then use it.
mapView = (MapView) findViewById(R.id.mapView);
overlayList = mapView.getOverlays();

Determine user location on osm maps

I am working on an android application that determines user location in osm maps. I am being able to show user location on the map, but if the location change the whole map is reloaded, what’s wrong with that? Also how I can increase the accuracy of the user location? And how can I make a circle that increase and decrease according to the accuracy(as shown in Google one)?
code :
public class OsmDemoActivity extends Activity implements LocationListener,
MapViewConstants
{
private MapView mMapView;
private MapController mapController;
private LocationManager mLocMgr;
private ItemizedOverlay<OverlayItem> mMyLocationOverlay;
private ResourceProxy mResourceProxy;
ArrayList<OverlayItem> items;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mResourceProxy = new DefaultResourceProxyImpl(getApplicationContext());
setContentView(R.layout.main);
//mMapView.setUseDataConnection(false);
initilaizeMap();
//addOverlay();
mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
public void initilaizeMap()
{
mMapView = (MapView) this.findViewById(R.id.mapView);
mMapView.setTileSource(TileSourceFactory.MAPNIK);
//mMapView.setUseDataConnection(false);
mMapView.setBuiltInZoomControls(true);
mMapView.setMultiTouchControls(true);
mapController = this.mMapView.getController();
mapController.setZoom(15);
mapController.setCenter(new GeoPoint(15.610762,32.540345));
/*
final MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this, mMapView,
mResourceProxy);
myLocationOverlay.enableMyLocation();
//myLocationOverlay.disableMyLocation(); // not on by default
myLocationOverlay.disableCompass();
myLocationOverlay.disableFollowLocation();
myLocationOverlay.setDrawAccuracyEnabled(true);
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapController.animateTo(myLocationOverlay
.getMyLocation());
}
});
//ArrayList<OverlayItem> mOsmOverlays;
//mOsmOverlays.add(myLocationOverlay);
*/
}
public void addOverlay()
{
GeoPoint point2 = new GeoPoint(53554070, -2959520); // centre map here
GeoPoint point3 = new GeoPoint(53554070 + 1000, -2959520 + 1000); // icon goes here
GeoPoint point4 = new GeoPoint(15.610844, 32.540045);
GeoPoint point5 = new GeoPoint(15610844 + 40, 32540045 + 40);
GeoPoint point6 = new GeoPoint(15610844 + 50, 32540045 + 50);
GeoPoint point7 = new GeoPoint(15610844 + 10, 32540045 +10);
mapController.setCenter(point4);
items = new ArrayList<OverlayItem>();
// Put overlay icon a little way from map center
items.add(new OverlayItem("Here5", "SampleDescription", point5));
items.add(new OverlayItem("Here6", "SampleDescription", point6));
items.add(new OverlayItem("Here7", "SampleDescription", point7));
/* OnTapListener for the Markers, shows a simple Toast. */
this.mMyLocationOverlay = new ItemizedIconOverlay<OverlayItem>(items,
new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
#Override
public boolean onItemSingleTapUp(final int index,
final OverlayItem item) {
Toast.makeText(
OsmDemoActivity.this,
"Item onItemSingleTapUp '" + item.mTitle, Toast.LENGTH_LONG).show();
return true; // We 'handled' this event.
}
#Override
public boolean onItemLongPress(final int index,
final OverlayItem item) {
Toast.makeText(
OsmDemoActivity.this,
"Item onItemLongPress '" + item.mTitle ,Toast.LENGTH_LONG).show();
return false;
}
}, mResourceProxy);
this.mMapView.getOverlays().add(this.mMyLocationOverlay);
mMapView.invalidate();
}
public void displayLocation(GeoPoint loc)
{
mapController.setCenter(loc);
items = new ArrayList<OverlayItem>();
// Put overlay icon a little way from map center
items.add(new OverlayItem("Here u r", "SampleDescription", loc));
/* OnTapListener for the Markers, shows a simple Toast. */
this.mMyLocationOverlay = new ItemizedIconOverlay<OverlayItem>(items,
new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
#Override
public boolean onItemSingleTapUp(final int index,
final OverlayItem item) {
Toast.makeText(
OsmDemoActivity.this,
"Item onItemSingleTapUp '" + item.mTitle, Toast.LENGTH_LONG).show();
return true; // We 'handled' this event.
}
#Override
public boolean onItemLongPress(final int index,
final OverlayItem item) {
Toast.makeText(
OsmDemoActivity.this,
"Item onItemLongPress '" + item.mTitle ,Toast.LENGTH_LONG).show();
return false;
}
}, mResourceProxy);
mMapView.getOverlays().clear();
this.mMapView.getOverlays().add(this.mMyLocationOverlay);
//mMapView.invalidate();
}
public void onLocationChanged(Location location)
{
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint gpt = new GeoPoint(lat, lng);
//mapController.setCenter(gpt);
//mMapView.invalidate();
displayLocation(gpt);
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
You must use an location change listener
Maybe this can help you
Listener:
package dispatch.driver.osmMaps;
import org.osmdroid.util.GeoPoint;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.widget.Toast;
public class OsmGeoUpdateHandler implements LocationListener
{
private OsmMapsActivity mMapActivity;
public OsmGeoUpdateHandler(OsmMapsActivity aMapActivity)
{
this.mMapActivity = aMapActivity;
}
#Override
public void onLocationChanged(Location location)
{
Toast.makeText(mMapActivity,
"latitude = " + location.getLatitude() * 1e6 + " longitude = " + location.getLongitude() * 1e6,
Toast.LENGTH_SHORT).show();
int latitude = (int) (location.getLatitude() * 1E6);
int longitude = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(latitude, longitude);
mMapActivity.updateCarPosition(point);
}
#Override
public void onProviderDisabled(String provider)
{
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider)
{
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
// TODO Auto-generated method stub
}
}
OsmMapActivity class (how to use listener)
public class OsmMapsActivity extends Activity
{
// final private int MAP_DEFAULT_ZOOM = 14;
final private double MAP_DEFAULT_LATITUDE = 44.445883;
final private double MAP_DEFAULT_LONGITUDE = 26.040963;
private MapView mMapView;
private ResourceProxy mResourceProxy;
private OsmMapsItemizedOverlay mItemizedOverlay;
private MyLocationOverlay mMyLocationOverlay;
private LocationManager locationManager;
private OverlayItem lastPosition = null;
private Order mOrder;
OsmGeoUpdateHandler mUpdateHandler;
private ArrayList<OverlayItem> mItems = new ArrayList<OverlayItem>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Specify the XML layout to use:
setContentView(R.layout.osmmap);
mResourceProxy = new DefaultResourceProxyImpl(getApplicationContext());
mMapView = (MapView) findViewById(R.id.mapview);
// Setup the mapView controller:
mMapView.setBuiltInZoomControls(true);
mMapView.setMultiTouchControls(true);
mMapView.setClickable(true);
mMapView.setUseDataConnection(false);
mMapView.setTileSource(TileSourceFactory.MAPNIK);
mMapView.getController().setZoom(12);
/* location manager */
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mUpdateHandler = new OsmGeoUpdateHandler(this);
Location location = null;
for (String provider : locationManager.getProviders(true))
{
location = locationManager.getLastKnownLocation(provider);
if (location != null)
{
//location.setLatitude(MAP_DEFAULT_LATITUDE);
//location.setLongitude(MAP_DEFAULT_LONGITUDE);
locationManager.requestLocationUpdates(provider, 0, 0, mUpdateHandler);
break;
}
}
//add car position
if (location == null)
{
location = new Location(LocationManager.GPS_PROVIDER);
location.setLatitude(MAP_DEFAULT_LATITUDE);
location.setLongitude(MAP_DEFAULT_LONGITUDE);
updateCarPosition(new GeoPoint(location));
}
} // end onCreate()
public void updateCarPosition(GeoPoint aPoint)
{
if (mItemizedOverlay == null)
{
return;
}
OverlayItem overlayItem;
/* remove last position marker */
removeLastPosition(lastPosition);
overlayItem = new OverlayItem("Center", "Center", (GeoPoint) aPoint);
lastPosition = overlayItem;
mItemizedOverlay.addOverlay(overlayItem);
mMapView.getOverlays().add(mItemizedOverlay);
mMapView.getController().animateTo(aPoint);
}
}

Animate to User Location (Android)

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.

Categories

Resources