Java 无法解析方法 getMap()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38232747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:07:31  来源:igfitidea点击:

Cannot resolve method getMap()

javaandroidgoogle-maps

提问by Solmanian

I am trying to get a map fragment working within my application and I continue to get an error when trying to get my GoogleMap object.

我正在尝试让地图片段在我的应用程序中工作,但在尝试获取我的 GoogleMap 对象时继续出现错误。

FragmentWithMap.java

FragmentWithMap.java

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;



public class FragmentWithMap extends android.support.v4.app.Fragment {
    private OnFragmentInteractionListener mListener;
    private static final double LAT = 32.084;
    private static final double LON = 34.8878;
    Place place;
    private GoogleMap mMap;
    private View view;
    private Marker marker;
    int userIcon = FragmentWithDetails.userIcon;

    public static FragmentWithMap newInstance(Place place) {
        Bundle args = new Bundle();
        if (place != null) {
            args.putInt("id", place.getId());
            args.putString("name", place.getName());
            args.putString("address", place.getAddress());
            args.putFloat("lat", place.getLat());
            args.putFloat("lng", place.getLng());
        }
        FragmentWithMap fragment = new FragmentWithMap();
        fragment.setArguments(args);
        return fragment;
    }

    public FragmentWithMap() {
        //empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null && getArguments().getString("name") != null) {
            place = new Place(getArguments().getInt("id"), getArguments().getString("name"),
                    getArguments().getString("address"), getArguments().getFloat("lat"),
                    getArguments().getFloat("lng"));
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_fragment_with_map, container, false);
        }
        setUpMapIfNeeded();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        android.support.v4.app.Fragment f = getFragmentManager()
                .findFragmentById(R.id.fragmnet_container_map);
        if (f != null) {
            try {
                getFragmentManager().beginTransaction().remove(f).commit();
            } catch (IllegalStateException ise) {
                Log.d("FragmentWithMap", "Already closed");
            }
        }

        ViewGroup parentViewGroup = (ViewGroup) view.getParent();
        if (parentViewGroup != null) {
            parentViewGroup.removeAllViews();
        }
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public void showPlace(Place place) {
        setPlace(place);
        setUpMap();
    }

    public void setPlace(Place place) {
        this.place = place;
    }


    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(Uri uri);
    }

    private void setUpMapIfNeeded() {
        // Do a null check
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.


            Fragment mmm = getChildFragmentManager().findFragmentById(R.id.fragment_map2);
            mMap = ((SupportMapFragment) mmm).getMap();

            // Check if we were successful
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {
        double lat = LAT;
        double lng = LON;
        String name = "You are here";
        if (place != null) {
            lat = place.getLat();
            lng = place.getLng();
            name = place.getName();
        }
        if (marker != null) {
            marker.remove();
        }
        LatLng position = new LatLng(lat, lng);
        MarkerOptions markerOptions = new MarkerOptions().
                position(position).
                title(name).
                icon(BitmapDescriptorFactory.fromResource(userIcon)).
                snippet("Your last recorded location");

        marker = mMap.addMarker(markerOptions);
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mMap.setMyLocationEnabled(true);
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(position, 15);
        mMap.animateCamera(cameraUpdate);
    }

}

And here's the XML

这是 XML

fragment_with_map.xml

fragment_with_map.xml

<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/fragment_map2"
    tools:context="com.example.eldad.myplacesapp.FragmentWithMap"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    />

I copied the code from a different app, where the method getMap() is merely deprecated, so I doubt the problem is in the code itself. I have no issue with it being deprecated, and I prefer not to use the getMapAsync() if I don't have to. But here for some reason I recieve the error

我从另一个应用程序复制了代码,其中 getMap() 方法仅被弃用,所以我怀疑问题出在代码本身。我对它被弃用没有任何问题,如果我不需要,我宁愿不使用 getMapAsync()。但出于某种原因,我在这里收到了错误

"Cannot resolve method 'getMap()'"

“无法解析方法‘getMap()’”

. I also recieve an error

. 我也收到一个错误

"Error:Execution failed for task ':app:compileDebugJavaWithJavac'.

Compilation failed; see the compiler error output for details."

“错误:任务 ':app:compileDebugJavaWithJavac' 的执行失败。

编译失败;有关详细信息,请参阅编译器错误输出。”

Though I can't be sure if it's connected to this issue.

虽然我不确定它是否与这个问题有关。

回答by Daniel Nugent

The getMap()method was previously deprecated, and now it's been removed. If you look at the documentation for SupportMapFragment, it's not there.

getMap()方法以前被弃用,现在已被删除。如果您查看SupportMapFragment文档,则它不存在。

You can also see in the release notes:

您还可以在发行说明中看到:

The previously-deprecated getMap() function is no longer available in the Google Play services SDK. (It is still available in the Google Play services APK that is delivered to Android devices.) The getMap() function has been deprecated since December 2014. See the release blog postfor help with converting from getMap() to getMapAsync().

之前弃用的 getMap() 函数在 Google Play 服务 SDK 中不再可用。(它仍然在交付给 Android 设备的 Google Play 服务 APK 中可用。)自 2014 年 12 月以来,getMap() 函数已被弃用。有关从 getMap() 转换为 getMapAsync() 的帮助,请参阅发布博客文章

And from the blog post:

来自博客文章:

In December 2014 we deprecated getMap() in favor of getMapAsync(). From this release onwards, you'll need to use getMapAsync() in order to compile your apps.

2014 年 12 月,我们弃用了 getMap() 以支持 getMapAsync()。从这个版本开始,你需要使用 getMapAsync() 来编译你的应用程序。

So, just use getMapAsync(), it's simple.

所以,只要使用getMapAsync(),就很简单了。

First have your Fragment implement the OnMapReadyCallback interface:

首先让你的 Fragment 实现 OnMapReadyCallback 接口:

public class FragmentWithMap extends android.support.v4.app.Fragment
          implements OnMapReadyCallback { 

Then, modify your setUpMapIfNeeded() code, and add the onMapReady() callback:

然后,修改您的 setUpMapIfNeeded() 代码,并添加 onMapReady() 回调:

private void setUpMapIfNeeded() {
  if (mMap == null) {
    SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.fragment_map2);
    mapFrag.getMapAsync(this);
  }
}

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

回答by Divyesh V.Murani

Use this

用这个

compile 'com.google.android.gms:play-services-location:8.4.0'


 map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
                R.id.map)).getMap();