CyberJunkie
CyberJunkie

Reputation: 22684

Google Maps merge rectangles into one polygon and search it

Below is my code with an array of bounds and rectangle drawings on the map representing each bounds item.

http://jsfiddle.net/XffyE/4/

Is it possible to merge multiple rectangles/bounds into one polygon? The goal is to search within the polygon that was created by merging the rectangles.

For example searching places within the merged bounds instead of each bounds individually.

    function createBounds() {

        var bounds = new Array();

        bounds[0] = new google.maps.LatLngBounds(
            new google.maps.LatLng(25.941886953491675, -80.17411103748543),
            new google.maps.LatLng(25.947676224813897, -80.16767330177947)
        );
        bounds[1] = new google.maps.LatLngBounds(
            new google.maps.LatLng(25.941886953491675, -80.16767330177947),
            new google.maps.LatLng(25.94622890698334, -80.1644544339265)
        );
        bounds[2] = new google.maps.LatLngBounds(
            new google.maps.LatLng(25.927413775186118, -80.1644544339265),
            new google.maps.LatLng(25.94622890698334, -80.15962613214703)
        );
        bounds[3] = new google.maps.LatLngBounds(
            new google.maps.LatLng(25.927413775186118, -80.15962613214703),
            new google.maps.LatLng(25.931755728677782, -80.15801669822054)
        );
        bounds[4] = new google.maps.LatLngBounds(
            new google.maps.LatLng(25.927413775186118, -80.15801669822054),
            new google.maps.LatLng(25.933203046508336, -80.15318839644107)
        );
        bounds[5] = new google.maps.LatLngBounds(
            new google.maps.LatLng(25.92886109301667, -80.15318839644107),
            new google.maps.LatLng(25.933203046508336, -80.15157896251458)
        );

        drawRectangles(bounds);   
    }

    // Draw the array of bounds as rectangles on the map
    function drawRectangles(bounds) {
      boundsRectangles = new Array(bounds.length);
      for (var i = 0; i < bounds.length; i++) {
        boundsRectangles[i] = new google.maps.Rectangle({
          bounds: bounds[i],
          fillOpacity: 0,
          strokeOpacity: 1.0,
          strokeColor: '#000000',
          strokeWeight: 1,
          map: map
        });
      }
    }

Upvotes: 1

Views: 2728

Answers (1)

nwellcome
nwellcome

Reputation: 2299

Fun question, the short answer is:

  1. Find the coordinates of the vertices of all your rectangles
  2. Sort those vertices either clockwise or anti-clockwise (whichever Google maps wants)
  3. Feed those vertices as an array of LatLng objects in sorted order to Polygon() constructor

I'm sorry that I don't have time to go into detail about how to find the opposite corners or sort them all by angle, hopefully someone else can help you with that if this isn't enough.

Upvotes: 1

Related Questions