如何在 Android 中的 onMapReady() 之外添加 Google 地图标记?

How to add Google Map Markers outside of onMapReady() in Android?

我有以下功能returns我设备的当前位置:

void getCurrentLocation()
{
    Location myLocation  = map.getMyLocation();
    if(myLocation!=null)
    {
        double dLatitude = myLocation.getLatitude();
        double dLongitude = myLocation.getLongitude();
        map.addMarker(new MarkerOptions().position(new LatLng(dLatitude, dLongitude))
                .title("My Location").icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_RED)));
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));

    }
    else
    {
        Toast.makeText(this, "Unable to fetch the current location", Toast.LENGTH_SHORT).show();
    }
}

但有些方法显示为红色,就像未定义一样:

如您所见,这些方法与地图有关,它在 onMapReady() 函数中起作用,但在它之外显示无法识别。这是为什么?我必须添加哪些库?我这样声明地图:

private MapFragment map;

你为什么要使用

 private MapFragment map;

您的地图类型应为

com.google.android.gms.maps.GoogleMap

只是改变

private MapFragment map;

private GoogleMap map;

并得到如下地图:

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

它将正常工作。

您的一般代码结构应该如下所示。 重要的部分是将您的本地 map 引用分配给 onMapReady() 回调中返回的引用。

public class MainActivity extends Activity 
        implements OnMapReadyCallback {

    private GoogleMap map;

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

        MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);

        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap retMap) {

        map = retMap;

        setUpMap();

    }

    public void setUpMap(){

        map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        map.setMyLocationEnabled(true);
    }

    void getCurrentLocation()
    {
        Location myLocation  = map.getMyLocation();
        if(myLocation!=null)
        {
            double dLatitude = myLocation.getLatitude();
            double dLongitude = myLocation.getLongitude();
            map.addMarker(new MarkerOptions().position(new LatLng(dLatitude, dLongitude))
                    .title("My Location").icon(BitmapDescriptorFactory
                            .defaultMarker(BitmapDescriptorFactory.HUE_RED)));
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));

        }
        else
        {
            Toast.makeText(this, "Unable to fetch the current location", Toast.LENGTH_SHORT).show();
        }
    }

}