获取 GPS 位置坐标并存储在数组中 [重复]

Posted

技术标签:

【中文标题】获取 GPS 位置坐标并存储在数组中 [重复]【英文标题】:get GPS location co-ordinates and store in an array [duplicate] 【发布时间】:2014-03-27 09:12:32 【问题描述】:

我是 android 新手,我想获取设备当前位置坐标并将其返回。

只要需要位置,就会调用以下函数。

伪代码

    Public arrays GetLocation()
     // GET LATITUDE
     // GET LONGITUDE
     LocationArray = [LATITUDE] [LONGITUDE]
     return LocationArray 
    

如何有效地实现这一点。提前致谢

【问题讨论】:

【参考方案1】:
public class GPSTracker extends Service implements LocationListener 

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

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

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

    public Location 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);

            if (!isGPSEnabled && !isNetworkEnabled) 
                // no network provider is enabled
             else 
                this.canGetLocation = true;
                // 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;
    

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

    /**
     * Function to get latitude
     * */
    public double getLatitude()
        if(location != null)
            latitude = location.getLatitude();
        

        // return latitude
        return latitude;
    

    /**
     * Function to get longitude
     * */
    public double getLongitude()
        if(location != null)
            longitude = location.getLongitude();
        

        // return longitude
        return longitude;
    

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() 
        return this.canGetLocation;
    

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert()
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() 
            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("Cancel", new DialogInterface.OnClickListener() 
            public void onClick(DialogInterface dialog, int which) 
            dialog.cancel();
            
        );

        // Showing Alert Message
        alertDialog.show();
    

    @Override
    public void onLocationChanged(Location location) 
    

    @Override
    public void onProviderDisabled(String provider) 
    

    @Override
    public void onProviderEnabled(String provider) 
    

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

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


为了得到

 gps = new GPSTracker(AndroidGPSTrackingActivity.this);

                // check if GPS enabled     
                if(gps.canGetLocation())

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    // \n is for new line
                    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();    
                

【讨论】:

如何从另一个类调用这个方法?【参考方案2】:
public double[] getLocation()

    double[] latlon = new double[2];
 // Get the location manager
 LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
 Criteria criteria = new Criteria();
 String bestProvider = locationManager.getBestProvider(criteria, false);
 Location location = locationManager.getLastKnownLocation(bestProvider);
 Double lat,lon;
 try 
   lat = location.getLatitude ();
   lon = location.getLongitude ();
   latlon[0] = lat;
   latlon[1] = lon;
   return latlon;
 
 catch (NullPointerException e)
     e.printStackTrace();
   return null;
 

【讨论】:

这会获取设备的当前位置还是最后知道的位置? 它为您提供最后知道的位置,如果您需要新的位置,而不是使用@degvesh patel 给出的上述答案。在应用启动时启动 gps 服务并在需要时获取位置。 数组'latlon'是在没有指定大小的情况下创建的,在java中可以吗? 这意味着可以在数组中存储尽可能多的数据?? 您可以将第一行替换为以下内容。 gps = new GPSTracker(getApplicationContext());如果有帮助,请在此评论中标记。

以上是关于获取 GPS 位置坐标并存储在数组中 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

Android:获取 GPS 坐标并将其发送到服务器的服务

Android获取当前位置的最佳方式[重复]

我对获取当前位置android有问题[重复]

获取手机的GPS位置[重复]

在django中计算附近的gps坐标

如何获取用户指向的 GPS 坐标?