torsdag 18 januari 2018

Drawing a donut in Bing Maps


Polygons with holes aka donuts have been a challange in web mapping. For not too long ago when customers asked if it is possible to have holes in polygons, I was avoiding the question. It is possible to send an array of rings to the polygon constructor. But within Spatial math library it is possible to achieve holes in polygons pretty easy. If a user draw a polygon on top of a polygon on the same layer, it might mean a hole.


  1. Create a polygon. The easiest way I know for this use case is to make a circle. 
  2. Create another smaller polygon, a polygon that I use to punch out the hole on the bigger polygon.
  3. Use the difference function in Spatial Math library to punch out the polygon.
  4. Add the donut polygon to the map. Done. 


Assuming there is an instantiated Bing Maps variable named map...
 Microsoft.Maps.loadModule('Microsoft.Maps.SpatialMath', () =>; {
    const outer = Microsoft.Maps.SpatialMath.getRegularPolygon(map.getCenter(),
                  30, 36, Microsoft.Maps.SpatialMath.DistanceUnits.Kilometers);

    const outerRing = new Microsoft.Maps.Polygon(outer);

    const  inner = Microsoft.Maps.SpatialMath.getRegularPolygon(map.getCenter(), 
                   10, 36, Microsoft.Maps.SpatialMath.DistanceUnits.Kilometers);

    const innerRing = new Microsoft.Maps.Polygon(inner);
    const donut = Microsoft.Maps.SpatialMath.Geometry.difference(outerRing, 


It is surprisingly easy to accomplish holes in polygons - and drawing circles. It is about ten lines of code depending on how you count it. Inside the module, it is in fact six lines that acctually do something.

It is powerful, easy to use and it solves reall world problems, like drawing islands on a lake. Or lakes on islands. 

Inga kommentarer:

Skicka en kommentar