Google Maps V3 fitBounds on visible markers

后端 未结 3 1342
深忆病人
深忆病人 2021-02-10 23:07

Finding it hard to get clear information on this but what I am trying to achieve is fitBounds on visible markers.

The Array defines the title, category, lat/long and hre

相关标签:
3条回答
  • 2021-02-10 23:36

    On first thought you would think you could use a bounds object and keep track of what is visible. But since you are also hiding markers and you can't remove a coordinate from the bounds, that wouldn't work.

    I think the best option would be to show/hide required markers, then loop through all of them and add them to a new bounds object if visible. Then fitbounds to that.

    function fitVisibleMarkers() {
        var bounds = new google.maps.LatLngBounds();
        for(var m in markers) {
            if (markers[m].getVisible()) {
                bounds.extend(markers[m].getPosition());
            }
        }
        map.fitBounds(bounds);
    }
    
    $("#activities .checkbox").click(function(){
        var cat = $(this).attr("value");
        if ($(this).is(":checked")) {
            show(cat);
        } else {
            hide(cat);
        }
        fitVisibleMarkers();
    });
    
    0 讨论(0)
  • 2021-02-10 23:55

    enter code hereif(markers[marker_id].getMap() != null ) { document.getElementById('markerlar').innerHTML += '
    ' +marker_id+''+markers[marker_id].position+''; //markers[marker_id].setMap(null); }

    0 讨论(0)
  • 2021-02-11 00:00

    well, you could program that inside your show function, I created own fiddle for you which demonstrates how to set 2 markers visible from array of 3 markers and fitBounds for only those:

    fiddle example

    Since code is now visible, with your case you could make separate fitBoundsToVisibleMarkers() method to be runned always after show() and hide() methods. for example:

    function fitBoundsToVisibleMarkers() {
    
        var bounds = new google.maps.LatLngBounds();
    
        for (var i=0; i<markers.length; i++) {
            if(markers[i].getVisible()) {
                bounds.extend( markers[i].getPosition() );
            }
        }
    
        map.fitBounds(bounds);
    
    }
    

    and your code does this:

    function show(category) {
        for (var i=0; i<locations.length; i++) {
            if (locations[i][2] == category) {
                markers[i].setVisible(true);
            }
        }
    
        // updating bounds in view
        fitBoundsToVisibleMarkers();
    }
    
    function hide(category) {
        for (var i=0; i<locations.length; i++) {
            if (locations[i][2] == category) {
                markers[i].setVisible(false);
            }
        }
    
        // updating bounds in view
        fitBoundsToVisibleMarkers();
    }
    
    0 讨论(0)
提交回复
热议问题