Stu
Stu

Reputation: 61

How to add a "hole" to a Circle Polygon (Google Maps API V3)

This Pentagon example shows holes can be added inside a Polygon: http://code.google.com/p/gmaps-samples-v3/source/browse/trunk/poly/pentagon.html?r=40

I would like to add a hole inside a circle.

Currently I am mimicking this by making a circle shape polygon and putting inner and outer bounds and it is working fine, however the code is extremely long seeing as the map has ~15 circles in it.

Any help would be much appreciated

Thanks!

Upvotes: 5

Views: 4706

Answers (1)

Heitor Chang
Heitor Chang

Reputation: 6057

I didn't find anything for the Circle class, but someone has figured out a function that will reduce your code size. It does the same thing you are doing, creating polygons shaped like a circle.

function drawCircle(point, radius, dir) { 
var d2r = Math.PI / 180;   // degrees to radians 
var r2d = 180 / Math.PI;   // radians to degrees 
var earthsradius = 3963; // 3963 is the radius of the earth in miles

   var points = 32; 

   // find the raidus in lat/lon 
   var rlat = (radius / earthsradius) * r2d; 
   var rlng = rlat / Math.cos(point.lat() * d2r); 


   var extp = new Array(); 
   if (dir==1)  {var start=0;var end=points+1} // one extra here makes sure we connect the
   else     {var start=points+1;var end=0}
   for (var i=start; (dir==1 ? i < end : i > end); i=i+dir)  
   { 
      var theta = Math.PI * (i / (points/2)); 
      ey = point.lng() + (rlng * Math.cos(theta)); // center a + radius x * cos(theta) 
      ex = point.lat() + (rlat * Math.sin(theta)); // center b + radius y * sin(theta) 
      extp.push(new google.maps.LatLng(ex, ey)); 
      bounds.extend(extp[extp.length-1]);
   } 
   // alert(extp.length);
   return extp;
   }

var map = null;
var bounds = null;

function initialize() {
  var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(-33.9, 151.2),
    mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"),
                                myOptions);
 
  bounds = new google.maps.LatLngBounds();

  var donut = new google.maps.Polygon({
                 paths: [drawCircle(new google.maps.LatLng(-33.9,151.2), 100, 1),
                         drawCircle(new google.maps.LatLng(-33.9,151.2), 50, -1)],
                 strokeColor: "#0000FF",
                 strokeOpacity: 0.8,
                 strokeWeight: 2,
                 fillColor: "#FF0000",
                 fillOpacity: 0.35
     });
     donut.setMap(map);
  
 map.fitBounds(bounds);
 
}

http://www.geocodezip.com/v3_polygon_example_donut.html

The function drawCircle(point, radius, dir) uses dir to distinguish positive space and holes. You have to alternate them to create holes.

Upvotes: 5

Related Questions