Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to get current location (latitude and longitude)?

I am using the following code to get the current location namely (latitude and longitude), but I am not getting current location (latitude and longitude).

Anyone knows why?

package com.ram.currentlocation;

import android.app.Activity;    
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

public class Location_Gps extends Activity
{

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

      /* Use the LocationManager class to obtain GPS locations */
      LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

      LocationListener mlocListener = new MyLocationListener();
      mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
    }

    /* Class My Location Listener */
    public class MyLocationListener implements LocationListener
    {

      @Override
      public void onLocationChanged(Location loc)
      {

        loc.getLatitude();
        loc.getLongitude();

        String Text = "My current location is: " +
        "Latitud = " + loc.getLatitude() +
        "Longitud = " + loc.getLongitude();

        Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
      }

      @Override
      public void onProviderDisabled(String provider)
      {
        Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
      }

      @Override
      public void onProviderEnabled(String provider)
      {
        Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
      }

      @Override
      public void onStatusChanged(String provider, int status, Bundle extras)
      {

      }
    }
}

P.S.: I am using the following permissions in the manifest file:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_CORSE_LOCATION"/>
like image 502
Jeeva Avatar asked May 23 '11 10:05

Jeeva


People also ask

How do I find my current latitude and longitude?

Android: Open Google Maps; it will zoom to your approximate location. Press and hold on the screen to drop a pin marker. Click on the dropped pin; latitude and longitude will be displayed below the map.


1 Answers

You have a mistake in your manifest file. Correct one is:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
like image 157
evilone Avatar answered Sep 29 '22 09:09

evilone