Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

javascript - check if map markers are within selected bounds

I have a map with various markers and i need to be able to draw a rectangle on the map and select the markers which are within the rectangle bounds.

So far i have found some great info here: How to get markers inside an area selected by mouse drag?

I have implemented the keymapzoom plugin ok. like so

    $('#dispatcher').gmap3({action:'get'}).enableKeyDragZoom({
        boxStyle: {
          border: "dashed black",
          //backgroundColor: "red",
          opacity: 0.5
        },
        paneStyle: {
          backgroundColor: "gray",
          opacity: 0.2
        }
  });
var dz = $('#dispatcher').gmap3({action:'get'}).getDragZoomObject();
google.maps.event.addListener(dz, 'dragend', function (bnds) {
  alert(bnds);
});

This gives me the following ((lat,long),(lat,long)) format from the alert(bnds);

I need to know how i can now check if any markers are within this?

I already have an object that is storing the markers for another reason. like:

    markers[name] = {};
    markers[name].lat = lati;
    markers[name].lng = longi;

which might be useful?

I don't understand how to use the GLatLngBounds and containsLatLng(latlng:GLatLng) as suggested.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your question is tagged with the v3 version of the Maps API, so I'll assume you are using that version (which you should as v2 is deprecated). Note that some classes and methods are named different than in your question.

Bounds are represented with the LatLngBounds class. You can perform the contains method on an instance of that class to determine if a point lies within those bounds.

If you have an object with all your markers, you can loop through them and check each marker, for example:

var bounds = new google.maps.LatLngBounds(sw, ne);
for (var a in markers) {
    if (bounds.contains(new google.maps.LatLng(markers[a].lat, markers[a].lng)) {
        // marker is within bounds
    }
}

On a side note, I would store the LatLng object in the markers object when creating them. That way you don't have to create them wherever you need.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...