Android Map View切换

时间:2011-08-17 13:35:13

标签: android google-maps

我正在尝试将地图视图从标准地图视图切换到卫星。我在这个网站上得到了以下代码。但是'mMapView'以红色标出,表示错误,执行建议的解决方案不起作用。

请向我解释我做错了什么以及我能做些什么来解决这个问题。感谢。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mapview :
if(mMapView.isSatellite()) {
mMapView.setSatellite(false); 
} else {
mMapView.setSatellite(true); 
}
default :
return super.onOptionsItemSelected(item);
}
}

我的onCreate是:

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(false);
}

2 个答案:

答案 0 :(得分:2)

使用mapView创建一个字段,并在“OnOptionItemSelected”中使用它。像这样:

private MapView mapView;
...
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.map);
  mapView = (MapView) findViewById(R.id.mapview);
  mapView.setBuiltInZoomControls(true);
  mapView.setSatellite(false);
}
...
@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
//this should be the id for the item in the menu, no for the map.
//if you select the item in the menu that toggle the view of your map, then, change the map
//I copied your code, but becareful because I think this can give you problems (about 
//having the same ids for the map and for the item in the same spacename ("id")
              case R.id.mapview : 
                if(mapView.isSatellite()) {
                   mapView.setSatellite(false); 
                } else {
                   mapView.setSatellite(true); 
                }
              default :
               return super.onOptionsItemSelected(item);
              }
            }

答案 1 :(得分:0)

@Finuka - 这无助于解决问题。它会导致它们出错:

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.map);
  mapView = (MapView) findViewById(R.id.mapview);
  mapView.setBuiltInZoomControls(true);
  mapView.setSatellite(false);
}

他们最初使用的应该是这个:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map);
    MapView mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);
    mapView.setSatellite(false);
}

我在地图应用中尝试了这个。 (我没有添加切换功能,因为我不需要)