如何使用getMapAsync在自己的android应用程序中显示谷歌地图



我想在我自己的android应用程序中显示谷歌地图。。。我在manifest.im中使用了谷歌地图api键,使用了getMapAsync()。但它不起作用。。下面的代码是我犯的错误吗?请帮帮我。。非常感谢。

这是xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >
<fragment 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"
          android:id="@+id/map"
          tools:context=".ClinicMap"
          class="com.google.android.gms.maps.SupportMapFragment"
          android:apiKey="AIzaSyCbtSjGcG1g2u9H-hfuO6Tx7F442ZndDb4"/>

这是我的主要活动

public class ClinicMap extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.clinic_map);

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
 //        MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
 //        mapFragment.getMapAsync(this);
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    // Add a marker in Mumbai, India, and move the camera.
    LatLng mumbai = new LatLng(19.0128, 72.8246);
    if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    public void requestPermissions(@NonNull String[] permissions, int requestCode)
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for Activity#requestPermissions for more details.
        return;
    }
    mMap.setMyLocationEnabled(true);
    //mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(mumbai));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mumbai, 4));
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    mMap.addMarker(new MarkerOptions()
            .title("mumbai")
            .snippet("The most populous city in India.")
            .position(mumbai));
    }
 }

当我使用MapFragment时,我在一个空对象引用上得到了错误"尝试调用虚拟方法'void com.google.android.gms.maps.MapFragment.getMapAsync(com.google.aAndroid.gms-maps.OnMapReadyCallback)'"

当我使用SupportMapFragment时
输出将类似于

您需要将API密钥放在Manifest.xml中,而不是放在布局文件中,如果该密钥不在清单文件中,您将无法访问映射服务,并且您的片段将不显示任何内容。

转到您的清单,检查您是否添加了以下行。

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>

和内部<application>标签:

<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="API_KEY"/>

此外,您还需要检查您的mapFragment对象是否正确创建,通常我会使用这段代码来确保我没有向getMapAsync()传递null引用。

fragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_fragment);
        if(fragment == null){
            FragmentManager manager = getFragmentManager();
            fragment =SupportMapFragment.newInstance();
            manager.beginTransaction().replace(R.id.map_fragment, fragment).commit();
        }
        if (fragment != null){
            fragment.getMapAsync(this);
        }

我在一个简单的Fragment中使用过这个,你有一个FragmentActivity,所以你可能需要做一些小的更正来适应你的情况。

编辑:

我注意到您的类扩展了FragmentActivity,我编写的代码与扩展Fragment的类一起工作。在我看来,我有两个可能的解决方案:

  1. 创建一个FragmentActivity和另一个类,extends Fragmentimplements OnMapReadyCallback用于创建和操作地图。

  2. 创建一个简单的活动,在其layout.xml中创建一个片段并实例化映射。在这种情况下,你应该有这样的东西:

MAP_LAYOUT.xml:

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

ACTIVITY.java:

我只写OnCreate()SetUpMapIfYouNeed()SetUpMap()的细节,不写全班。

private GoogleMap mMap; // Might be null if Google Play services APK is not available.
@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_activity);
        Bundle bundle = new Bundle(getIntent().getExtras());
        this.title = bundle.getString("name");
        setUpMapIfNeeded();
        //Other lines of code
        //...
        //...
        }

/**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     * <p/>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     * <p/>
     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        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"));
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        mMap.setMyLocationEnabled(true);
        //Move the map to a specific point

    }

相关内容

最新更新