简体   繁体   English

如何单击地图上多个标记中的一个标记,然后转到包含标记信息的活动

[英]How to click a marker from multiple markers on a map and then go to a activity with info of the markers

I want to create multiple markers on a map, each marker will have information, such as location, address..., and when I click the marker, another activity will show up and show the info of the marker I clicked, and I wrote some codes, the result turns out to be that, for different markers, the info transferred from the markers to the activity is the same, the code is like following:我想在地图上创建多个标记,每个标记都会有信息,比如位置、地址...,当我点击标记时,另一个活动会出现并显示我点击的标记的信息,我写了一些代码,结果证明,对于不同的标记,从标记传输到活动的信息是相同的,代码如下:

for (final MyMarkerData object: aaa) {
        m = googleMap.addMarker(new MarkerOptions()
                .position(object.getLatLng())
                .title(object.getTitle())
                .snippet(object.getSnippet()));
        googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker m) {
                Intent intent = new Intent(getActivity(), EventInfo.class);
                intent.putExtra("title", object.getTitle());
                startActivity(intent);
                return false;
            }
        });
      }

the code in the activity is like:活动中的代码如下:

Intent intent = getIntent();
    String a = intent.getStringExtra("title");
    TextView textview  =  findViewById(R.id.eventInfo);
    textview.setText(a);

when I click three different markers, the TextView showed the same info(actually is different), which is the last info in ArrayList aaa, so what's wrong with this?当我单击三个不同的标记时,TextView 显示相同的信息(实际上是不同的),这是 ArrayList aaa 中的最后一个信息,那么这有什么问题呢?

googleMap use only 1 OnMarkerClickListener for every Marker clicked event so you set it multiple times in a for loop is useless, the last one will override the previous listener. googleMap对每个标记点击事件仅使用 1 个OnMarkerClickListener ,因此您在 for 循环中多次设置它是无用的,最后一个将覆盖前一个侦听器。 That's why only the last listener is registered.这就是为什么只注册最后一个侦听器的原因。

Two things to refactor here: - Call setOnMarkerClickListener only 1 time is enough - Define a HashMap<Marker, object> to get the right object from the clicked marker这里需要重构两件事: - 只调用setOnMarkerClickListener 1 次就足够了 - 定义一个HashMap<Marker, object>以从点击的标记中获取正确的对象

HashMap<Object, Marker> markerMap = new HashMap<Object, Marker>();

googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
    @Override
    public boolean onMarkerClick(Marker m) {
        Object obj = markerMap.get(m);

        // Use obj for correct data object
    }
});

for (final MyMarkerData object: aaa) {
    marker = googleMap.addMarker(new MarkerOptions()
            .position(object.getLatLng())
            .title(object.getTitle())
            .snippet(object.getSnippet()));

    markerMap.put(aaa, marker)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM