Google Maps V2:使用GPS获取lat long值

时间:2016-04-18 13:53:27

标签: android google-maps gps

我正在创建一个简单的应用程序,它使用GPS获取纬度和经度值,我试图将其传递给谷歌地图以在地图上显示它。 GPS工作正常,但当我使用lat long的值时,它什么都不做。 使用默认标记只能看到地图。

MainActivity.java

public class MainActivity extends AppCompatActivity {

    GoogleMap googleMap;
    GpsTracker gps;
    double lattitude;
    double longitude;
    Button btnMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnMap = (Button) findViewById(R.id.buttonMap);
        gps = new GpsTracker(MainActivity.this);

        if( gps.canGetLocation()) {
            lattitude = gps.getLatitude();
            longitude = gps.getLongitude();
            Toast.makeText(getApplicationContext(),"Location"+lattitude+"/n"+longitude,Toast.LENGTH_SHORT).show();

            } else {
                gps.showAlertDialog();
            }

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


        }






    /**
     * function to load map. If map is not created it will create it for you
     * */
    public void initialiseMap() {




        if (googleMap == null) {
            googleMap = ( (MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

            Toast.makeText(getApplicationContext(),"Location"+lattitude+"/n"+longitude,Toast.LENGTH_SHORT).show();

            MarkerOptions marker = new MarkerOptions().position(new LatLng(gps.getLatitude(),gps.getLongitude())).title("Location");
            googleMap.addMarker(marker);
            CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(lattitude,longitude)).zoom(12).build();
            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            Toast.makeText(getApplicationContext(),"Location"+lattitude+"/n"+longitude,Toast.LENGTH_SHORT).show();

            // check if map is created successfully or not
            if (googleMap == null) {

                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onStop() {
        super.onStop();
        gps.stopUsingGPS();
    }

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

}

显示lat很长。我已经读过我接收的lat long是双格式的,而谷歌地图的标记采用Double作为LatLng的参数。

GPSTracker.java

public class GpsTracker extends Service implements LocationListener {

    private final Context mContext;

    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    boolean canGetLocation = false;

    Location location;
    double latitude;
    double longitude;

    private final long MIN_DISTANCE = 10;
    private final long MIN_TIME = 30;
    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 enabled
            } else {

                this.canGetLocation = true;

                // first get location from network provider
                if (isNetworkEnabled) {
                    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return null;
                    }
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, 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 provider

                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
                        Log.d("GPS provider", "GPS provider");

                        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) {
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            locationManager.removeUpdates(GpsTracker.this);
        }
    }


    // functions to get latitude and longitude

    public double getLatitude()
    {
        if(location != null){
            latitude = location.getLatitude();
        }
        return latitude;
    }


    public double getLongitude()
    {
        if(location != null){
            longitude = location.getLongitude();
        }
        return longitude;
    }


    // function to check whether GPS/WiFi is enabled

    public boolean canGetLocation()
    {

        return this.canGetLocation;
    }


    /* Function to show alert dialog
     * on pressing settings button will launch settings options   */

    public void showAlertDialog()
    {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        alertDialog.setTitle("GPS Settings").setMessage("GPS not Enabled. /n Want to enable it ? ").setCancelable(false);

        alertDialog.setPositiveButton("Settings", new OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {


                // Implicit intent
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);

            }
        });

        alertDialog.setNegativeButton("No", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int arg1) {

                dialog.cancel();

            }
        });

        alertDialog.show();
    }







    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onLocationChanged(Location arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }

}

请告诉我现在还需要添加什么。也许覆盖方法?

0 个答案:

没有答案