如何获取我的代码以提供我当前的位置?

Posted

技术标签:

【中文标题】如何获取我的代码以提供我当前的位置?【英文标题】:How do i get my code to give my current location? 【发布时间】:2019-12-23 04:30:00 【问题描述】:

我试图让我的代码放大并在我打开地图活动后给我我的确切位置,但相反,我得到了一张显示非洲地图的地图。

我写了一些从网上教程中得到的代码,但没有一个能成功地给出我想要的。

我尝试使用这个link

也试过用这个YouTube video

MapActivity.java:

package com.kiki.doctorlocation;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;


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


public class MapActivity extends FragmentActivity implements 
OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, LocationListener 

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private GoogleMap mMap;;

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



@Override
public void onMapReady(GoogleMap googleMap) 
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.getUiSettings().setZoomGesturesEnabled(true);
    mMap.getUiSettings().setCompassEnabled(true);

    //Initialize Google Play Services
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) 
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        
     else 
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    


private void buildGoogleApiClient() 
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();


@Override
public void onConnected(@Nullable Bundle bundle) 
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) 
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
                mLocationRequest, this);
    


@Override
public void onConnectionSuspended(int i) 



@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) 



@Override
public void onLocationChanged(Location location) 
    mLastLocation = location;
    if (mCurrLocationMarker != null) 
        mCurrLocationMarker.remove();
    
    //Showing Current Location Marker on Map
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    LocationManager locationManager = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);
    String provider = locationManager.getBestProvider(new Criteria(), true);
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) 
        return;
    
    Location locations = locationManager.getLastKnownLocation(provider);
    List<String> providerList = locationManager.getAllProviders();
    if (null != locations && null != providerList && providerList.size() > 0) 
        double longitude = locations.getLongitude();
        double latitude = locations.getLatitude();
        Geocoder geocoder = new Geocoder(getApplicationContext(),
                Locale.getDefault());
        try 
            List<Address> listAddresses = geocoder.getFromLocation(latitude,
                    longitude, 1);
            if (null != listAddresses && listAddresses.size() > 0) 
                String state = listAddresses.get(0).getAdminArea();
                String country = listAddresses.get(0).getCountryName();
                String subLocality = listAddresses.get(0).getSubLocality();
                markerOptions.title("" + latLng + "," + subLocality + "," + state
                        + "," + country);
            
         catch (IOException e) 
            e.printStackTrace();
        
    
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
    mCurrLocationMarker = mMap.addMarker(markerOptions);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
    if (mGoogleApiClient != null) 
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
                this);
    

public boolean checkLocationPermission() 
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) 

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) 
            ActivityCompat.requestPermissions(this,
                    new String[]Manifest.permission.ACCESS_FINE_LOCATION,
                    MY_PERMISSIONS_REQUEST_LOCATION);
         else 
            ActivityCompat.requestPermissions(this,
                    new String[]Manifest.permission.ACCESS_FINE_LOCATION,
                    MY_PERMISSIONS_REQUEST_LOCATION);
        
        return false;
     else 
        return true;
    


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) 
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) 
        case MY_PERMISSIONS_REQUEST_LOCATION: 
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) 
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) 
                    if (mGoogleApiClient == null) 
                        buildGoogleApiClient();
                    
                    mMap.setMyLocationEnabled(true);
                
             else 
                Toast.makeText(this, "permission denied",
                        Toast.LENGTH_LONG).show();
            
            return;
        
    


我希望当我运行我的代码时,我的地图会放大并给出我当前的确切位置。代码没有错误,这就是我需要帮助的原因。

【问题讨论】:

【参考方案1】:

我会尽力提供帮助。我假设你的 gradle 中有所有 必要的库。检查你是否有

implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.google.android.libraries.places:places:1.0.0'

同时确认您是否拥有以下权限(除了您可能拥有的其他权限之外)

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

在较新的 Android 版本上,您可能需要在运行时请求权限。您可以在活动中添加存根。

  public static boolean hasPermissions(Context context, String... permissions) 
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) 
            for (String permission : permissions) 
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) 
                    return false;
                
            
        
        return true;
    

//调用上述函数

    String[] PERMISSIONS = Manifest.permission.INTERNET,Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA ;
    if (!hasPermissions(this, PERMISSIONS)) 
        ActivityCompat.requestPermissions(this, PERMISSIONS, 1);
    

您的活动可能如下所示。

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.RelativeLayout;
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.common.api.Status;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.TypeFilter;
import com.google.android.libraries.places.widget.AutocompleteSupportFragment;
import com.google.android.libraries.places.widget.listener.PlaceSelectionListener;


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




public class SetPickUpLocation extends FragmentActivity implements OnMapReadyCallback 

    SupportMapFragment mapFragment;
    private GoogleMap mMap;
    private GoogleMap.OnCameraIdleListener onCameraIdleListener;
    private TextView resutText;
    private FusedLocationProviderClient fusedLocationProviderClient;
    private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 5445;
    private Location currentLocation;
    public static String latitude = null, longitude = null, location = null, area = null;
    private boolean firstTimeFlag = true;
    Button setLocation;
    View mapView;
    AutocompleteSupportFragment autocompleteFragment;
    String TAG = "Google_Places";
    int AUTOCOMPLETE_REQUEST_CODE = 1;

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


        resutText = (TextView) findViewById(R.id.dragg_result);
        setLocation = (Button) findViewById(R.id.setLocation);

        autocompleteFragment = (AutocompleteSupportFragment)
                getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);


        mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        mapView = mapFragment.getView();
        Toast.makeText(SetPickUpLocation.this, ConstantValues.DRAG_MAP_MARKER, Toast.LENGTH_SHORT).show();
        configureCameraIdle();

        Places.initialize(getApplicationContext(), ConstantValues.GOOGLE_API_KEY);

        setLocation.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                if (latitude != null && longitude != null) 
                  //you can put your logic here
                else
                  //you can put your logic here
                
            
        );


        autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME , Place.Field.LAT_LNG));
        //autocompleteFragment.setTypeFilter(TypeFilter.REGIONS);
        autocompleteFragment.setCountry("KE");

        autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() 
            @Override
            public void onPlaceSelected(Place place) 
                // TODO: Get info about the selected place.
                //Log.d(TAG , place.getName()  + ", " + place.getId());
                if(mMap != null)
                    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(place.getLatLng(), 16);
                    mMap.animateCamera(cameraUpdate);
                    autocompleteFragment.setText("");
                
               //
                //mMap.mo
            

            @Override
            public void onError(Status status) 
                // TODO: Handle the error.
                Log.d(TAG , "An error occurred: " + status);
            
        );




    






    @Override
    protected void onStop() 
        super.onStop();
        if (fusedLocationProviderClient != null)
            fusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
    

    @Override
    protected void onResume() 
        super.onResume();
        if (isGooglePlayServicesAvailable()) 
            fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
            startCurrentLocationUpdates();
        
    

    @Override
    protected void onDestroy() 
        super.onDestroy();
        fusedLocationProviderClient = null;
        mMap = null;
    

    private void configureCameraIdle() 
        onCameraIdleListener = new GoogleMap.OnCameraIdleListener() 
            @Override
            public void onCameraIdle() 

                LatLng latLng = mMap.getCameraPosition().target;
                Geocoder geocoder = new Geocoder(SetPickUpLocation.this);

                try 
                    List<Address> addressList = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
                    if (addressList != null && addressList.size() > 0) 
                        String locality = addressList.get(0).getAddressLine(0);
                        String country = addressList.get(0).getCountryName();

                        latitude = Double.toString(latLng.latitude);
                        longitude = Double.toString(latLng.longitude);

                        if (!locality.isEmpty() && !country.isEmpty()) 
                            resutText.setText(locality);
                            location = locality;
                            try
                                String city = addressList.get(0).getAdminArea();
                                if(!city.isEmpty())
                                    area = city;
                                
                            catch (Exception e)

                            

                        


                    

                 catch (IOException e) 
                    e.printStackTrace();
                

            
        ;
    


    @Override
    public void onMapReady(GoogleMap googleMap) 
        mMap = googleMap;
        mMap.setOnCameraIdleListener(onCameraIdleListener);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
        

        mMap.setMyLocationEnabled(true);
        if (mapView != null &&
                mapView.findViewById(Integer.parseInt("1")) != null) 
            // Get the button view
            View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
            // and next place it, on bottom right (as Google Maps app)
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
                    locationButton.getLayoutParams();
            // position on right bottom
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
            layoutParams.setMargins(0, 0, 100, 330);
        
    

    private final LocationCallback mLocationCallback = new LocationCallback() 

        @Override
        public void onLocationResult(LocationResult locationResult) 
            super.onLocationResult(locationResult);
            if (locationResult.getLastLocation() == null)
                return;
            currentLocation = locationResult.getLastLocation();
            if (firstTimeFlag && mMap != null) 
                animateCamera(currentLocation);
                firstTimeFlag = false;
            
            //showMarker(currentLocation);
        
    ;

    private void startCurrentLocationUpdates() 
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(3000);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
            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) 
                ActivityCompat.requestPermissions(SetPickUpLocation.this,
                        new String[]Manifest.permission.ACCESS_FINE_LOCATION,
                        MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
                return;
            
        
        fusedLocationProviderClient.requestLocationUpdates(locationRequest, mLocationCallback, Looper.myLooper());
    

    private boolean isGooglePlayServicesAvailable() 
        GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
        int status = googleApiAvailability.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status)
            return true;
        else 
            if (googleApiAvailability.isUserResolvableError(status))
                Toast.makeText(this, "Please Install google play services to use this application", Toast.LENGTH_LONG).show();
        
        return false;
    

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) 
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) 
            if (grantResults[0] == PackageManager.PERMISSION_DENIED)
                Toast.makeText(this, "Permission denied by uses", Toast.LENGTH_SHORT).show();
            else if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
                startCurrentLocationUpdates();
        
    

    private void animateCamera(@NonNull Location location) 
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(getCameraPositionWithBearing(latLng)));
    

    @NonNull
    private CameraPosition getCameraPositionWithBearing(LatLng latLng) 
        return new CameraPosition.Builder().target(latLng).zoom(16).build();
    



XML 布局(您可以使用自己的 ViewGroups)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_
    android:layout_
    tools:context=".orders.SetPickUpLocation">


    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_
        android:layout_ />

    <android.support.v7.widget.CardView
        android:id="@+id/idCardView"
        android:layout_
        android:layout_
        android:layout_alignParentTop="true"
        app:cardCornerRadius="4dp">

        <fragment
            android:id="@+id/autocomplete_fragment"
            android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
            android:layout_
            android:layout_ />
    </android.support.v7.widget.CardView>

    <ImageView
        android:layout_
        android:layout_
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@drawable/ic_google_map_marker"
        android:text="TextView" />


    <LinearLayout
        android:layout_
        android:layout_
        android:layout_alignParentBottom="true"
        android:background="#ffffff"
        android:orientation="vertical"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin">

        <LinearLayout
            android:layout_
            android:layout_
            android:orientation="horizontal"
            android:paddingTop="@dimen/activity_horizontal_margin"
            android:paddingBottom="@dimen/activity_horizontal_margin"
            android:weightSum="3">

            <ImageView
                android:layout_
                android:layout_
                android:layout_weight="0.2"
                android:gravity="center_vertical"
                android:src="@drawable/ic_google_map_marker" />

            <TextView
                android:id="@+id/dragg_result"
                android:layout_
                android:layout_
                android:layout_gravity="center_vertical"
                android:layout_weight="2.8"
                android:fontFamily="@font/museo"
                android:gravity="left"
                android:paddingLeft="3dp"
                android:text="Select this location"
                android:textColor="#000"
                android:textSize="18dp" />
        </LinearLayout>


        <Button
            android:id="@+id/setLocation"
            style="?android:attr/borderlessButtonStyle"
            android:layout_
            android:layout_
            android:layout_marginBottom="@dimen/activity_horizontal_margin"

            android:fontFamily="@font/museo"
            android:text="Select this location"
            android:textColor="#ffffff"
            android:textSize="18sp"
            android:textStyle="bold" />
    </LinearLayout>


</RelativeLayout>

我希望这会有所帮助,并且还可以使用您自己的图标/可绘制对象,因为我没有在此处包含它们。

【讨论】:

【参考方案2】:

所以之前的答案对我不起作用,所以我决定另辟蹊径,这是对我有用的代码

MapActivity.java

import android.app.Dialog;
import android.content.pm.PackageManager;
import android.location.Address;
imsport android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

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


public class MapActivity extends AppCompatActivity implements OnMapReadyCallback 

    private GoogleMap mMap;

    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);

        if (GSA()) 
            Toast.makeText(this, "Services perfect", Toast.LENGTH_SHORT).show();
            setContentView(R.layout.activity_map);
            initMap();
         else 

        

    

    private void initMap() 
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync((OnMapReadyCallback) this);
    

    public boolean GSA() 
        GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
        int isAvailable = googleApiAvailability.isGooglePlayServicesAvailable(this);
        if (isAvailable == ConnectionResult.SUCCESS)
            return true;
        else if (googleApiAvailability.isUserResolvableError(isAvailable)) 
            Dialog dialog = googleApiAvailability.getErrorDialog(this, isAvailable, 0);
            dialog.show();
         else 
            Toast.makeText(this, "Can't connect to Google services", Toast.LENGTH_SHORT).show();
        
        return false;
    

    @Override
    public void onMapReady(GoogleMap googleMap) 
        mMap = googleMap;
        // gotoLocationzoom(-1.276680, 36.904785, 15);

        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
            //    Activity#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 Activity#requestPermissions for more details.
            return;
        
        mMap.setMyLocationEnabled(true);

//        LatLng sydney = new LatLng(-1.276680, 36.904785);
//        googleMap.addMarker(new MarkerOptions().position(sydney)
//                .title("Marker in white hse"));
//        googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    
    private void gotoLocationzoom (double lat, double lng, float zoom)
        LatLng latLng = new LatLng(lat,lng);
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng,zoom);
        mMap.animateCamera(cameraUpdate);
    
    public void search(View view) throws IOException 
        EditText et = (EditText) findViewById(R.id.editText);
        String location = et.getText().toString();

        Geocoder geocoder = new Geocoder(this);
        List<Address> list = geocoder.getFromLocationName(location,1);
        Address address = list.get(0);
        String locality = address.getLocality();
        Toast.makeText(this, locality, Toast.LENGTH_SHORT).show();
        double lat = address.getLatitude();
        double lng = address.getLongitude();
        gotoLocationzoom(lat,lng,15);
        LatLng latLng = new LatLng(lat,lng);
        mMap.addMarker(new MarkerOptions().position(latLng).title(location).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
    

activity_map.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    tools:context=".MapActivity">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_
        android:layout_
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="0dp"
        tools:context="com.example.mapwithmarker.MapsMarkerActivity" />

    <EditText
        android:id="@+id/editText"
        android:layout_
        android:layout_
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginEnd="115dp"
        android:layout_marginRight="115dp"
        android:ems="10"
        android:hint="Enter your destination"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/button"
        android:layout_
        android:layout_
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginEnd="17dp"
        android:layout_marginRight="17dp"
        android:onClick="search"
        android:text="search" />


</RelativeLayout>

我添加到我的 AndroidManifest.xml 的权限

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

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE.EXTERNAL.STORAGE"/>
<uses-permission android:name="com.google.androidproviders.gsf.permissions.READ.GSERVICES"/>
<uses-permission android:name="com.kiki.doctorlocation.permission.MAPS.RECEIVE"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<permission android:name="com.kiki.doctorlocation.permission.MAPS.RECEIVE" android:protectionLevel="signature"/>

这是对我有用的代码...感谢您的见解

【讨论】:

以上是关于如何获取我的代码以提供我当前的位置?的主要内容,如果未能解决你的问题,请参考以下文章

如何通过iphone应用程序中的代码获取用户的当前位置?

如何使用 GPS 获取我在 Android 中的当前位置?

我无法使用我的代码获取当前位置

Android:如何获取经度和纬度的当前位置?

如何使用swift获取appdelegate中的当前位置

用百度地图api,怎么获取当前我的位置