1

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

}


 }
  • Get your solution from here..http://android-er.blogspot.in/2009/11/mapview-to-center-on-current-location.html – Bhavin Apr 27 '12 at 13:17
  • @userSeven7s it was something like IllegalArgumentException:listener==null. I think it's related to the fact that if you update the current location it may return a null. – boolean.chick Apr 27 '12 at 13:29
  • @Dev Thanks. i will try that now and come back with updates. – boolean.chick Apr 27 '12 at 13:29
  • if you want to show the user location then MyLocationOverlay could be useful.Please have a look at this link http://stackoverflow.com/questions/5593480/modifying-mylocationoverlay-color-in-android – Shabbir Panjesha Apr 27 '12 at 14:10
  • Hey guys. Thanks a lot for your help. I got it working eventually. Mixed up a few tutorials. here's my final code: – boolean.chick Apr 27 '12 at 14:46
  • Stackoverflow won't allow me to post my answer. I'll get back with the answer in around 6 hrs. – boolean.chick Apr 27 '12 at 14:50

2 Answers2

3

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

}
Nayanesh Gupte
  • 2,735
  • 25
  • 37
0

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.

hermann
  • 6,237
  • 11
  • 46
  • 66