如何在谷歌地图android上设置多个标记?

Posted

技术标签:

【中文标题】如何在谷歌地图android上设置多个标记?【英文标题】:how to set the multiple marker on google map android? 【发布时间】:2020-04-22 14:26:50 【问题描述】:

我已经完成了具有多个位置的谷歌地图标记,并且我添加了一些带有医院名称、经度和纬度等字段的医院位置,我从 firebase 检索并加载到具有医院名称的可搜索微调器。当我单击医院名称时,它标记为该特定位置,但在我的代码中,所有位置都被标记,但是当我单击它时,它会转到该标记并返回当前位置,当我单击医院时可以做什么来显示该位置可搜索微调器中的名称任何人请帮助我

提前致谢


This is my java code

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, IFirebaseLoaddone, NavigationView.OnNavigationItemSelectedListener 

    private GoogleMap mMap;
    double longitude, latitude;
    private SearchableSpinner searchableSpinner;

    DatabaseReference hospitalRef;
    IFirebaseLoaddone iFirebaseLoaddone;
    List<Hospital> hospitals;

    private DrawerLayout drawer;
    private HashMap<String, Marker> mMarkers = new HashMap<>();

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

        searchableSpinner = findViewById(R.id.searchviewid);
        BubbleSeekBar bubbleSeekBar = findViewById(R.id.seekbar);
        final TextView textView = findViewById(R.id.textview);

        drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //init Db
        hospitalRef = FirebaseDatabase.getInstance().getReference("hospital");
        //init interface
        iFirebaseLoaddone = this;

        hospitalRef.addListenerForSingleValueEvent(new ValueEventListener() 
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) 

                List<Hospital> hospital = new ArrayList<>();
                for (DataSnapshot hospitalsnapshot : dataSnapshot.getChildren()) 
                    hospital.add(hospitalsnapshot.getValue(Hospital.class));
                
                iFirebaseLoaddone.onFirebaseLoadSuccess(hospital);

            

            @Override
            public void onCancelled(DatabaseError databaseError) 
                iFirebaseLoaddone.onFirebaseLoadFailed(databaseError.getMessage());

            
        );

        searchableSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() 
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
                hospitalRef.addChildEventListener(new ChildEventListener() 
                    @Override
                    public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) 
                        setMarker(dataSnapshot);
                    

                    @Override
                    public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) 
                        setMarker(dataSnapshot);
                    

                    @Override
                    public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) 

                    

                    @Override
                    public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) 

                    

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) 

                    
                );
            

            @Override
            public void onNothingSelected(AdapterView<?> parent) 

            
        );


        bubbleSeekBar.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListener() 
            @Override
            public void onProgressChanged(int progress, float progressFloat) 
                //textView.setText( String.format( "on change %d",progress ) );
            

            @Override
            public void getProgressOnActionUp(int progress, float progressFloat) 

            

            @Override
            public void getProgressOnFinally(int progress, float progressFloat) 

            
        );

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

        latitude = getIntent().getDoubleExtra("latitude", 0);
        longitude = getIntent().getDoubleExtra("longtitude", 0);

        findViewById(R.id.zoomin).setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                mMap.animateCamera(CameraUpdateFactory.zoomIn());
            
        );

        findViewById(R.id.zoomout).setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                mMap.animateCamera(CameraUpdateFactory.zoomOut());
            
        );


    

    @Override
    public void onMapReady(GoogleMap googleMap) 

        mMap = googleMap;

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager
                .PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) 

            return;
        

        mMap.setMyLocationEnabled(true);

        mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() 
            @Override
            public void onMyLocationChange(Location location) 

                CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
                CameraUpdate Zoom = CameraUpdateFactory.zoomTo(16);
                mMap.clear();

                MarkerOptions mp = new MarkerOptions();
                mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
                mp.title("Source");

                mMap.addMarker(mp);
                mMap.moveCamera(center);
                mMap.animateCamera(Zoom);
            
        );
    


    @Override
    public void onFirebaseLoadSuccess(List<Hospital> hospitalList) 

        hospitals = hospitalList;
        //get all data
        List<String> name_list = new ArrayList<>();
        List<Double> latitude = new ArrayList<>();
        List<Double> longitude = new ArrayList<>();
        for (Hospital hospital : hospitalList)
            name_list.add(hospital.getName());




        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, name_list);
        searchableSpinner.setAdapter(adapter);

    



    @Override
    public void onFirebaseLoadFailed(String message) 

    

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) 

        switch (item.getItemId()) 
            case R.id.nav_home:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new HomeFragment()).commit();
                break;
            case R.id.nav_location:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new LocationFragment()).commit();
                break;
            case R.id.nav_setting:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new SettingFragment()).commit();
                break;
            case R.id.nav_logout:
               logout();
                break;

        

        drawer.closeDrawer(GravityCompat.START);
        return true;
    

    private void logout()
    
        FirebaseAuth.getInstance().signOut();

        Intent intent= new Intent(getApplicationContext(),LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    

    @Override
    public void onBackPressed() 
        if(drawer.isDrawerOpen(GravityCompat.START))
            drawer.closeDrawer(GravityCompat.START);
        else 
            super.onBackPressed();
        
    

    private  void  setMarker(DataSnapshot dataSnapshot)

        String key = dataSnapshot.getKey();
        HashMap<String, Object> value = (HashMap<String, Object>) dataSnapshot.getValue();

        double latitude = Double.parseDouble(value.get("latitude").toString());
        double longitude = Double.parseDouble(value.get("longitude").toString());

        LatLng location = new LatLng(latitude,longitude);

        if(!mMarkers.containsKey(key)) 
            mMarkers.put(key, mMap.addMarker(new MarkerOptions().title(key).position(location)));
        
        else
        
            mMarkers.get(key).setPosition(location);

        
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for(Marker marker : mMarkers.values())
            builder.include(marker.getPosition());
        
        mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder.build(),100));

    




【问题讨论】:

【参考方案1】:

当我看到您的代码时,问题出在 setOnMyLocationChangeListener 上,因为每次 GPS 为您提供更新时,您都会将地图动画化到您当前的位置。

删除这两行:

mMap.moveCamera(center);
mMap.animateCamera(Zoom);

之后会是这样的:

mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() 
            @Override
            public void onMyLocationChange(Location location) 

                CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
                CameraUpdate Zoom = CameraUpdateFactory.zoomTo(16);
                mMap.clear();

                MarkerOptions mp = new MarkerOptions();
                mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
                mp.title("Source");

                mMap.addMarker(mp);'

            
        );
    

希望能解决问题

【讨论】:

没有任何效果,即使当我点击医院名称时它的工作原理相同,它也会返回当前位置 如果我将地图自动移动到当前位置

以上是关于如何在谷歌地图android上设置多个标记?的主要内容,如果未能解决你的问题,请参考以下文章

用户如何在谷歌地图颤振上添加多个标记

如何在谷歌地图上添加多个标记

单击标记时,新按钮会自动出现在谷歌地图(Android)上?如何删除?

按钮单击dialogFragment后如何在谷歌地图上添加标记?

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

如何在谷歌地图上显示多个信息窗口?