为啥谷歌地图在首次启动时不会自动缩放到用户位置?

Posted

技术标签:

【中文标题】为啥谷歌地图在首次启动时不会自动缩放到用户位置?【英文标题】:Why won't Google maps auto zoom to user location when it first starts?为什么谷歌地图在首次启动时不会自动缩放到用户位置? 【发布时间】:2019-06-15 07:43:00 【问题描述】:

当用户第一次进入 GoogleMapsActivity 时,它不会自动将他们带到他们的位置,用户必须点击右上角的小位置图标按钮,它将把他们带到他们的位置。

我尝试过使用 newLatLngZoom(latLng, zoom) 但这不起作用。在发布这个问题之前,我浏览了所有建议的问题,但没有一个有效。有些也在ios中。我正在使用安卓系统。

public class AppetiteMapsActivity extends FragmentActivity implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener



private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private static final String TAG = "AppetiteMapsActivity";
private Location lastLocation;
private Marker currentUserLocationMarker;
private LocationManager locationManager;
private com.google.android.gms.location.LocationListener listener;
private static final int Request_User_Location_Code= 99;

private long UPDATE_INTERVAL = 2 * 1000;  /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */


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


    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
    
        checkUserLocationPermission();
    

    // 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);

    checkLocation();




@Override
public void onMapReady(GoogleMap googleMap) 
    mMap = googleMap;

    // Add a marker in current user location and move the camera
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
    
        buildGoogleApiClient();
        // Call current location of user
        mMap.setMyLocationEnabled(true);
    



public boolean checkUserLocationPermission()

    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, Request_User_Location_Code);
        
        else
            
            ActivityCompat.requestPermissions(this, new String[]Manifest.permission.ACCESS_FINE_LOCATION, Request_User_Location_Code);
            
            return false;
    
    else
    
        return true;
    


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)

    switch(requestCode)
    
        case Request_User_Location_Code:

            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            
                if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                
                    if (googleApiClient == null)
                    
                        buildGoogleApiClient();
                    
                    mMap.setMyLocationEnabled(true);
                

            

            else
            
                Toast.makeText(this, R.string.on_request_permission_gps_not_located, Toast.LENGTH_LONG).show();
            
            return;
    


protected synchronized void buildGoogleApiClient()

    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    googleApiClient.connect();


@Override
public void onConnected(Bundle bundle) 
    

        locationRequest = new LocationRequest();
        locationRequest.setInterval(1100);
        locationRequest.setFastestInterval(1100);
        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        
            LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
        
    


@Override
public void onConnectionSuspended(int i) 
    Log.i(TAG, "Connection Suspended");
    googleApiClient.connect();


@Override
public void onConnectionFailed(ConnectionResult connectionResult) 
    Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());


@Override
protected void onStart() 
    super.onStart();
    if (googleApiClient != null) 
        googleApiClient.connect();
    


@Override
protected void onStop() 
    super.onStop();
    if (googleApiClient.isConnected()) 
        googleApiClient.disconnect();
    


protected void startLocationUpdates() 
    // Create the location request
    locationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(UPDATE_INTERVAL)
            .setFastestInterval(FASTEST_INTERVAL);
    // Request location updates
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
        return;
    
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,
            locationRequest, this);
    Log.d("reque", "--->>>>");


@Override
public void onLocationChanged(Location location)

    lastLocation = location;
    if (currentUserLocationMarker!=null)
    
        currentUserLocationMarker.remove();
    

    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title(getString(R.string.user_current_location_marker_title));
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));

    currentUserLocationMarker = mMap.addMarker(markerOptions);


    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomBy(14));

    if(googleApiClient != null)
    
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
    



private boolean checkLocation() 
    if(!isLocationEnabled())
        showAlert();
    return isLocationEnabled();


private void showAlert() 
    final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle(R.string.show_alert_title_enable_location)
            .setMessage(getString(R.string.show_alert_location_settings_off_1) +
                    getString(R.string.show_alert_location_settings_off_2))
            .setPositiveButton(R.string.show_alert_positive_button_location_settings, new DialogInterface.OnClickListener() 
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) 

                    Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(myIntent);
                
            )
            .setNegativeButton(R.string.explain_negative_button, new DialogInterface.OnClickListener() 
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) 

                
            );
    dialog.show();


private boolean isLocationEnabled() 
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);



我希望 Google 地图在用户首次进入 Google 地图活动时自动转到用户位置,但用户必须单击右上角的位置按钮才能将其发送到那里。感谢您的帮助和建议!

【问题讨论】:

文档或其他地方是否有某些内容让您认为缺少某个功能? 我不这么认为。 startLocationUpdates 说它从未使用过,但是当我将它添加到 onCreate 方法时,它使我的应用程序崩溃。到目前为止,一切都很完美,我只希望它会在 Google Maps Activity 首次启动时自动缩放到用户位置,因为到目前为止,我必须手动点击地图右上角的小圆圈图标才能去到用户位置。 虽然我明白你在说什么,但我的意思是“我认为它不应该自动为你做到这一点”。当您尝试致电startLocationUpdates() 时,您的想法是正确的。看起来您已经编写了所有这些代码。也许放弃已弃用的FusedLocationApi——见here。如果您的代码崩溃,请使用堆栈跟踪来确定出了什么问题。 非常感谢 ????感谢您的建议! 【参考方案1】:

我尝试过使用newLatLngZoom(latLng, zoom),但没有成功。

像这样使用它,它会工作:

mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng, zoom));
mMap.getUiSettings().setRotateGesturesEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);

注意:

    首先,您启用缩放控件。 然后,您执行缩放操作。 之后,您禁用缩放控件。

希望对你有帮助。

Reference for more info

【讨论】:

非常感谢您的建议!明天当我回到编码时,我将尝试添加这个!有一个美好的夜晚!感谢您的帮助。 太棒了!工作!谢谢!我们都是堆栈溢出的新手!感谢您抽出宝贵时间提供帮助!我很感激!如果你有时间,请加1我的主要帖子?谢谢!

以上是关于为啥谷歌地图在首次启动时不会自动缩放到用户位置?的主要内容,如果未能解决你的问题,请参考以下文章

首次加载android后如何禁用谷歌地图当前位置跟踪

GoogleMap 在用户交互之前不会加载详细的地图

启用位置后刷新谷歌地图

根据地理位置在首次访问时重定向用户

如何根据标记位置设置谷歌地图的缩放级别

自动调整缩放以适应谷歌地图中的所有标记