2014-10-01 61 views
0

我想顯示一個顯示標記數組的地圖。我和OpenLayers Library一起使用OSM來做到這一點。如果我使用靜態值,一切正常。但是現在我想要顯示SQL表中的標記。獲取數據並將其填充到JS數組中的最佳方式是什麼?將SQL數據導入JS數組

這是我的代碼:

 <script> 
     map = new OpenLayers.Map("mapdiv"); 
     map.addLayer(new OpenLayers.Layer.OSM()); 

     var size = new OpenLayers.Size(10,10); 
     var icon = new OpenLayers.Icon('img/marker.gif', size); 

     epsg4326 = new OpenLayers.Projection("EPSG:4326"); //WGS 1984 projection 
     projectTo = map.getProjectionObject(); //The map projection (Spherical Mercator) 

     var lonLat = new OpenLayers.LonLat(8.289166666666, 46.834444444444) .transform(epsg4326, projectTo); 

     var zoom=8; 
     map.setCenter (lonLat, zoom); 

     // var markers = new OpenLayers.Layer.Markers("Markers"); 
     // map.addLayer(markers); 

     // markers.addMarker(new OpenLayers.Marker(lonLat, icon)); 

     var vectorLayer = new OpenLayers.Layer.Vector("Overlay"); 

     // Define an array. 
     var markers = [ 

     // SQL DATA NEEDS TO GO HERE! Formated like this: 
     // [47.153339352283,8.51886974582752], 
     // [47.5047313406471,8.76598280071111], 
     // [47.3085363748528,8.598335445835] 

     ]; 

     //Loop through the markers array 
     for (var i=0; i<markers.length; i++) { 

      var lon = markers[i][1]; 
      var lat = markers[i][0]; 

      var feature = new OpenLayers.Feature.Vector(
        new OpenLayers.Geometry.Point(lon, lat).transform(epsg4326, projectTo), 
        {description: "marker number " + i} , 
        {externalGraphic: 'img/marker.gif', graphicHeight: 10, graphicWidth: 10, } 
       );    
      vectorLayer.addFeatures(feature); 
     }       

     map.addLayer(vectorLayer); 

    </script> 

SQL表:

http://i.stack.imgur.com/OLZIc.png

謝謝:)

+0

使用ajax和服務器端語言(如php或asp)來拉取數據並將其作爲json推出。使用結果然後填充什麼OSM需要 – user3036342 2014-10-01 09:49:46

+0

哪個數據庫?如果Postgres,你可以使用st_asjson並從你的服務器使用java,php返回geojson,無論作爲(geo)json可以非常容易地轉換爲開放層功能。 – 2014-10-01 11:55:54

+0

@JohnBarça我正在使用MS SQL Server ... – 2014-10-01 12:56:26

回答

0

好吧,我已經有了一個解決方案: 首先我建了在C#中使用stringbuilder字符串並正確格式化爲我的JS數組。然後我將該字符串傳入JS:

var markers = [ <%=markers1%> ];