4

I need to get the device's current geographical location.

Scenario : if I am in US..:

my device location should be US

Same as in the case, when I am in UK :

my device location should be UK

I need the sample code for finding this geographical location.(location determined by Network Location Provider)

MorningGlory
  • 758
  • 1
  • 11
  • 21
  • 2
    haven't you tried to see related question : http://stackoverflow.com/questions/3145089/what-is-the-simplest-and-most-robust-way-to-get-the-users-current-location-in-a – MKJParekh Nov 28 '11 at 05:18
  • @Frankenstein the question should probably be reworded, but it seems to be how to get the current country code which is a little different than latitude and longitude – skynet Nov 28 '11 at 05:29
  • 1
    @Craigy yeh you are right..but I thought...if manu has looked into the related would have found the answer and another thing..If seen other..would have know how to get Lat/Long then he would have asked how to know country name from lat/long..and then..while asking question to get address line..the related links would have solved that also..cause these are COMMON question and answered beautifully already on SO...so Manu only needed to see other SO question and all his doubts would have been cleared.. – MKJParekh Nov 28 '11 at 05:34

5 Answers5

7

If you want to get the current country code, you want to look into Geocoder which you can use to get an Address which provides a getCountryCode method. Something like this

Geocoder geocoder = new Geocoder(this);
List<Address> addresses = null;

try {
    addresses = geocoder.getFromLocation(
        location.getLatitude(),
        location.getLongitude(), 1);
} catch (IOException e) {
    e.printStackTrace();
}

if (addresses != null && addresses.size() > 0) {
    Address address = addresses.get(0);
    String countryCode = address.getCountryCode();
}

As far as getting the current latitude and longitude, there is plenty of information out there on how to do that

Community
  • 1
  • 1
skynet
  • 9,898
  • 5
  • 43
  • 52
3

There are many tutorial available for this, Here on SO i have read nice answer by Fedor on get current location of the user, try this What is the simplest and most robust way to get the user's current location in Android?. To give answer of your question in code is some lengthy, also in that answer he explain nice way..

Also go through Android developer guide Obtaining User Location for basic information how location manager works in android..

Thanks.

Community
  • 1
  • 1
user370305
  • 108,599
  • 23
  • 164
  • 151
3

Here is the code

Main MapActivity

  public class WhereIam extends MapActivity {
MapController mapController;
MyPositionOverlay positionOverlay;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    MapView myMapView=(MapView)findViewById(R.id.myMapView);

    myMapView.setSatellite(true);


    myMapView.setBuiltInZoomControls(true);
    mapController=myMapView.getController();
    mapController.setZoom(17);
    positionOverlay = new MyPositionOverlay();
    List<Overlay> overlays = myMapView.getOverlays();
    overlays.add(positionOverlay);

         LocationManager locationManager;
        String context=Context.LOCATION_SERVICE;
        locationManager=(LocationManager)getSystemService(context);

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        String provider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(provider);

        final LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
            updateWithNewLocation(location);
            }
            public void onProviderDisabled(String provider){
            updateWithNewLocation(null);
            }
            public void onProviderEnabled(String provider){ }
            public void onStatusChanged(String provider, int status,
            Bundle extras){ }
            };

        updateWithNewLocation(location);
        locationManager.requestLocationUpdates(provider, 2000, 10,
                locationListener);  
}
private void updateWithNewLocation(Location location) {
    if(location!=null)  {
        // Update the map location.
        positionOverlay.setLocation(location);
        Double geoLat = location.getLatitude()*1E6;
        Double geoLng = location.getLongitude()*1E6;
        GeoPoint point = new GeoPoint(geoLat.intValue(),
        geoLng.intValue());
        mapController.animateTo(point);

    }
}   
@Override
protected boolean isRouteDisplayed() {

    return true;
}

Another MyPositionOverlay class

public class MyPositionOverlay extends Overlay {
Location location;
private final int mRadius = 5;
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
  Projection projection = mapView.getProjection();
  if (shadow == false) {
  // Get the current location
  Double latitude = location.getLatitude()*1E6;
  Double longitude = location.getLongitude()*1E6;
  GeoPoint geoPoint;
  geoPoint = new GeoPoint(latitude.intValue(),longitude.intValue());
  // Convert the location to screen pixels
  Point point = new Point();
  projection.toPixels(geoPoint, point);
  RectF oval = new RectF(point.x - mRadius, point.y - mRadius,
  point.x + mRadius, point.y + mRadius);
  // Setup the paint
  Paint paint = new Paint();
  paint.setARGB(250, 255, 0, 0);
  paint.setAntiAlias(true);
  paint.setFakeBoldText(true);
  Paint backPaint = new Paint();
  backPaint.setARGB(175, 50, 50, 50);
  backPaint.setAntiAlias(true);
  RectF backRect = new RectF(point.x + 2 + mRadius,
  point.y - 3*mRadius,
  point.x + 65, point.y + mRadius);
  // Draw the marker
  canvas.drawOval(oval, paint);
  canvas.drawRoundRect(backRect, 5, 5, backPaint);
  canvas.drawText("Here I Am", point.x + 2*mRadius, point.y, paint);
  }
  super.draw(canvas, mapView, shadow);
  }
  @Override
 public boolean onTap(GeoPoint point, MapView mapView) {
 return false;
}
 public Location getLocation() {
  return location;
  }
  public void setLocation(Location location) {
  this.location = location;
  }
}
Sunny
  • 14,522
  • 15
  • 84
  • 129
1

Above solutions is also correct, but some time if location is null then it crash the app or not working properly. The best way to get Latitude and Longitude of android is:

 Geocoder geocoder;
     String bestProvider;
     List<Address> user = null;
     double lat;
     double lng;

    LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);

     Criteria criteria = new Criteria();
     bestProvider = lm.getBestProvider(criteria, false);
     Location location = lm.getLastKnownLocation(bestProvider);

     if (location == null){
         Toast.makeText(activity,"Location Not found",Toast.LENGTH_LONG).show();
      }else{
        geocoder = new Geocoder(activity);
        try {
            user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        lat=(double)user.get(0).getLatitude();
        lng=(double)user.get(0).getLongitude();
        System.out.println(" DDD lat: " +lat+",  longitude: "+lng);

        }catch (Exception e) {
                e.printStackTrace();
        }
    }
Datta Kunde
  • 467
  • 6
  • 14
0
public class LocationHelper {
LocationManager locationManager;

public boolean getLocation(Context context)
{
    if(locationManager==null)
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    List<String> providers = locationManager.getAllProviders();
    Location location;

    for(String provider: providers) {
    try {
        if(locationManager.isProviderEnabled(provider)) {
            //dont use listener, it sometimes does not work             
            location = locationManager.getLastKnownLocation(provider);  
            if(location != null) {
                getDeviceInfo(location, context);
                break;
            }
            }
    } catch (Exception e) {

    }
    }

    return true;
}

private void getDeviceInfo(Location location, Context context) {
     Geocoder geocoder = new Geocoder(context);
     List<Address> addresses = null;

     try {
         addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
     } catch (Exception e) {
         e.printStackTrace();
     }

     if (addresses != null && addresses.size() > 0) {
         Address address = addresses.get(0);
         String countryCode = address.getCountryCode();
     //any other data...
     }
}

}

himanshurb
  • 1,115
  • 1
  • 12
  • 22