I ask a new question about the problem I have, because I tried it but I don't know how to solve it.
(I'm learning OpenLayers, and I see that it isn't that easy).
Using a html select, I run a PHP query and write a GeoJSON. What I can't do is how to dynamically load the resulting data and update the map every time the query is run. In a previous answer a user told me more or less how to do it, but I don't know how to apply it, if with ajax or that ...
In the HTML, I send by ajax the query I make:
<head>
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function(e){
e.preventDefault();
var data = '&parcel='+$('#parcel').val();
$.ajax({
type:"POST",
dataType: "Json",
url : "functionsPHP/obParcel.php",
data:data,
success:function(response){
if(response.ok){
datos = data.data;
}else{
alert('no data!');
}
}
});
$("#formParcel")[0].reset();
})
})
</script>
</head>
<body>
<form id="formParcel" name="parcelchooser" method="post" onSubmit="return false;">
<div class="col caja">
<select id="parcel" name="parcel">
<option value="">Select option...</option>
<?php include "functionsPHP/parcels.php" ?>
</select>
</div>
<input type="submit" value="OK" class="button"></input>
</form>
</body>
The PHP query:
require("db_config.php");
$conexion = "host=$db_host port=$db_port dbname=$db_name user=$db_user password=$db_pass";
$dbconn = pg_connect($conexion);
if (!$dbconn){
echo "<center>Error DB conection!</center>";
exit;
}
$parcel = $_POST['parcel'];
$parcel = str_replace("#",",",$parcel);
$query = "SELECT id, cadastralc, od, poligon, parcel, longitude,latitude, ST_AsGeoJSON(geom, 7) AS geojson FROM parcelsWHERE considered = 'Yes' AND id = '$parcel'";
$result = pg_query($dbconn, $query) or die('Query failed: ' . pg_last_error());
$rows = pg_num_rows($result);
// Mi variable de respuesta
$respuesta = array();
if ($rows != 0){
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
$i = 0;
while ($line = pg_fetch_assoc($result)) {
$feature = array(
'type' => 'Feature',
'geometry' => json_decode($line['geojson'], true),
'properties' => $data[]=$line,
'id' => $i++
);
array_push($geojson['features'], $feature);
}
$observa = json_encode($geojson);
$response["ok"] = true;
$response["data"] = $observation;
$response["menssage"] = "Send";
$response["status"] = 200;
$filename = "../data/parcels.json";
$archivo = fopen($filename, "w");
fwrite($file, $observation);
fclose($file);
}else {
$response["ok"] = false;
$response["menssage"] = "No data";
$response["status"] = 200;
}
echo json_encode($response);
pg_free_result($result);
pg_close($dbconn);
This is the script where I define the map and load the GeoJSON.
var styles = {
'MultiPolygon': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 3,
}),
fill: new ol.style.Fill({
color: 'rgba(255, 255, 0, 1)',
}),
}),
};
var styleFunction = function (feature) {
return styles[feature.getGeometry().getType()];
};
var osm = new ol.layer.Tile({
title: "OSM",
//baseLayer:true,
source: new ol.source.OSM(),
visible:true,
displayInLayerSwitcher:true,
preview: "images/logo_OSM.png"
});
//The @Eoin response
var vectorParcels = new ol.source.Vector({
format: new ol.format.GeoJSON(),
loader: function(extent, resolution, projection) {
var proj = projection.getCode();
var xhr = new XMLHttpRequest();
xhr.open('POST', "functionsPHP/obParcel.php");
var onError = function() {
vectorParcels.removeLoadedExtent(extent);
}
xhr.onerror = onError;
xhr.onload = function() {
xhr.responseText;
if (xhr.status == 200) {
vectorParcels.addFeatures(
vectorParcels.getFormat().readFeatures(xhr.responseText));
vectorParcels.refresh();
} else {
onError();
}
}
xhr.send();
},
});
var vectorlayer = new ol.layer.Vector({
source:vectorParcels
});
var view = new ol.View({
projection: projection,
zoom:5.6,
center: [984934.497931, 5074393.544263]
});
var map= new ol.Map({
target: 'map',
view:view,
layers: [osm, vectorlayer],
controls: ol.control.defaults({
zoom: false,
attribution: false,
rotate: false,
}),
});
map.addControl (new ol.control.ScaleLine({
units:'metric',
minWidth:100
})
);
var zoomslider = new ol.control.ZoomSlider();
//zoomslider.Target(document.getElementById('EP'));
map.addControl(zoomslider);
var zoomExt = new ol.control.ZoomToExtent({
extent: [-514454.2,4072762.7, 2856113.0,6173863.8],
className:'ext'
})
mainbar.addControl(zoomExt);
var mousePosition = new ol.control.MousePosition({
coordinateFormat: function(coordinates){
var coord_x = coordinates[0].toFixed(3);
var coord_y = coordinates[1].toFixed(3);
return 'Lon: ' + coord_x + ' | ' + 'Lat: ' + coord_y;
},
projection: 'EPSG:3857',
target: document.getElementById('myposition'),
undefinedHTML: ' '
});
map.addControl(mousePosition);
I'm POSTing the selected field, and I get the GeoJSON in the html form. The header that sends, for example is, parcel: 2 but that data should not be collected by (the @Eoin response) instead of sending it by the post I put in the form?
//The @Eoin response
var vectorParcels = new ol.source.Vector({
format: new ol.format.GeoJSON(),
loader: function(extent, resolution, projection) {
var proj = projection.getCode();
var xhr = new XMLHttpRequest();
xhr.open('POST', "functionsPHP/obParcel.php");
var onError = function() {
vectorParcels.removeLoadedExtent(extent);
}
...