Show my current location in the Google Map

前端 未结 5 491
-上瘾入骨i
-上瘾入骨i 2021-01-16 01:19

Finally I succeed to display the map,Now,I want to show my current location, I tried by using these code but it didn\'t work when I clicked the my location button in the to

5条回答
  •  野的像风
    2021-01-16 01:40

    private GoogleApiClient mGoogleApiClient;
    private GoogleMap mMap;
    

    Implement this listeners:

    LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener 
    

    onCreateView or onCreate method:

    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
            .addApi(LocationServices.API).addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).build();
        mGoogleApiClient.connect();
    }
    

    @Override Methods:

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            if (mLastLocation != null)
                onLocationChanged(mLastLocation);
            return;
        }
    }
    
    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(),location.getLongitude())));
            mMap.animateCamera(CameraUpdateFactory.zoomTo(6), 5000, null);
        }
    }
    

    Hope your task done.

提交回复
热议问题