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

时间:2015-07-22 18:21:07

标签: android google-maps google-maps-api-2

我有以下函数返回设备的当前位置:

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();
    }
}

但有些方法显示为红色,如未定义: this

正如您所注意到的,这些方法与map相关,它在onMapReady()函数中起作用,但是它表明它无法识别。这是为什么?我要添加哪些库?我宣布这样的地图:

private MapFragment map;

2 个答案:

答案 0 :(得分:4)

这是您的通用代码结构应该是什么样子。 重要的是将您的本地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();
        }
    }

}

答案 1 :(得分:1)

你为什么使用

 private MapFragment map;

您的地图应为

类型
com.google.android.gms.maps.GoogleMap

只需更改

private MapFragment map;

private GoogleMap map;

并获取如下地图:

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

它会正常工作。