如何获得当前的纬度和经度?

Posted

技术标签:

【中文标题】如何获得当前的纬度和经度?【英文标题】:How to get current Latitude and Longitude? 【发布时间】:2019-10-11 19:06:40 【问题描述】:

我创建了一个简单的应用程序,它通过按钮单击“打开”在地图上显示给定的地理位置,现在我试图通过单击按钮“locateme”获取当前的纬度和经度,并在 EditText 中设置它们

我试图在 MainActivity 中创建一个获取当前纬度和经度的函数,但不起作用,我在 MapsActivity 中也尝试过同样的事情,但也不起作用

package com.example.aufgabe2;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.maps.LocationSource;

public class MainActivity extends AppCompatActivity implements     LocationListener 

Button Open, locateme;
EditText latitude, longitude;

Double longitude_current;
Double latitude_current;
LocationManager locationManager;

String[] items_names = "Munich", "Tunis", "Barcelone", "Frankfurt", "Wien", "paris", "london", "dubai";
int[] Images = R.drawable.munich, R.drawable.tunis, R.drawable.barcelona, R.drawable.frank, R.drawable.wien, R.drawable.paris, R.drawable.london, R.drawable.dubai;
String[] items_lati = "48.13743", "36.8065", "41.3851", "50.110924", "48.210033", "48.8566", "51.5074", "25.2048";
String[] items_lng = "11.57549", "10.1815", "2.1734", "8.682127", "16.363449", "2.3522", "0.1278", "55.2708";

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ListView listView = (ListView) findViewById(R.id.listView);
    CustomAdapter customAdapter = new CustomAdapter();
    listView.setAdapter(customAdapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() 
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) 

            latitude.setText(items_lati[position]);
            longitude.setText(items_lng[position]);


        
    );

    if (googleServiceAvailable()) 
        Toast.makeText(this, "PERFEKT ", Toast.LENGTH_LONG).show();
        init();
    


    latitude = (EditText) findViewById(R.id.Latitude);
    longitude = (EditText) findViewById(R.id.Longitude);

    Open = (Button) findViewById(R.id.button);
    locateme = (Button) findViewById(R.id.button_locate_me);


    latitude.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
    longitude.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

    //Open button for displaying the Map
    Open.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
            //condition here

            if (longitude.length() == 0) 
                longitude.setError("your longitude is empty");
             else if (latitude.length() == 0) 
                latitude.setError("your latitude is empty");
             else 
                Toast.makeText(MainActivity.this, "values added successfully ", Toast.LENGTH_SHORT).show();
                init();
            

        
    );

    // here is my locateme button 

    locateme.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) 

            
            Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
            onLocationChanged(location);


        
    );





public void init()
    Open=(Button) findViewById(R.id.button);
    Open.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 

            Intent intent = new Intent(MainActivity.this, MapsActivity.class);
            Double lati =Double.parseDouble(latitude.getText().toString());
            Double longi =Double.parseDouble(longitude.getText().toString());
             intent.putExtra("longitude",longi);
            intent.putExtra("latitude",lati);
            startActivity(intent);


        
    );




  //testing the availability of google service
public boolean googleServiceAvailable()
    GoogleApiAvailability api = GoogleApiAvailability.getInstance();
    int isavailable = api.isGooglePlayServicesAvailable(this);
    if (isavailable == ConnectionResult.SUCCESS)
        return true;
    else if (api.isUserResolvableError(isavailable))

        Dialog dialog = api.getErrorDialog(this,isavailable,0);
        dialog.show();
    else
        Toast.makeText(this,"Cant connect to play services ", Toast.LENGTH_LONG).show();
    
    return false;



@Override
public void onLocationChanged(Location location) 
    Toast.makeText(this,"Cant connect your current location ", Toast.LENGTH_LONG).show();
    latitude_current=location.getLatitude();
    longitude_current=location.getLongitude();
    latitude.setText(String.valueOf(latitude_current));
    longitude.setText(String.valueOf(longitude_current));




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



@Override
public void onProviderEnabled(String provider) 



@Override
public void onProviderDisabled(String provider) 




class CustomAdapter extends BaseAdapter 

    @Override
    public int getCount() 
        return Images.length;
    

    @Override
    public Object getItem(int position) 
        return null;
    

    @Override
    public long getItemId(int position) 
        return 0;
    

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) 

        view = getLayoutInflater().inflate(R.layout.mylist, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.imageView);

        TextView textView_name = (TextView) view.findViewById(R.id.textView_name);


        imageView.setImageResource(Images[i]);
        textView_name.setText(items_names[i]);


        return view;
    


我希望“locateme”按钮获取当前的经度和纬度并在 EditText 中显示它们

【问题讨论】:

嘿,你试过使用 FusedLocationProviderClient 吗?它使获取位置变得非常容易。你可以在这里medium.com/@droidbyme/… 和developers.google.com/android/reference/com/google/android/gms/… 阅读更多相关信息。我也有一个使用谷歌地图的安卓应用程序,你可以看看这里github.com/PabiMoloi/Location/blob/master/app/src/main/java/com/… 【参考方案1】:

清单

   <uses-permission android:name="android.permission.INTERNET" />
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

代码

    GPSTracker gpsTracker = new GPSTracker(this);

    if (gpsTracker.getIsGPSTrackingEnabled())
    
        String stringLatitude = String.valueOf(gpsTracker.latitude);
        textview = (TextView)findViewById(R.id.fieldLatitude);
        textview.setText(stringLatitude);

        String stringLongitude = String.valueOf(gpsTracker.longitude);
        textview = (TextView)findViewById(R.id.fieldLongitude);
        textview.setText(stringLongitude);
     

GPS 追踪器

    import java.io.IOException;
    import java.util.List;
    import java.util.Locale;

    import android.app.AlertDialog;
    import android.app.Service;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.location.Address;
    import android.location.Geocoder;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.provider.Settings;
    import android.util.Log;

    /**
     * Create this Class from tutorial : 
     * http://www.androidhive.info/2012/07/android-gps-location-manager-                tutorial
     * 
     * For Geocoder read this :         http://***.com/questions/472313/android-reverse-geocoding-        getfromlocation
     * 
     */

    public class GPSTracker extends Service implements LocationListener 

// Get Class Name
private static String TAG = GPSTracker.class.getName();

private final Context mContext;

// flag for GPS Status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS Tracking is enabled 
boolean isGPSTrackingEnabled = false;

Location location;
double latitude;
double longitude;

// How many Geocoder should return our GPSTracker
int geocoderMaxResults = 1;

// 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

// Declaring a Location Manager
protected LocationManager locationManager;

// Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
private String provider_info;

public GPSTracker(Context context) 
    this.mContext = context;
    getLocation();


/**
 * Try to get my current location by GPS or Network Provider
 */
public void getLocation() 

    try 
        locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

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

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

        // Try to get location if you GPS Service is enabled
        if (isGPSEnabled) 
            this.isGPSTrackingEnabled = true;

            Log.d(TAG, "Application use GPS Service");

            /*
             * This provider determines location using
             * satellites. Depending on conditions, this provider may take a while to return
             * a location fix.
             */

            provider_info = LocationManager.GPS_PROVIDER;

         else if (isNetworkEnabled)  // Try to get location if you Network Service is enabled
            this.isGPSTrackingEnabled = true;

            Log.d(TAG, "Application use Network State to get GPS coordinates");

            /*
             * This provider determines location based on
             * availability of cell tower and WiFi access points. Results are retrieved
             * by means of a network lookup.
             */
            provider_info = LocationManager.NETWORK_PROVIDER;

         

        // Application can use GPS or Network Provider
        if (!provider_info.isEmpty()) 
            locationManager.requestLocationUpdates(
                provider_info,
                MIN_TIME_BW_UPDATES,
                MIN_DISTANCE_CHANGE_FOR_UPDATES, 
                this
            );

            if (locationManager != null) 
                location = locationManager.getLastKnownLocation(provider_info);
                updateGPSCoordinates();
            
        
    
    catch (Exception e)
    
        //e.printStackTrace();
        Log.e(TAG, "Impossible to connect to LocationManager", e);
    


/**
 * Update GPSTracker latitude and longitude
 */
public void updateGPSCoordinates() 
    if (location != null) 
        latitude = location.getLatitude();
        longitude = location.getLongitude();
    


/**
 * GPSTracker latitude getter and setter
 * @return latitude
 */
public double getLatitude() 
    if (location != null) 
        latitude = location.getLatitude();
    

    return latitude;


/**
 * GPSTracker longitude getter and setter
 * @return
 */
public double getLongitude() 
    if (location != null) 
        longitude = location.getLongitude();
    

    return longitude;


/**
 * GPSTracker isGPSTrackingEnabled getter.
 * Check GPS/wifi is enabled
 */
public boolean getIsGPSTrackingEnabled() 

    return this.isGPSTrackingEnabled;


/**
 * Stop using GPS listener
 * Calling this method will stop using GPS in your app
 */
public void stopUsingGPS() 
    if (locationManager != null) 
        locationManager.removeUpdates(GPSTracker.this);
    


/**
 * Function to show settings alert dialog
 */
public void showSettingsAlert() 
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    //Setting Dialog Title
    alertDialog.setTitle(R.string.GPSAlertDialogTitle);

    //Setting Dialog Message
    alertDialog.setMessage(R.string.GPSAlertDialogMessage);

    //On Pressing Setting button
    alertDialog.setPositiveButton(R.string.action_settings, new DialogInterface.OnClickListener() 

        @Override
        public void onClick(DialogInterface dialog, int which) 
        
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        
    );

    //On pressing cancel button
    alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() 

        @Override
        public void onClick(DialogInterface dialog, int which) 
        
            dialog.cancel();
        
    );

    alertDialog.show();


/**
 * Get list of address by latitude and longitude
 * @return null or List<Address>
 */
public List<Address> getGeocoderAddress(Context context) 
    if (location != null) 

        Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);

        try 
            /**
             * Geocoder.getFromLocation - Returns an array of Addresses 
             * that are known to describe the area immediately surrounding the given latitude and longitude.
             */
            List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);

            return addresses;
         catch (IOException e) 
            //e.printStackTrace();
            Log.e(TAG, "Impossible to connect to Geocoder", e);
        
    

    return null;


/**
 * Try to get AddressLine
 * @return null or addressLine
 */
public String getAddressLine(Context context) 
    List<Address> addresses = getGeocoderAddress(context);

    if (addresses != null && addresses.size() > 0) 
        Address address = addresses.get(0);
        String addressLine = address.getAddressLine(0);

        return addressLine;
     else 
        return null;
    


/**
 * Try to get Locality
 * @return null or locality
 */
public String getLocality(Context context) 
    List<Address> addresses = getGeocoderAddress(context);

    if (addresses != null && addresses.size() > 0) 
        Address address = addresses.get(0);
        String locality = address.getLocality();

        return locality;
    
    else 
        return null;
    


/**
 * Try to get Postal Code
 * @return null or postalCode
 */
public String getPostalCode(Context context) 
    List<Address> addresses = getGeocoderAddress(context);

    if (addresses != null && addresses.size() > 0) 
        Address address = addresses.get(0);
        String postalCode = address.getPostalCode();

        return postalCode;
     else 
        return null;
    


/**
 * Try to get CountryName
 * @return null or postalCode
 */
public String getCountryName(Context context) 
    List<Address> addresses = getGeocoderAddress(context);
    if (addresses != null && addresses.size() > 0) 
        Address address = addresses.get(0);
        String countryName = address.getCountryName();

        return countryName;
     else 
        return null;
    


@Override
public void onLocationChanged(Location location) 


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


@Override
public void onProviderEnabled(String provider) 


@Override
public void onProviderDisabled(String provider) 


@Override
public IBinder onBind(Intent intent) 
    return null;

【讨论】:

感谢您的回答,但我尝试将此代码集成到我的项目中,我得到的纬度和经度始终为 0。 您授予权限了吗?

以上是关于如何获得当前的纬度和经度?的主要内容,如果未能解决你的问题,请参考以下文章

如何获得经纬度地理坐标?

在我的 Reactjs 网络应用程序中集成谷歌地图后,如何获得“纬度”和“经度”?

给定(纬度,经度)点,距离和方位,如何获得新的经纬度

如何在本机反应中获得纬度和经度?

如何从纬度/经度获取附近的位置?

如何获得位于地图上的指针的纬度和经度?