【问题标题】:onMapReady won't display maponMapReady 不会显示地图
【发布时间】:2018-09-28 01:56:39
【问题描述】:

我有两个项目的代码几乎相同,但这个项目不会显示地图,它只会烤我放在里面的东西

onMapReady

我确实有一个扩展 FragmentActivity 并实现 OnMapReadyCallback 的公共类

 private GoogleMap mMap;

将我的 GoogleMap 设为私有,因为它适用于我的其他项目。

在我的 onCreate 里面也是这个,后面跟着 onMapReady

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

@Override
public void onMapReady(GoogleMap googleMap) {
    Toast.makeText(MapsActivity.this, "onMapReady", Toast.LENGTH_SHORT).show();
    mMap = googleMap;

    LatLng start = new LatLng(10.008154, 123.635460);
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(start, 9));
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    } else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }
}
protected synchronized void buildGoogleApiClient() {
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
    if (mGoogleApiClient != null) {
        mGoogleApiClient.connect();
    }
}


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

它只显示这样 而不是

请不要介意标记。

【问题讨论】:

    标签: android google-maps


    【解决方案1】:

    我已经使用 fusedlocation Provider API 来获取用户的当前位置。

     public class activityPlot extends AppCompatActivity implements
                OnMapReadyCallback{
    
            private String TAG = activityPlot.class.getSimpleName();
    
            private GoogleMap mMap;
            private Boolean mLocationPermissionGranted = false;
            private FusedLocationProviderClient mFusedLocationProviderClient;
            private LatLng mDefaultLocation;
            private Location mLastKnownLocation;
    
            //  Request Code for Location Permission...
            private static final int LOCATION_PERMISSION_REQUEST_CODE = 438;
    
            @SuppressLint({"ClickableViewAccessibility", "ResourceType"})
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_plot);
    
                SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
                if (mapFragment != null) {
                    View mapView = mapFragment.getView();
                    if (mapView != null &&
                            mapView.findViewById(1) != null) {
                        @SuppressLint("ResourceType") View locationButton = ((View) mapView.findViewById(1).getParent()).findViewById(2);
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
                                locationButton.getLayoutParams();
                        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
                        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
                        layoutParams.setMargins(0, 0, 30, 200);
                    }
                    mapFragment.getMapAsync(this);
                }
    
                mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
            }
    
            @Override
            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;
                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    
                updateLocationUI();
                getDeviceLocation();
            }
    
            private void getLocationPermission() {
                Log.i(TAG, "asking for permission");
                if (ContextCompat.checkSelfPermission(this.getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    mLocationPermissionGranted = true;
                    updateLocationUI();
                } else {
                    ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
                }
            }
    
            @Override
            public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
                mLocationPermissionGranted = false;
                switch (requestCode) {
                    case LOCATION_PERMISSION_REQUEST_CODE: {
                        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                            mLocationPermissionGranted = true;
                        }
                    }
                }
                updateLocationUI();
            }
    
            private void updateLocationUI() {
                if (mMap == null) {
                    return;
                }
                try {
                    if (mLocationPermissionGranted) {
                        mMap.setMyLocationEnabled(true);
                        mMap.getUiSettings().setMyLocationButtonEnabled(true);
                    } else {
                        mMap.setMyLocationEnabled(false);
                        mMap.getUiSettings().setMyLocationButtonEnabled(false);
                        mLastKnownLocation = null;
                        getLocationPermission();
                    }
                } catch (SecurityException e) {
                    Log.e("Exception: %s", e.getMessage());
                }
            }
    
            private void getDeviceLocation() {
                try {
                    if (mLocationPermissionGranted) {
                        Task locationResult = mFusedLocationProviderClient.getLastLocation();
                        locationResult.addOnCompleteListener(this, task -> {
                            if (task.isSuccessful()) {
                                mLastKnownLocation = (Location) task.getResult();
                                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), 17));
                            } else {
                                Log.d(TAG, "Current location is null. Using defaults.");
                                Log.e(TAG, "Exception: %s", task.getException());
                                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, 17));
                                mMap.getUiSettings().setMyLocationButtonEnabled(false);
                            }
                        });
                    }
                } catch (SecurityException e) {
                    Log.e("Exception: %s", e.getMessage());
                }
            }
        }
    

    我的 XML 文件如下所示:->

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        orientation="vertical"
        tools:context=".activityPlot">
    
     <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
    </LinearLayout>
    

    清单文件 ->

    // Add Permissions and Meta-Data for key...
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="android.example.com.googlemap">
    
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.INTERNET" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <meta-data
                android:name="com.google.android.geo.API_KEY"
                android:value="@string/google_maps_key" />
        </application>
    
    </manifest>
    

    在 Gradle 文件中添加这些依赖项 ->

     //  Maps, Places and Location Libraries...
        implementation 'com.google.android.gms:play-services-maps:15.0.1'
        implementation 'com.google.android.gms:play-services-location:15.0.1'
    

    【讨论】:

    • 这段代码对我来说运行完美。希望它在您的设备上也能正常工作。如果这不起作用,那么,1. 尝试更新您设备上的播放服务,2. 尝试使用干净的项目和重建项目全新安装您的应用程序。
    猜你喜欢
    • 2018-08-30
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    相关资源
    最近更新 更多