我如何获得当前GPS位置编程的机器人?

我如何获得当前GPS位置编程的机器人?

问题描述:

我需要以编程方式让我的当前位置使用GPS。我该怎么办呢?

I need to get my current location using GPS programmatically. How do I do that?

我创建了一个小型应用程序一步一步的说明来获取当前位置的GPS坐标。

I have created a small application with step by step description to get current location's GPS coordinates.

完整的示例源$ C ​​$ c是在 Get您现在的位置坐标,城市名称 - 在Android中

Complete example source code is in Get Current Location coordinates , City name - in Android.

查看它是如何工作的:

  • 所有我们需要做的就是在清单文件中添加此权限:

  • All we need to do is add this permission in the manifest file:

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

  • 和创建一个LocationManager实例是这样的:

  • And create a LocationManager instance like this:

    LocationManager locationManager = (LocationManager)
    getSystemService(Context.LOCATION_SERVICE);
    

  • 检查GPS已启用。

  • Check if GPS is enabled or not.

    ,然后实现LocationListener的,并得到坐标:

    And then implement LocationListener and get coordinates:

    LocationListener locationListener = new MyLocationListener();
    locationManager.requestLocationUpdates(
    LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
    

  • 下面是示例code这样做

  • Here is the sample code to do so

    /*---------- Listener class to get coordinates ------------- */
    private class MyLocationListener implements LocationListener {
    
        @Override
        public void onLocationChanged(Location loc) {
            editLocation.setText("");
            pb.setVisibility(View.INVISIBLE);
            Toast.makeText(
                    getBaseContext(),
                    "Location changed: Lat: " + loc.getLatitude() + " Lng: "
                        + loc.getLongitude(), Toast.LENGTH_SHORT).show();
            String longitude = "Longitude: " + loc.getLongitude();
            Log.v(TAG, longitude);
            String latitude = "Latitude: " + loc.getLatitude();
            Log.v(TAG, latitude);
    
            /*------- To get city name from coordinates -------- */
            String cityName = null;
            Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
            List<Address> addresses;
            try {
                addresses = gcd.getFromLocation(loc.getLatitude(),
                        loc.getLongitude(), 1);
                if (addresses.size() > 0)
                    System.out.println(addresses.get(0).getLocality());
                cityName = addresses.get(0).getLocality();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            String s = longitude + "\n" + latitude + "\n\nMy Current City is: "
                + cityName;
            editLocation.setText(s);
        }
    
        @Override
        public void onProviderDisabled(String provider) {}
    
        @Override
        public void onProviderEnabled(String provider) {}
    
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    }