繁体   English   中英

如何在Android应用中获取经度和纬度?

[英]How can I get the longitude and latitude in my android app?

我已经尝试获取特定电话的location了一段时间。 我使用了以下代码,但是当我尝试在模拟器中运行该应用程序时,它没有显示位置,而是崩溃了。

一旦获得了经度和纬度,我将使用它来在Google地图上映射当前位置!

public class Homescreen extends ActionBarActivity implements LocationListener {
    final TextView t = (TextView)findViewById(R.id.textView1);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_homescreen);

        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.homescreen, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        int latitude = (int) (location.getLatitude());
        int longitude = (int) (location.getLongitude());
        t.setText(latitude);

//      Log.i("Geo_Location", "Latitude: " + latitude + ", Longitude: " + longitude);

    }

试试这个课..

public class MainActivity extends Service implements LocationListener {

.....

        // The minimum distance to change Updates in meters
        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

        // The minimum time between updates in milliseconds
        private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

        Location location; // location

        double latitude; // latitude
        double longitude; // longitude

        public Location getLocation() {
            try {
                LocationManager locationManager = (LocationManager).getAplicationContext()
                        .getSystemService(LOCATION_SERVICE);

                // getting GPS status
                 boolean isGPSEnabled = locationManager
                        .isProviderEnabled(LocationManager.GPS_PROVIDER);

                // getting network status
                boolean isNetworkEnabled = locationManager
                        .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                if (!isGPSEnabled && !isNetworkEnabled) {
                    // no network provider is enabled
                } else {
                    // First get location from Network Provider
                    if (isNetworkEnabled) {
                        locationManager.requestLocationUpdates(
                                LocationManager.NETWORK_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("Network", "Network");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                    // if GPS Enabled get lat/long using GPS Services
                    if (isGPSEnabled) {
                        if (location == null) {
                            locationManager.requestLocationUpdates(
                                    LocationManager.GPS_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("GPS Enabled", "GPS Enabled");
                            if (locationManager != null) {
                                location = locationManager
                                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (location != null) {
                                    latitude = location.getLatitude();
                                    longitude = location.getLongitude();
                                }
                            }
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return location;
        }

双值纬度经度返回lon,lat

使用此活动。 希望对您有帮助。

   package yourPackage;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.infologitech.spotways.constants.SpotwaysSettingsKeys.SettingDefaultValue;
import com.infologitech.spotways.constants.SpotwaysSettingsKeys.SettingKey;
import com.infologitech.spotways.custom.TransactionSupport;

public class GetCurrentLocationActivity extends Activity implements
        LocationListener, ConnectionCallbacks, OnConnectionFailedListener {

    private Context context = this;
    private LocationClient mLocationClient;
    private LocationRequest mLocationRequest;
    private Location mLocation;
    private float minAccuracy = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (checkPlayServices()) {
        mLocationClient = new LocationClient(this, this, this);
        mLocationClient.connect();
        //waitForLocation();
}else finish();
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {

    }

    @Override
    public void onConnected(Bundle arg0) {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setInterval(5 * 1000);
        mLocationRequest.setFastestInterval(2 * 1000);
        mLocationRequest.setSmallestDisplacement(5f);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationClient.requestLocationUpdates(mLocationRequest, this);
    }

    @Override
    public void onDisconnected() {

    }

    @Override
    public void onLocationChanged(Location loc) {
        if (loc != null) {
            int latitude = (int) (loc.getLatitude());
        int longitude = (int) (loc.getLongitude());
        Toast.makeText(this,"Lat "+latitude+", Lng "+longitude);
        }
    }

    @Override
    protected void onDestroy() {
        stopUpdate();
        super.onDestroy();
    }

    private void stopUpdate() {
        try {
            mLocationClient.removeLocationUpdates(this);
            mLocationClient.disconnect();
        } catch (Exception e) {
        }
    }

    public  boolean checkPlayServices() {
        final int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
                        resultCode, context, 3434);
                if (dialog != null) {
                    dialog.show();
                    dialog.setOnDismissListener(new OnDismissListener() {
                        public void onDismiss(DialogInterface dialog) {
                            if (ConnectionResult.SERVICE_INVALID == resultCode) {
                            }
                        }
                    });
                    return false;
                }
            }

            return false;
        }
        return true;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM