android - 如何在谷歌地图中添加标记?

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

我想在谷歌地图上添加一个标记。我在我的应用程序中成功加载了 map ,但是当我尝试添加标记时,应用程序崩溃了。我不知道为什么。请有人帮助我!

我的代码:

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>

最佳答案

创建方法 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 中获取 map ,然后使用Marker 添加到 map 中

 mMap.addMarker(new MarkerOptions().position(new LatLng(Your_lat, Your_long)).title("Marker"));

关于android - 如何在谷歌地图中添加标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22471859/

相关文章:

android - 在同一 fragment 事务中添加多个 fragment

android - 如何在android中的 map View 中设置地形 View ?

java - 当我从短信收到经度和纬度时,如何在谷歌地图中添加标记

android - Google Maps API 和 Facebook SDK for Android 不再工作,可能是因为调试 key

java - 当我从 Play 商店下载我的应用程序时,Google map v2 不会出现

android - 在 android Widgets 中实现 ListView

android - Android 的 JSON 解析 - 嵌套项目?

android - 如何测试方法在 Mockito 中返回 bool 值

android - 错误膨胀类 com.readystatesoftware.maps.TapControlledMapView

android - 我可以为我的所有应用程序使用一个 Google Maps API key ,而无需注册它们的包名称吗?