1. 程式人生 > >openlayers讀取KML並顯示在地圖上

openlayers讀取KML並顯示在地圖上

在ol裡面讀取KML檔案時,如果style總是不對,需要設定一個重要的屬性 extractStyles: false 

不多說了,上程式碼示例

 var projection = ol.proj.get('EPSG:3857');
        var map = new ol.Map({
            target: 'map',
            view: new ol.View({
                center: ol.proj.transform([104.06, 30.67], 'EPSG:4326', 'EPSG:3857'),
                zoom: 7,
                projection: projection,
            })
        });
        var layer = new ol.layer.Tile({
            title: "基礎地圖",
            source: new ol.source.TileArcGISRest({
                url: 'http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer'
            })
        });
        map.addLayer(layer);
 
var styles = new ol.style.Style({
            fill: new ol.style.Fill({
                color: 'rgba(245, 0, 255, 0.5)'
            }),
            stroke: new ol.style.Stroke({
                color: '#ffcc33',
                width: 2
            })
        });  
var vectorSource2 = new ol.source.Vector({
            url: '../data/chengdu.kml',
            format: new ol.format.KML({
                dataProjection: 'EPSG:4326',
                featureProjection: 'EPSG:3857',
                extractStyles: false //至關重要
            }),
            projection: 'EPSG:3857'
        });
        var kmlLayer = new ol.layer.Vector({
            source: vectorSource2,
            style: styles
        });
        map.addLayer(kmlLayer);

技術交流請留言