实时添加标记和折线

时间:2014-12-11 19:40:51

标签: android google-maps marker google-polyline

如何使用来自其他活动的实时数据在地图上添加更多标记并绘制更多折线? 我正在使用地图教程。 但我只能在oncreate中添加标记,并且无法传递来自其他活动的实时数据

如何添加多个标记,定期从另一个活动中提取纬度和长度

1 个答案:

答案 0 :(得分:0)

真正取决于如何将数据从其他活动传递到使用Google Maps v2 API的数据。我能想到的最简单的方法是使用Gson(自动链接到docs(toJson方法))

Gson允许您序列化Gson的对象into its equivalent Json representation。根据我的经验,该对象不应包含非泛型类型,例如其他对象。这可能是您的标记对象的一个​​示例。

class MarkerObject {
    public String name = "";
    public String snippet = "";
    public double lat = 0.0;
    public double lng = 0.0;
    public String markerImg = "";

    public MarkerObject() {}
}

要将其序列化为Json字符串并将其传递给intent,请执行以下操作:

MarkerObject exampleOfObject = new MarkerObject();
exampleOfObject.name = "Test Marker";
exampleOfObject.snippet = "Description/snipper woooh!";
exampleOfObject.lat = 1.0;
exampleOfObject.lng = 1.0;

Intent intent = new Intent(this, YourMapActivity.class);
intent.putExtra("exampleMarker", new Gson().toJson(exampleOfObject));
startActivity(intent);

并在onCreate()方法的地图活动中阅读。

在方法的底部可能看起来像这样:

Intent intent = getIntent();
String jsonMarker = intent.getStringExtra("exampleMarker", "");

if(jsonMarker != "") {
    MarkerObject exampleOfObject = (MarkerObject) new Gson().fromJson(jsonMarker);

    MarkerOptions exampleMarkerOptions = new MarkerOptions();

    exampleMarkerOptions.title(exampleOfObject.name);
    exampleMarkerOptions.snippet(exampleOfObject.snippet);
    exampleMarkerOptions.position(new LatLng(exampleOfObject.lat, exampleOfObject.lng));

    // Change 'map' into the variable name of your GoogleMap object.
    map.addMarker(exampleMarkerOptions);
}

我自己没有测试过,但根据文档,它应该可行。如果您想添加/修改/删除某些内容,请随时编辑此答案。

相关问题