我想在Google地图中添加一个标记。我在我的应用程序中成功加载了地图但是当我尝试添加标记时,应用程序崩溃了。我不知道为什么。请有人帮助我!
我的代码:
public class BasicMapActivity extends FragmentActivity {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
setUpMap();
}
@Override
protected void onResume() {
super.onResume();
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}
Layout.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:id="@+id/map2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>
答案 0 :(得分:1)
创建方法setUpMapIfNeeded()
并调用onResume()
和onCreate()
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
首先,您需要从SupportMapFragment
获取地图,然后使用
Marker
添加到地图中
mMap.addMarker(new MarkerOptions().position(new LatLng(Your_lat, Your_long)).title("Marker"));
答案 1 :(得分:0)
试试这个
private void setUpMap() {
Marker pos_Marker = googleMap.addMarker(new MarkerOptions().position(starting).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_laumcher)).title("Starting Location").draggable(false));
pos_Marker.showInfoWindow();
}