-
-
Save ThomasG77/28e26c6754bf31f25bc55ff672ab866b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset=utf-8> | |
<meta name=description content=""> | |
<meta name=viewport content="width=device-width, initial-scale=1"> | |
<title>Write to TopoJSON</title> | |
<link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css"> | |
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x --> | |
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script> | |
<script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script> | |
<script src="https://unpkg.com/topojson@3"></script> | |
</head> | |
<body> | |
<div id="map" class="map"></div> | |
<script> | |
var raster = new ol.layer.Tile({ | |
source: new ol.source.TileJSON({ | |
url: 'https://api.tiles.mapbox.com/v3/mapbox.world-dark.json?secure' | |
}) | |
}); | |
var style = new ol.style.Style({ | |
fill: new ol.style.Fill({ | |
color: 'rgba(255, 255, 255, 0.6)' | |
}), | |
stroke: new ol.style.Stroke({ | |
color: '#319FD3', | |
width: 1 | |
}) | |
}); | |
var vectorSource = new ol.source.Vector({ | |
url: 'https://openlayers.org/en/v4.6.5/examples/data/geojson/countries.geojson', | |
format: new ol.format.GeoJSON() | |
}) | |
var vector = new ol.layer.Vector({ | |
source: vectorSource, | |
style: style | |
}); | |
var map = new ol.Map({ | |
layers: [raster, vector], | |
target: 'map', | |
view: new ol.View({ | |
center: [0, 0], | |
zoom: 1 | |
}) | |
}); | |
// There are no writeFeatures for TopoJSON reading the API | |
// http://openlayers.org/en/latest/apidoc/ol.format.TopoJSON.html | |
// We use the official library https://github.com/topojson/topojson | |
// loaded in a script tag with src "https://unpkg.com/topojson@3" | |
// For the demo, we consider you are loading existing | |
// source vectorSource and an associated vector layer | |
vectorSource.on('change', evt => { | |
if (vectorSource.getState() === 'ready') { | |
var geojsonObject = (new ol.format.GeoJSON()) | |
.writeFeaturesObject( | |
vectorSource.getFeatures(), { | |
featureProjection: 'EPSG:3857' | |
} | |
); | |
console.log('GeoJSON', geojsonObject); | |
var topojsonObject = topojson.topology({ | |
world: geojsonObject | |
}); | |
console.log('TopoJSON', topojsonObject); | |
} | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment