【问题标题】:Get current Location automatically on opening up the app打开应用程序时自动获取当前位置
【发布时间】:2015-11-18 11:54:33
【问题描述】:

我无法在 Google 地图活动中获取我的当前位置,我已确保在 Android 清单中实现了权限,但它仍然变为 0,0 而不是我当前的位置。在模拟器上,位置首选项设置为开启。

这是我的主要活动:

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class RainstormMap extends FragmentActivity {

private GoogleMap mMap; 

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

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


private void setUpMapIfNeeded() {

    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment)              getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}

/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.
 * <p/>
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
private void setUpMap() {
    mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}

【问题讨论】:

    标签: java android google-maps android-activity android-studio


    【解决方案1】:

    你需要实现定位服务!

    使用 LocationListener 和 GoogleApiClient 接口

    public class RainstormMap extends FragmentActivity implements OnMapReadyCallback,
            GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener,
            LocationListener {
    
        private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 1000;
    
        /**
         * Map Settings
         */
        private static final int DEFAULT_ZOOM = 15;
        private static final int LOCATION_INTERVAL = 1000;
    
        /**
         * Map Properties and Utilities
         */
        private GoogleMap mMap;
        private GoogleApiClient mApiClient;
        private LocationRequest mLocationRequest;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_rainstorm_map);
    
            mApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
    
            // Create the LocationRequest object
            mLocationRequest = LocationRequest.create()
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                    .setInterval(LOCATION_INTERVAL)        // 10 seconds, in milliseconds
                    .setFastestInterval(LOCATION_INTERVAL); // 1 second, in milliseconds
    
            // setup map
            ((MapFragment) getFragmentManager().findFragmentById(R.id.googleMap)).getMapAsync(this);
        }
    
        /**
         * When get User Geo point call this method to list places by location
         *
         * @param location
         *          User current location
         */
        private void handleNewLocation(Location location) {
            // go to user location
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(location.getLatitude(),
                            location.getLongitude()),
                    DEFAULT_ZOOM
            ));
    
            mMap.addMarker(new MarkerOptions()
                    .title("Marker")
                    .position(new LatLng(
                            location.getLatitude(),
                            location.getLongitude()));
    
    
        }
    
        /**
         * --------- Google API Connection and get Map if is ready ---------
         */
    
        @Override
        public void onConnected(Bundle bundle) {
            Location loc = LocationServices.FusedLocationApi.getLastLocation(mApiClient);
    
            if (loc != null) {
                handleNewLocation(loc);
            } else {
                LocationServices.FusedLocationApi.requestLocationUpdates(mApiClient, mLocationRequest, this);
            }
        }
    
        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            if (connectionResult.hasResolution()) {
                try {
                    // Start an Activity that tries to resolve the error
                    connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                } catch (IntentSender.SendIntentException e) {
                    e.printStackTrace();
                }
            } else {
                Log.i(Const.TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
            }
        }
    
        @Override
        public void onConnectionSuspended(int i) {
            //TODO connection suspended implement
        }
    
        @Override
        public void onLocationChanged(Location location) {
            handleNewLocation(location);
        }
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            mMap.setMyLocationEnabled(true);
        }
    
        /**
         * --------- Activity Life Cycle ---------
         */
    
        @Override
        public void onResume() {
            super.onResume();
            mApiClient.connect();
        }
    
        @Override
        public void onPause() {
            super.onPause();
            if (mApiClient.isConnected()) {
                mApiClient.disconnect();
            }
        }
    }
    

    activity_rainstorm_map.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"
        android:id="@+id/rootView">
    
        <fragment
            android:id="@+id/googleMap"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:tag="ftag_google_map"
            android:name="com.google.android.gms.maps.MapFragment"/>
    
    </RelativeLayout>
    

    【讨论】:

    • 代码编译正确,谢谢。它只是不显示我的位置或标记。我确实获得了位置按钮,但它不会转到我的位置。
    猜你喜欢
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多