getting current location longitude and latitude in android

半世苍凉 提交于 2019-12-04 19:32:28
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.util.Log;
import android.os.Bundle;
import android.widget.Toast;




public class GPSLocationBased extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.locationbased);


    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    LocationListener ll = new Mylocationlistener();





    // ---Get the status of GPS---
    boolean isGPS = lm
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

    // If GPS is not enable then it will be on
    if(!isGPS)
    {
        Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
        intent.putExtra("enabled", true);
         sendBroadcast(intent);


    }

    //<--registers the current activity to be notified periodically by the named provider. Periodically,
    //the supplied LocationListener will be called with the current Location or with status updates.-->
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}

/**
 *Mylocationlistener class will give the current GPS location 
 *with the help of Location Listener interface 
 */
private class Mylocationlistener implements LocationListener {
    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            // ---Get current location latitude, longitude, altitude & speed ---

            Log.d("LOCATION CHANGED", location.getLatitude() + "");
            Log.d("LOCATION CHANGED", location.getLongitude() + "");
            float speed = location.getSpeed();
            double altitude = location.getAltitude();
            Toast.makeText(GPSLocationBased.this,"Latitude = "+
                    location.getLatitude() + "" +"Longitude = "+ location.getLongitude()+"Altitude = "+altitude+"Speed = "+speed,
                    Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!