我尝试实施谷歌地图 v2,但我得到的只是错误。我遵循 了这些教程: http ://www.vogella.com/articles/AndroidGoogleMaps/article.html和http://blog-emildesign.rhcloud.com/?p=435教程(我使用 google api 8,所以有时我不得不更改一些东西 - 例如 SupportFragmentManager 而不是 FragmentManager)我的活动(修改了 Lars Vogel 的示例):
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapsInitializer;
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 MapActivity extends FragmentActivity {
static final LatLng HAMBURG = new LatLng(53.558, 9.927);
static final LatLng KIEL = new LatLng(53.551, 9.993);
private SupportMapFragment map;
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
mMap = map.getMap();
Marker hamburg = mMap.addMarker(new MarkerOptions().position(HAMBURG)
.title("Hamburg"));
Marker kiel = mMap.addMarker(new MarkerOptions()
.position(KIEL)
.title("Kiel")
.snippet("Kiel is cool")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
// Move the camera instantly to hamburg with a zoom of 15.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
// Zoom in, animating the camera.
mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
}
我的布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapActivity" >
<fragment
class="com.google.android.gms.maps.SupportMapFragment"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
我在 Marker hamburg 获得了 NPE。当我注释掉这一行时,我在 Marker kiel 处得到下一个错误 - ibitmapdescriptorfactory 未初始化。所以我猜这是 Marker 上的 .icon 方法的问题——在汉堡的情况下它是空/默认的,而在第二种情况下没有初始化。我不知道如何解决这个问题。