1. 程式人生 > >openLayer3圖層加入資料,一邊加一邊更新。

openLayer3圖層加入資料,一邊加一邊更新。

這個需要考慮JS多執行緒的問題,需要用定時器建立新的執行緒去做,一個執行緒的話會出現需要所有資料加入後,地圖上才出現點。

<!DOCTYPE html>
<html>
  <head>
    <title>Clustered Features</title>
    <link rel="stylesheet" href="http://openlayers.org/en/v3.18.2/css/ol.css" type="text/css">
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="http://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script> <script src="http://openlayers.org/en/v3.18.2/build/ol.js"></script> </head> <body> <div id="map" class="map"></div> <button
onClick="play()">
新增要素</button> <script> var count = 10000; var features = new Array(count); var e = 4500000; for (var i = 0; i < count; ++i) { var coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e]; features[i] = new ol.Feature(new
ol.geom.Point(coordinates)); } var source = new ol.source.Vector({ }); var styleCache = {}; var vectlayers= new ol.layer.Vector({ source: source, style: new ol.style.Style({ image: new ol.style.Circle({ radius: 10, stroke: new ol.style.Stroke({ color: '#fff' }), fill: new ol.style.Fill({ color: '#3399CC' }) }) }) }); var raster = new ol.layer.Tile({ source: new ol.source.OSM() }); function createPlayer(interval,count,show,onFinished){ var t={ timer:null, index:0, count:count, isPause:false, play:function(){ t.timer=setInterval(function(){ if(!t.isPause){ if(t.index<t.count){ show(t.index++); } else{ t.stop(); } } },interval) }, pause:function(){ t.isPause = true; }, continue:function(){ t.isPause=false; }, stop:function(){ t.index=0; clearInterval(t.timer); onFinished(); } } return t; } function addFeatures(index){ for(var i=index*100;i<100*(index+1);i++){ vectlayers.getSource().addFeature(features[i]); } } function play(){ var animate=createPlayer(500,100,function(index){ addFeatures(index); }); animate.play(); } var map = new ol.Map({ layers: [raster, vectlayers], renderer: 'canvas', target: 'map', view: new ol.View({ center: [0, 0], zoom: 2 }) });
</script> </body> </html>