Google 点击标记打开地图 activity

Google Maps open activity on marker click

我在 Google 地图中制作自定义标记并希望它们在点击时打开 activity。我使用了 SetOnMarkerClickListener ,但它似乎不起作用。我哪里做错了?我怎样才能让我的代码更好更干净。代码如下。

public class Location extends FragmentActivity implements OnMapReadyCallback{

    GoogleMap map;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        map = googleMap;

        LatLng University = new LatLng(43.242007480536806, 76.95185128808076);
        LatLng AgroBio = new LatLng(43.24019774903174, 76.95182725886109);
        LatLng WaterLandForest = new LatLng(43.24203640423325, 76.95286753906628);
        LatLng HydraTech = new LatLng(43.24064521255793, 76.95167663826041);
        LatLng IT = new LatLng(43.23943180174249, 76.95194217695317);
        LatLng Vet = new LatLng(43.24140285274656, 76.93963598030956);
        LatLng TechBio = new LatLng(43.24111066883304, 76.93696680532199);
        LatLng AgriTech = new LatLng(43.24118832901344, 76.95236044889603);

        map.moveCamera(CameraUpdateFactory.newLatLngZoom(University, 17));

        map.addMarker(new MarkerOptions().position(University).icon(bitmapDescriptorFromVector(getApplicationContext(), R.drawable.ic_map_university)));
        map.addMarker(new MarkerOptions().position(AgroBio).icon(bitmapDescriptorFromVector(getApplicationContext(), R.drawable.ic_map_university)));
        map.addMarker(new MarkerOptions().position(WaterLandForest).icon(bitmapDescriptorFromVector(getApplicationContext(), R.drawable.ic_map_university)));


        map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if(marker.equals(University)){
                    Intent intent = new Intent(Location.this, o_kaznau.class);
                    startActivity(intent);
                    return true;
                } if(marker.equals(AgroBio)){
                    Intent intent = new Intent(Location.this, agrobio.class);
                    startActivity(intent);
                }

                return false;
            }
        });

    }

您的 if 条件失败,因为 if(marker.equals(University)) 在您将 LatLng 与标记进行比较时始终为假。

尝试:

在 onMarkerClick 中添加这个

LatLng position = marker.getPosition();

然后在你的 if 条件下

if(position.equals(University)){
....
}

和你的第二个 if 条件一样