Javascript – How to make a Google Maps API v3 hexagon tiled map, preferably coordinate-based

google mapsgoogle-maps-api-2google-maps-api-3javascript

http://econym.org.uk/gmap/example_eshapes.htm has a Google Maps API v2 example of how to tile hexagons, although the implementation scales painfully: it has a center hexagon, then six hexagons adjacent to it in the appropriate directions, then (in quasi-recursion) three hexagons adjacent to one of the hexagons adjacent to the original hexagon. And it has a nice border with transparent fill.

How can I create a similar effect, but preferably with tiling so that I specify (without mounds of recursion) that I want a tile six hexagons to the east of the origin and four hexagons 60° north of east from the tile six hexagons to the east?

I'm looking for something coordinate-based and preferably simple. I've looked at the source for http://www.rootmetrics.com/check-coverage/ and it works, but the code is coupled to their specific page, markup, etc., so imitating their code would take a bit of untangling.

Best Answer

The following example demonstrates how to render horizontal hexagons grid:

function initialize() {
    var mapOptions = {
        zoom: 7,
        mapTypeId: google.maps.MapTypeId.TERRAIN
    };

    var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
    var startPosition = new google.maps.LatLng(33.748589, -84.390392);  //Atlanta, GA, USA 
    var radius = 40 * 1000; //radius in meters
    drawHorizontalHexagonGrid(map,startPosition,radius,6);
    map.setCenter(startPosition);
}

function drawHorizontalHexagonGrid(map,startPosition,radius,count){
    var curPos = startPosition;
    var width = radius * 2 * Math.sqrt(3)/2 ; 
    for(var i = 0;i < count; i++){
        drawHorizontalHexagon(map,curPos,radius);
        curPos = google.maps.geometry.spherical.computeOffset(curPos, width,90);   
    }
}

function drawHorizontalHexagon(map,position,radius){
    var coordinates = [];
    for(var angle= 0;angle < 360; angle+=60) {
       coordinates.push(google.maps.geometry.spherical.computeOffset(position, radius, angle));    
    }
  
    // Construct the polygon.
    var polygon = new google.maps.Polygon({
        paths: coordinates,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35
    });
    polygon.setMap(map);
    map.setCenter(position);
}

google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map-canvas {
    height: 100%;
    margin: 0px;
    padding: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=geometry"></script>
<div id="map-canvas"></div>