Get current location in onMapReady in android using google locations API

前端 未结 1 1213
闹比i
闹比i 2021-02-04 15:45

I\'m trying to display the current location of the user on the google map inside my app but I don\'t want to keep updating the location as the user moves. His initial location s

相关标签:
1条回答
  • 2021-02-04 16:35

    Just move the code that creates the Markers from onMapReady() to onConnected(), and move the call buildGoogleApiClient() call from onCreate() to onMapReady():

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        //buildGoogleApiClient();
    
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    
    }
    
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    
        // Add a marker in Sydney and move the camera
        mMap.setMyLocationEnabled(true);
    
        //add this here:
        buildGoogleApiClient();
    
        //LatLng loc = new LatLng(lat, lng);
        //mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
        //mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
    }
    
    @Override
    public void onConnected(Bundle bundle) {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            lat = mLastLocation.getLatitude();
            lng = mLastLocation.getLongitude();
    
            LatLng loc = new LatLng(lat, lng);
            mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
        }
    }
    

    Although, note that you will frequently get null from the call to getLastLocation(). You can use requestLocationUpdates(), and call removeLocationUpdates() when the first location comes in. Take a look at this answer, it has a complete example of exactly what you're trying to do.

    0 讨论(0)
提交回复
热议问题