2016-11-18 2 views
0

나는 Openlayers3에 대한 새로운 지식을 가지고있다. ..... 나는 openlayers3에 벡터 데이터를로드하기 위해 PHP로 & 아약스를 사용하여 데이터베이스에서 데이터를로드하려고하는데, 나는 갇혀 있고 어떤 문제인지 모른다. 여기 내 코드 누구든지 저를 도울 수 있습니까?ajax를 사용하여 openlayer3에서 레이어를 추가하는 방법은 무엇입니까?

$(document).ready(function() 
{ 
//extent of the map 
view = new ol.View({ 
    center:ol.proj.transform([125.7799,8.7965], 'EPSG:4326', 'EPSG:3857'), 
    zoom:11, 
    maxZoom:18, 
    minZoom:2 
}); 

//BaseLayer 
var baseLayer = new ol.layer.Tile({ 
    source: new ol.source.OSM() 
}); 

// create a vector source that loads a GeoJSON file 
var vectorSource = new ol.source.Vector({ 
    projection: 'EPSG:4326', 
    url: 'data/Boundaries.geojson', 
    format: new ol.format.GeoJSON() 

    }); 

var geoJSONFormat = new ol.format.GeoJSON(); 

var farmersSource = new ol.source.Vector({ 
    loader: function(extent, resolution, projection) { 
    var url = 'allfarmers_geojson.php?p=' + extent.join(','); 
    $.ajax({ 
     url: url, 
     success: function(data) { 
     var features = geoJSONFormat.readFeatures(data); 
     farmersSource.addFeatures(features); 
     } 
    }); 
    }, 
    strategy: ol.loadingstrategy.bbox 
}); 


// Polygons 
var createPolygonStyleFunction = function() { 
    return function(feature, resolution) { 
    var style = new ol.style.Style({ 
     stroke: new ol.style.Stroke({ 
     color: 'blue', 
     width: 1 

     }), 
     fill: new ol.style.Fill({ 
     color: '#faeaac' 
     }), 
     //text: createTextStyle(feature) 
    }); 
    return [style]; 
    }; 
}; 

// a vector layer to render the source 
var vectorLayer = new ol.layer.Vector({ 
    source: vectorSource, 
    style:createPolygonStyleFunction() 

}); 

var farmersLayer = new ol.layer.Vector({ 
    source: farmersSource 
    //style:createPolygonStyleFunction() 

}); 

//Map 
var map = new ol.Map({ 
    target:'map', 
    controls:ol.control.defaults().extend([ 
     new ol.control.ScaleLine(), 
     new ol.control.ZoomSlider() 
    ]), 
    renderer: 'canvas', 
    layers:[baseLayer,vectorLayer,farmersLayer], 
    view:view 
}); 

//////////styling features and with mouse over color change///////////// 
var highlightStyleCache = {}; 

var featureOverlay = new ol.layer.Vector({ 
source: new ol.source.Vector(), 
map: map, 
style: function(feature, resolution) { 
    var text = resolution < 5000 ? feature.get('NAME_3') : ''; 
    if (!highlightStyleCache[text]) { 
    highlightStyleCache[text] = new ol.style.Style({ 
     stroke: new ol.style.Stroke({ 
     color: '#f00', 
     width: 1 
     }), 
     fill: new ol.style.Fill({ 
     color: 'rgba(255,0,0,0.1)' 
     }), 
     text: new ol.style.Text({ 
     font: '12px Calibri,sans-serif', 
     text: text, 
     fill: new ol.style.Fill({ 
      color: '#f00' 
     }) 
     }) 
    }); 
    } 
    return highlightStyleCache[text]; 
} 
}); 

var highlight; 
var displayFeatureInfo = function(pixel) { 

var feature = map.forEachFeatureAtPixel(pixel, function(feature) { 
     return feature; 
    }); 

    if (feature !== highlight) { 
     if (highlight) { 
     featureOverlay.getSource().removeFeature(highlight); 
     } 
     if (feature) { 
     featureOverlay.getSource().addFeature(feature); 
     } 
     highlight = feature; 
    } 

    }; 

    map.on('pointermove', function(evt) { 
    if (evt.dragging) { 
     return; 
    } 
    var pixel = map.getEventPixel(evt.originalEvent); 
    displayFeatureInfo(pixel); 
    }); 

    map.on('click', function(evt) { 
    displayFeatureInfo(evt.pixel); 
    }); 
//////////End of styling features and with mouse over color change///////////// 

}); 

여기가 아니 정확히 당신이 필요하지만 서버에서 data 응답을 this..You 아마 오른쪽 돌출부를 설정해야 시도하고 분석하는지 문제가 있는지 내 PHP 파일

<?php 
    $conn = new PDO('mysql:host=localhost;dbname=FarmersDB','root','admin'); 

    $sql = 'SELECT *, _coordinates__latitude AS x, _coordinates__longitude AS y FROM farmers'; 

if (isset($_GET['bbox']) || isset($_POST['bbox'])) { 
$bbox = explode(',', $_GET['bbox']); 
$sql = $sql . ' WHERE x <= ' . $bbox[2] . ' AND x >= ' . $bbox[0] . ' AND y <= ' . $bbox[3] . ' AND y >= ' . $bbox[1]; 
} 

$rs = $conn->query($sql); 
if (!$rs) { 
echo 'An SQL error occured.\n'; 
exit; 
} 

$geojson = array(
'type'  => 'FeatureCollection', 
'features' => array() 
); 


while ($row = $rs->fetch(PDO::FETCH_ASSOC)) { 
$properties = $row; 

unset($properties['x']); 
unset($properties['y']); 
$feature = array(
    'type' => 'Feature', 
    'geometry' => array(
     'type' => 'Point', 
     'coordinates' => array(
      $row['x'], 
      $row['y'] 
     ) 
    ), 
    'properties' => $properties 
); 

array_push($geojson['features'], $feature); 
} 

header('Content-type: application/json'); 
echo json_encode($geojson, JSON_NUMERIC_CHECK); 
$conn = NULL; 
?> 
+0

이 문서 http://geojson.org/geojson-spec.html에서 설명한대로 서버에서 반환 된'success : function (data)'의'data' var은 geoJSON이어야합니다. 지금까지 어떤 문제가 발생 했습니까 ?? 서버에서 반환 된 데이터가 없습니다 ?? – GoinOff

+0

완료되었습니다, 고마워요 :) –

답변

0

입니다 ..Projection는 기본적으로 EPSG:3857입니다 : 또한

success: function(data) { 
    var JSONData; 
     try { 
     JSONData = JSON.parse(data); 
     } catch(err) { 
     alert(err); 
     return; 
     } 
     var format = new ol.format.GeoJSON(); 
     var features = format.readFeatures(JSONData, { 
      featureProjection: 'EPSG:3857' 
     }); 
     farmersSource.addFeatures(features); 
     farmersSource.changed(); 
    } 
    }); 

, var vectorSource 변화 EPSG:3857에 프로젝트. 또 다른 한가지는 vectorloader 속성을 source.vector에 추가해야합니다. 예 :

var locationSource = new ol.source.Vector({ 
    url: loc_url, 
    format: new ol.format.GeoJSON({ 
    defaultDataProjection :'EPSG:3857' 
    }), 
    loader: vectorLoader, 
    strategy: ol.loadingstrategy.all 
}); 

vectorLoader 함수는 다음과 같이 표시되며 서버에 대한 ajax 호출을합니다. 로더 기능에 대한 특별 참고 사항 - 소스 레이어에()를 호출 분명, 다시 벡터 로더 기능을 트리거 : 줬어요

var vectorLoader = function(extent, resolution, projection) { 
    var url = this.getUrl(); 
    utils.refreshGeoJson(this); 
} 


var utils = { 
    refreshGeoJson: function(source,url) { 
    var now = Date.now(); 
    if (typeof url == 'undefined') { 
     url = source.getUrl(); 
    } 
    url += '?t=' + now; //Prevents browser caching if retrieving a geoJSON file 
    console.info('refreshGeoJson url: ' + url); 
    this.getJson(url).when({ 
    ready: function(response) { 
    var JSONResponse; 
    try { 
     JSONResponse = JSON.parse(response); 
    } catch(err) { 
     alert(err + ' - ' + url); 
     return; 
    } 
    var format = new ol.format.GeoJSON(); 
    var features = format.readFeatures(JSONResponse, { 
     featureProjection: 'EPSG:3857' 
    }); 
     source.addFeatures(features); 
     source.changed(); 
    } 
    }); 
}, 
getJson: function(url) { 
    var xhr = new XMLHttpRequest(), 
    when = {}, 
    onload = function() { 
    console.log(url + ' xhr.status: ' + xhr.status); 
    if (xhr.status === 200) { 
    console.log('getJson() xhr: '); 
    console.dir(xhr); 
    console.log('getJson() xhr.response: '); 
    console.dir(xhr.response); 
     when.ready.call(undefined, xhr.response); 
    } 
    if (xhr.status === 404) { 
     console.log('map file not found! url: ' + url); 
    } 
    }, 
    onerror = function() { 
     console.info('Cannot XHR ' + JSON.stringify(url)); 
    }; 
     xhr.open('GET', url, true); 
     xhr.setRequestHeader('cache-control', 'no-store'); 
     xhr.onload = onload; 
     xhr.onerror = onerror; 
     xhr.send(null); 
     return { 
     when: function(obj) { when.ready = obj.ready; } 
     }; 
    } 
}; 

을 엑스트라를 많이 여기에 내가 당신의 문제가 무엇인지 확실하지 않다 때문에 코드로 위의 예제는 서버에서 geoJSON 파일을 주기적으로 변경하여 검색 할 때 유용합니다. PHP 스크립트를 호출하는 경우 똑같이 작동해야합니다.이 사양에 따라 geoJSON 데이터가 반환되는지 확인하십시오.

+0

고맙습니다. @GoinOff :) ....이 두 레이어에 대한 전설을 추가하는 방법에 대한 예제를 보여줄 수 있습니까? .... 미리 감사드립니다. –

+0

다행입니다. Openlayers 3에는 범례를 처리하는 기능이 없습니다. 내가 직접 쓰려고 생각하고 있지만 아직 어떻게 가야할지 모르겠다. – GoinOff

관련 문제