我想将epsg:28992中的本地geoJson文件重新投影到OpenLayers中的OSM epsg:4326。我觉得我已经接近解决方案了,但我不知道下一步该怎么做。我在SO尝试并寻找了多个例子,但我觉得我在某个地方遗漏了某行代码。
现在,下面的代码显示了我在null岛上的本地gjson文件。如何告诉Open Layer将其重新投影到荷兰?
提前谢谢。
<html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.0/proj4.js"></script>
<script src="http://epsg.io/28992.js"></script>
<!-- Include OpenLayers -->
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/build/ol.js"></script>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/css/ol.css"
/>
<style>
html, body, #map {
margin: 0;
height: 75%;
width: 75%;
font-family: sans-serif;
background-color: #04041b;
}
</style>
<title>A simple web app</title>
</head>
<body>
<div id="map"></div>
<script>
// create an empty OpenLayers map
var map = new ol.Map({
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
// create OpenStreetMap base layer
var baseMap = new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'http://{a-c}.tile.osm.org/{z}/{x}/{y}.png',
attributions: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
})
});
map.addLayer(baseMap);
/*
//reproject
var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON({
defaultDataProjection: 'EPSG:4326',
featureProjection: 'EPSG:28992'
})).readFeatures(geojsonObject)
});
//reproject
*/
//LocalJson
var geojsonSource = new ol.source.Vector({
format: new ol.format.GeoJSON(
),
projection: 'EPSG:28992',
url: 'PS2019_buurt.geo.json'
});
var geojsonStyle = new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 0, 0, 0.6)' // red
}),
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 0, 1)' // black
})
});
var geojsonLayer = new ol.layer.Vector({
source: geojsonSource,
style: geojsonStyle
});
map.addLayer(geojsonLayer);
//LocalJson
</script>
</body>
</html>
您的功能应该始终转换为视图投影:
var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON({
dataProjection: 'EPSG:4326',
featureProjection: map.getView().getProjection(),
})).readFeatures(geojsonObject)
});
(由于OpenLayers 5,defaultDataProjection
选项被重命名为dataProjection
(
目前,您的视图正在使用OSM使用的默认web mercator。
如果你想在EPSG:28992中查看所有内容(功能和OSM(,你需要注册proj4并设置视图投影
ol.proj.proj4.register(proj4);
var map = new ol.Map({
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2,
projection: 'EPSG:28992'
})
});
如果将geojsonSource
与url
一起使用,则无需指定投影,数据将自动转换为视图投影。
然而,如果geojson中的数据在EPSG:28992中,则需要
ol.proj.proj4.register(proj4);
var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON({
dataProjection: 'EPSG:28992',
featureProjection: map.getView().getProjection(),
})).readFeatures(geojsonObject)
});
或
ol.proj.proj4.register(proj4);
var geojsonSource = new ol.source.Vector({
format: new ol.format.GeoJSON({
dataProjection: 'EPSG:28992'
}),
url: 'PS2019_buurt.geo.json'
});