Skip to content

Instantly share code, notes, and snippets.

@andrewteg
Last active October 8, 2019 03:33
Show Gist options
  • Save andrewteg/81b8d45948d67003f5f1170e51d66e61 to your computer and use it in GitHub Desktop.
Save andrewteg/81b8d45948d67003f5f1170e51d66e61 to your computer and use it in GitHub Desktop.
MS4W Version 4.0 Query From .MAP File Sample
<html><head><title>query sample</title></head><body><PRE>
<?php
include("C:/ms4w/apps/phpmapscriptng-swig/include/mapscript.php"); // required SWIG include (contains constants for PHP7)
// sample filter strings to search on... OFFICIAL_N is name of field in Attribute Table for Layer
$filter_string = '("[OFFICIAL_N]" == "Gallery")'; //exact (use ==) - case-sensitive
$filter_string = '("[OFFICIAL_N]" ~* "^ga.*")'; //starts Ga (^ for starting) not case-sensitive
$filter_string = '("[OFFICIAL_N]" ~* ".*GA.*")'; //like Ga (.* maybe not needed?!?) not case-sensitive
$map = new mapObj("/ms4w/maps/file.map");
$layer = $map->getLayer(0); //first layer in mapfile
$layer->setFilter($filter_string); //filter results
$layer->template = true; //for historical reasons, the query attribute must be non-NULL for a layer to be queryable RE: https://www.mapserver.org/mapscript/mapscript.html#layerobj-attributes
$ext = $layer->getExtent();
$query = $layer->queryByRect($map, $ext); //must query before getting $layer numitems
$numResults = $layer->getNumResults();
$layername = $layer->name;
$layeritems = $layer->numitems; //count of items in attribute table
//echo 'Layer '.$layername.' has '.$layeritems.' items<br>';
for ($x=0;$x<$layeritems;$x++) {
$layer_headers[$x] = $layer->getItem($x); //for the layer, this gets the attribute field names
}
//print_r($layer_headers);
if($query == MS_SUCCESS) {
echo 'Query has '.$layer->getNumResults().' Results:<br>';
if($layer->getNumResults()>0) {
for ($i=0; $i < $layer->getNumResults(); $i++) {
$result = $layer->getResult($i); //print_r($result);
if($result === FALSE) {
error_log('No result '.$i);
} else {
$shape = $layer->getShape($result); //print_r($shape);
//echo ("#$i OBJECTID = ".$shape->values['OBJECTID'].'<br>'); //ms4w 3.x
//echo 'vals='.$shape->numvalues;
echo ("#$i OBJECTID = ".$shape->getValue(0)); //ms4w 4.x
$vals = array();
echo '<blockquote>';
for ($x=0;$x<$shape->numvalues;$x++) {
//echo $x.'='.$shape->getValue($x).'<br>';
$vals[$layer_headers[$x]] = $shape->getValue($x);
}
print_r($vals);
//echo 'WKT='.$shape->toWKT().'<br>';
print_r($shape->values);
echo '</blockquote>';
}
}
}
} else {
echo('Query Returned No Results');
}
echo '<hr>END<hr>'; ?>
</PRE></body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment