OpenLayers 3 Polygon over Dateline

by mcroteau

HTML

<script src="http://openlayers.org/en/v3.8.1/build/ol.js"></script>
<link rel="stylesheet" href="http://openlayers.org/en/v3.8.1/css/ol.css">
<div id="map"></div>

JavaScript

var wgs84Proj = new ol.proj.Projection({ code : "EPSG:4326" });
var origProj = new ol.proj.Projection({ code : "EPSG:900913" });

var mapTile = new ol.layer.Tile({
	source: new ol.source.OSM()
});
		

var convertedCoordinates = [];            
var unformattedCoordinates = [[175, 70], [175, 60], [-160, 60], [-160, 70]];

//Check/adjust for overlapping dateline
for (var i = 1; i < unformattedCoordinates.length; i++) {
    var dY = unformattedCoordinates[i][0] - unformattedCoordinates[i-1][0];
    if(Math.abs(dY) > 180)
        unformattedCoordinates[i][0] += 360;
}


$(unformattedCoordinates).each(function(index, coordinate){
    var lat = coordinate[0];
    var lon = coordinate[1];
    
    var circle = new ol.geom.Circle([lat, lon])
    circle.transform(wgs84Proj, origProj);

    convertedCoordinates.push(circle.getCenter());
});

var polygonGeometry = new ol.geom.Polygon([convertedCoordinates])
var polygonFeature = new ol.Feature({ geometry : polygonGeometry });

var vectorSource = new ol.source.Vector();
vectorSource.addFeature(polygonFeature);

var vectorLayer = new ol.layer.Vector({
    source: vectorSource
}); 


var mapView = new ol.View({
    center: [-19000000, 9500000],
  	zoom: 3
})
		
var map = new ol.Map({
  	layers : [mapTile],
  	target : 'map',
  	view   : mapView
});

map.addLayer(vectorLayer);