Php 如何使用ajax在openlayer3中添加层?
我是Openlayers3的新手……我正在尝试使用ajax和php从数据库加载数据,以将矢量数据加载到Openlayers3,我被卡住了,不知道问题出在哪里。 这是我的密码 有人能帮我吗Php 如何使用ajax在openlayer3中添加层?,php,ajax,openlayers-3,Php,Ajax,Openlayers 3,我是Openlayers3的新手……我正在尝试使用ajax和php从数据库加载数据,以将矢量数据加载到Openlayers3,我被卡住了,不知道问题出在哪里。 这是我的密码 有人能帮我吗 $(document).ready(function() { //extent of the map view = new ol.View({ center:ol.proj.transform([125.7799,8.7965], 'EPSG:4326', 'EPSG:3857'), zoom:
$(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/////////////
});
$(文档).ready(函数()
{
//地图的范围
视图=新的ol.view({
中心:ol.proj.transform([125.7799,8.7965],'EPSG:4326','EPSG:3857'),
缩放:11,
maxZoom:18,
最小缩放:2
});
//基层
var baseLayer=新的ol.layer.Tile({
来源:new ol.source.OSM()
});
//创建加载GeoJSON文件的矢量源
var vectorSource=新的ol.source.Vector({
投影:‘EPSG:4326’,
url:'data/bounders.geojson',
格式:new ol.format.GeoJSON()
});
var geoJSONFormat=new ol.format.GeoJSON();
var farmersSource=新的ol.source.Vector({
加载器:函数(范围、分辨率、投影){
var url='allfarmers_geojson.php?p='+extent.join(',');
$.ajax({
url:url,
成功:功能(数据){
var features=geoJSONFormat.readFeatures(数据);
farmersSource.addFeatures(特征);
}
});
},
策略:ol.loadingstrategy.bbox
});
//多边形
var createPolygonStyleFunction=函数(){
返回函数(特性、分辨率){
var style=新的ol.style.style({
笔划:新的ol风格笔划({
颜色:“蓝色”,
宽度:1
}),
填充:新的ol.style.fill({
颜色:“#faeaac”
}),
//文本:createTextStyle(功能)
});
返回[风格];
};
};
//用于渲染源的向量层
var vectorLayer=新ol.layer.Vector({
来源:矢量源,
样式:createPolygonStyleFunction()
});
var farmersLayer=新ol.layer.Vector({
资料来源:farmersSource
//样式:createPolygonStyleFunction()
});
//地图
var map=新ol.map({
目标:'地图',
控件:ol.control.defaults().extend([
新的ol.control.ScaleLine(),
新的ol.control.ZoomSlider()
]),
渲染器:“画布”,
图层:[基本图层、矢量图层、农民图层],
视图:视图
});
//////////样式功能和鼠标悬停在颜色更改上/////////////
var highlightStyleCache={};
var featureOverlay=新ol.layer.Vector({
source:new ol.source.Vector(),
地图:地图,
样式:功能(特征、分辨率){
var text=分辨率<5000?特征.get('NAME_3'):'';
如果(!highlightStyleCache[text]){
highlightStyleCache[text]=新的ol.style.style({
笔划:新的ol风格笔划({
颜色:“#f00”,
宽度:1
}),
填充:新的ol.style.fill({
颜色:“rgba(255,0,0,0.1)”
}),
文本:新的ol.style.text({
字体:“12px Calibri,无衬线”,
文本:文本,
填充:新的ol.style.fill({
颜色:'#f00'
})
})
});
}
返回highlightStyleCache[text];
}
});
var高亮显示;
var displayFeatureInfo=函数(像素){
var feature=map.forEachFeatureAtPixel(像素,函数(特征){
返回特性;
});
如果(功能!==高亮显示){
如果(突出显示){
featureOverlay.getSource().removeFeature(高亮显示);
}
如果(功能){
featureOverlay.getSource().addFeature(feature);
}
突出显示=特征;
}
};
map.on('pointermove',函数(evt){
如果(evt.拖动){
返回;
}
var pixel=map.getEventPixel(evt.originalEvent);
displayFeatureInfo(像素);
});
映射打开('click',函数(evt){
displayFeatureInfo(evt.像素);
});
//////////结束样式设置功能并将鼠标悬停在颜色更改上/////////////
});
这是我的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;
?>
无法确切确定您遇到了什么问题,但请尝试此操作。您可能需要设置正确的投影,并解析来自服务器的
数据
响应。投影默认为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调用。关于加载器函数的特别说明-在源层上调用clear()时,它将再次触发向量加载器函数:
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数据:不确切地确定您遇到了什么问题,但请尝试此操作。您可能需要设置正确的投影并解析服务器的
数据响应。投影默认为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调用。关于加载器函数的特别说明-在源层上调用clear()时,它将再次触发向量加载器函数:
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数据:data
var insuccess:function(data)
从服务器返回的需要是本文档中概述的geoJSON。到目前为止,您遇到了什么问题??没有从服务器返回数据??已完成,谢谢:)data
var insuccess:function(data)
从服务器返回的数据需要是本文档中概述的geoJSON。到目前为止,您遇到了什么问题??没有从中返回数据