【问题标题】:button click show current location in google map按钮单击在谷歌地图中显示当前位置
【发布时间】:2018-03-16 08:42:07
【问题描述】:

嗨,我是 android 开发的新手。这是我的场景 Button click show current location in Google Map fragment in my application.

现在我点击按钮显示当前位置 lattitudelongitude

这是我的代码:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="13dp"
        android:text="Start" />

    <TextView
        android:id="@+id/text_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="16dp"/>


</RelativeLayout>

MainActivity.java

package com.example.hello.sampleapp;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_LOCATION = 1;

    Button button;
    TextView textView;
    LocationManager locationManager;
    String lattitude,longitude;

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

        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

        textView = (TextView)findViewById(R.id.text_location);
        button = (Button)findViewById(R.id.button_location);
        button.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            buildAlertMessageNoGps();

        } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            getLocation();
        }
    }


    private void getLocation() {
        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                (MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

        } else {
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            Location location2 = locationManager.getLastKnownLocation(LocationManager. PASSIVE_PROVIDER);

            if (location != null) {
                double latti = location.getLatitude();
                double longi = location.getLongitude();
                lattitude = String.valueOf(latti);
                longitude = String.valueOf(longi);

                textView.setText("Your current location is"+ "\n" + "Lattitude = " + lattitude
                        + "\n" + "Longitude = " + longitude);

            } else  if (location1 != null) {
                double latti = location1.getLatitude();
                double longi = location1.getLongitude();
                lattitude = String.valueOf(latti);
                longitude = String.valueOf(longi);

                textView.setText("Your current location is"+ "\n" + "Lattitude = " + lattitude
                        + "\n" + "Longitude = " + longitude);


            } else  if (location2 != null) {
                double latti = location2.getLatitude();
                double longi = location2.getLongitude();
                lattitude = String.valueOf(latti);
                longitude = String.valueOf(longi);

                textView.setText("Your current location is"+ "\n" + "Lattitude = " + lattitude
                        + "\n" + "Longitude = " + longitude);
                String url = "https://iradivi.com/test/?latitude=" + lattitude +"&longitude=" + longitude;


            }else{

                Toast.makeText(this,"Unble to Trace your location",Toast.LENGTH_SHORT).show();

            }
        }
    }

    protected void buildAlertMessageNoGps() {

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Please Turn ON your GPS Connection")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        dialog.cancel();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    }

}

抱歉这个问题,我不知道该怎么问。

【问题讨论】:

标签: android google-maps


【解决方案1】:

你可以用它来获取经纬度对应的地址

Geocoder geocoder;
List<Address> address;
geocoder = new Geocoder(this, Locale.getDefault());

address = geocoder.getFromLocation(latitude, longitude, 1);

那就用这个

String city = address.get(0).getLocality();
String state = address.get(0).getAdminArea();

【讨论】:

  • 你能告诉我我想在哪里添加这段代码。
【解决方案2】:

使用这个方法

public void setUpCurrentLocation(double latitude, double longitude) {
    if (latitude == 0 || longitude == 0)
        return;
    LatLng latLng = new LatLng(latitude, longitude);
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, AppConstants.MAP_MAX_ZOOM);
    mGoogleMap.animateCamera(cameraUpdate);
}

【讨论】:

    【解决方案3】:

    根据您的评论,您的项目中需要 Google 地图。您可以使用 Android Studio 在您的应用程序中轻松添加 Google 地图活动。 File > New > Google > Google Maps Activity 将添加一个包含 Google Maps 片段的新 Activity。您可以将这个片段添加到您现有的活动中。但首先,您 need to get a Google Developers API key 在您的应用程序中显示 Google 地图。显示用户当前位置的方式有两种:

    第一种方式

    您可以手动获取位置并在地图上用标记显示它

    public void onMapReady(GoogleMap googleMap) {
        LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
        googleMap.addMarker(new MarkerOptions().position(currentLocation)
                .title("Current Location"));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
    }
    

    您可以在 here. 中找到完整的指南和文档

    第二种方式

    您可以在您的应用程序中启用 Google 地图中的当前位置功能。确保您拥有位置权限。

    public void onMapReady(GoogleMap googleMap) {
        googleMap.setMyLocationEnabled(true);
    }
    

    【讨论】:

      【解决方案4】:

      我用于谷歌服务位置的东西。在类下面使用来获取当前位置和其他信息...... 在 gradle 文件中添加以下依赖项。

          compile 'com.google.android.gms:play-services:9.2.0'
      compile 'com.google.android.gms:play-services-location:9.2.0'
      

      然后在使用下面的类之后..

      public class GPSController  implements
          LocationListener,
          GoogleApiClient.ConnectionCallbacks,
          GoogleApiClient.OnConnectionFailedListener
      

      { OnLocationUpdateListener onLocationUpdateListener; public final String TAG = getClass().getSimpleName();

      private FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
      GoogleApiClient googleApiClient;
      LocationRequest mLocationRequest;
      Location mCurrentLocation;
      private static long INTERVAL = 1000 * 10;
      private static long FASTEST_INTERVAL = 1000 * 5;
      FragmentActivity mActivity;
      private boolean isLiveUpdate = false;
      
      
      PendingResult<LocationSettingsResult> result;
      
      
      /**
       * Checking permission and connect with Google Location service
       * @param activity
       */
      public GPSController(FragmentActivity activity) {
      
          this.mActivity = activity;
          if(PermissionManager.checkPermission(mActivity,PermissionManager.ACCESS_LOCATION))
          {
              if (!isGooglePlayServicesAvailable()) {
                  CustomLogHandler.printInfolog("checking googleplayservice : ", "false");
                  ((BaseActivity)mActivity).showAlertDialog(mActivity, mActivity.getString(R.string.app_name), mActivity.getString(R.string.play_service_not_found));
              } else {
                  CustomLogHandler.printInfolog("checking googleplayservice : ", "true");
                  createLocationRequest();
                  initFuseAPI();
      
              }
          }
          else
          {
              PermissionManager.askForPermission(PermissionManager.ACCESS_LOCATION,mActivity);
          }
      
      }
      
      public void connectForLocation()
      {
          createLocationRequest();
          initFuseAPI();
      }
      
      /**
       * Turn on Live update of location on given interval
       * @param value
       * @param INTERVAL
       * @param FASTEST_INTERVAL
       */
      public void turnOnLiveUpdate(boolean value,long INTERVAL,long FASTEST_INTERVAL)
      {
          isLiveUpdate = value;
          this.INTERVAL = INTERVAL;
          this.FASTEST_INTERVAL = FASTEST_INTERVAL;
      }
      
      /**
       * Turn off live update of location
       */
      public void turnOffLiveUpdate()
      {
          isLiveUpdate = false;
      }
      
      /**
       * Disconnect from Google location service
       */
      public void disconnect()
      {
          try {
              Log.d(TAG, "onStop fired ..............");
              googleApiClient.disconnect();
              Log.d(TAG, "isConnected ...............: " +googleApiClient.isConnected());
          }catch (Throwable throwable)
          {
              throwable.printStackTrace();
          }
      }
      
      /**
       * Resume Location update service if stopped
       */
      public void onResumeUpdate()
      {
          try {
              if(googleApiClient != null) {
                  if (googleApiClient.isConnected()) {
                      startLocationUpdates();
                      Log.d(TAG, "Location update resumed .....................");
                  }
              }
          }catch (Throwable throwable)
          {
              throwable.printStackTrace();
          }
      }
      
      
      public void setLocatonUpdateListener(OnLocationUpdateListener onLocationUpdateListener)
      {
          this.onLocationUpdateListener  = onLocationUpdateListener;
      }
      
      /**
       * Create location update request
       */
      protected void createLocationRequest() {
          try {
              mLocationRequest = new LocationRequest();
              mLocationRequest.setInterval(INTERVAL);
              mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
              mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
          }catch (Throwable throwable)
          {
              throwable.printStackTrace();
          }
      }
      
      
      /**
       * Initialize google location service
       */
      void initFuseAPI()
      {
          try
          {
              googleApiClient = new GoogleApiClient.Builder(mActivity)
                      .addApi(LocationServices.API)
                      .addConnectionCallbacks(this)
                      .addOnConnectionFailedListener(this)
                      .build();
              Log.d(TAG, "initFuseAPI fired ..............");
              googleApiClient.connect();
          }catch (Throwable throwable)
          {
              throwable.printStackTrace();
          }
      }
      
      
      /**
       * Check Google location service is available or not
       * @return
       */
      private boolean isGooglePlayServicesAvailable() {
          int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mActivity);
          if (ConnectionResult.SUCCESS == status) {
              return true;
          } else {
              GooglePlayServicesUtil.getErrorDialog(status, mActivity, 0).show();
              return false;
          }
      }
      
      /**
       * called when connected with google location service
       * @param bundle
       */
      @Override
      public void onConnected( Bundle bundle) {
          Log.d(TAG, "onConnected - isConnected ...............: " + googleApiClient.isConnected());
          LocationManager manager = (LocationManager) mActivity.getSystemService(Context.LOCATION_SERVICE );
          boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
          if(statusOfGPS) {
              startLocationUpdates();
          }else
          {
              enableGpsService();
          }
      }
      
      @Override
      public void onConnectionSuspended(int i) {
      
      }
      
      @Override
      public void onConnectionFailed( ConnectionResult connectionResult) {
      
      }
      
      /**
       * Location update received here
       * @param location
       */
      @Override
      public void onLocationChanged(Location location) {
          Log.d(TAG, "Firing onLocationChanged..............................................");
          mCurrentLocation = location;
          SetLocation();
      }
      
      
      void enableGpsService()
      {
          try
          {
              LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                      .addLocationRequest(mLocationRequest);
              builder.setAlwaysShow(true);
              result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
              result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                  @Override
                  public void onResult( LocationSettingsResult locationSettingsResult) {
                      final Status status = locationSettingsResult.getStatus();
                      switch (status.getStatusCode()) {
                          case LocationSettingsStatusCodes.SUCCESS:
                              //already connected to GPS
                              startLocationUpdates();
                              break;
                          case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                              // Location settings are not satisfied. But could be fixed by
                              // showing the user a dialog.
                              try {
                                  status.startResolutionForResult(mActivity, PermissionManager.REQUEST_LOCATION);
                                  startLocationUpdates();
                              } catch (IntentSender.SendIntentException e) {
                                  // Ignore the error.
                              }
                              break;
                          case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                              //redirect user to setting screen, manually user can enble GPS
                              mActivity.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                              break;
                      }
                  }
              });
          }catch (Throwable throwable)
          {
              throwable.printStackTrace();
          }
      }
      
      
      
      
      
      /**
       * Request location update service
       */
      public void startLocationUpdates()
      {
          try {
              //check required even you checked it previously
              if (PermissionManager.checkPermission(mActivity, PermissionManager.ACCESS_LOCATION))
              {
                  fusedLocationProviderApi.requestLocationUpdates(googleApiClient, mLocationRequest, this);
                  Log.d(TAG, "Location update started ..............: ");
              } else {
                  PermissionManager.askForPermission(PermissionManager.ACCESS_LOCATION, mActivity);
              }
          }catch (Throwable throwable)
          {
              throwable.printStackTrace();
          }
      }
      
      /**
       * Stop location update
       */
      public void stopLocationUpdates() {
          try {
              if(googleApiClient != null) {
                  fusedLocationProviderApi.removeLocationUpdates(
                          googleApiClient, this);
                  Log.d(TAG, "Location update stopped .......................");
              }
          }catch (Throwable throwable)
          {
              throwable.printStackTrace();
          }
      }
      
      
      /**
       * set location values received
       */
      private void SetLocation()
      {
          try {
              Log.d(TAG, "UI update initiated .............");
              if (null != mCurrentLocation) {
                  onLocationUpdateListener.onLocationUpdate(mCurrentLocation);
      
                  /**isLiveUpdate = true for Live update **/
      
                  if (!isLiveUpdate) {
                      fusedLocationProviderApi.removeLocationUpdates(googleApiClient,this);
                  }
                  googleApiClient.disconnect();
      
                  //mCurrentLocation.getAccuracy()
                  //mCurrentLocation.getProvider()
      
              } else {
                  Log.d(TAG, "location is null ...............");
              }
          }catch (Throwable throwable)
          {
              throwable.printStackTrace();
          }
      }
      
      public Location getLocation(){
          return mCurrentLocation;
      }
      public static List<Address> getAddress(Double mLat, Double mLang, Context context)
      {
          List<Address> addresses = null;
          try
          {
              Geocoder geocoder = new Geocoder(context, Locale.getDefault());
              addresses = geocoder.getFromLocation(mLat, mLang, 1);
          }catch (Exception e)
          {
              e.printStackTrace();
          }
          return  addresses;
      }
      
      /**
       * For receive location update
       */
      public interface OnLocationUpdateListener {
           void onLocationUpdate(Location mCurrentLocation);
      }
      

      }

      然后将此类初始化为主要活动并获取当前位置的纬度和经度值..

      public class LocationActivity extends AppCompatActivity  implements GPSController.OnLocationUpdateListener{
      
      private static final int REQUEST_LOCATION = 1;
      
      private GPSController gpsController;
      Button button;
      TextView textView;
      LocationManager locationManager;
      String lattitude,longitude;
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.location_layout);
          gpsController = new GPSController(getActivity());
          gpsController.setLocatonUpdateListener(this);
      
      }
      @Override
      public void onLocationUpdate(Location mCurrentLocation) {
          CURRENT_LET = String.valueOf(mCurrentLocation.getLatitude());
          CURRENT_LANG = String.valueOf(mCurrentLocation.getLongitude());
       }
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-01-07
        • 1970-01-01
        • 1970-01-01
        • 2015-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多