示例#1
0
function MultiGeometryFromSelection($featureSrvc, $map, $selText)
{
    $sel = new MgSelection($map, $selText);
    $selLayers = $sel->GetLayers();
    $geomColl = new MgGeometryCollection();
    $agfRW = new MgAgfReaderWriter();
    $simplyPolygonOnly = true;
    for ($i = 0; $i < $selLayers->GetCount(); $i++) {
        $layer = $selLayers->GetItem($i);
        $filter = $sel->GenerateFilter($layer, $layer->GetFeatureClassName());
        $query = new MgFeatureQueryOptions();
        $query->SetFilter($filter);
        $featureSource = new MgResourceIdentifier($layer->GetFeatureSourceId());
        $features = $featureSrvc->SelectFeatures($featureSource, $layer->GetFeatureClassName(), $query);
        if ($features) {
            $classDef = $features->GetClassDefinition();
            $geomPropName = $classDef->GetDefaultGeometryPropertyName();
            $j = 0;
            while ($features->ReadNext()) {
                $geomReader = $features->GetGeometry($geomPropName);
                $geom = $agfRW->Read($geomReader);
                $type = $geom->GetGeometryType();
                if ($type == MgGeometryType::MultiPolygon || $type == MgGeometryType::CurvePolygon || $type == MgGeometryType::MultiCurvePolygon) {
                    $simplyPolygonOnly = false;
                } else {
                    if ($type != MgGeometryType::Polygon) {
                        continue;
                    }
                }
                $geomColl->Add($geom);
            }
        }
    }
    if ($geomColl->GetCount() == 0) {
        return null;
    }
    $gf = new MgGeometryFactory();
    if ($simplyPolygonOnly) {
        $polyColl = new MgPolygonCollection();
        for ($i = 0; $i < $geomColl->GetCount(); $i++) {
            $polyColl->Add($geomColl->GetItem($i));
        }
        return $gf->CreateMultiPolygon($polyColl);
    } else {
        return $gf->CreateMultiGeometry($geomColl);
    }
}
 public function SelectFeatures($resId, $schemaName, $className, $format)
 {
     //Check for unsupported representations
     $fmt = $this->ValidateRepresentation($format, array("xml", "html", "geojson"));
     $mimeType = $this->GetMimeTypeForFormat($fmt);
     try {
         $sessionId = "";
         if ($resId->GetRepositoryType() == MgRepositoryType::Session) {
             $sessionId = $resId->GetRepositoryName();
         }
         $this->EnsureAuthenticationForSite($sessionId, true, $mimeType);
         $siteConn = new MgSiteConnection();
         $siteConn->Open($this->userInfo);
         $site = $siteConn->GetSite();
         $this->VerifyWhitelist($resId->ToString(), $mimeType, "SELECTFEATURES", $fmt, $site, $this->userName);
         $featSvc = $siteConn->CreateService(MgServiceType::FeatureService);
         $query = new MgFeatureQueryOptions();
         $filter = $this->GetRequestParameter("filter", "");
         $propList = $this->GetRequestParameter("properties", "");
         $orderby = $this->GetRequestParameter("orderby", "");
         $orderOptions = $this->GetRequestParameter("orderoption", "asc");
         $maxFeatures = $this->GetRequestParameter("maxfeatures", "");
         $transformto = $this->GetRequestParameter("transformto", "");
         $bbox = $this->GetRequestParameter("bbox", "");
         $pageSize = $this->GetRequestParameter("pagesize", -1);
         $pageNo = $this->GetRequestParameter("page", -1);
         //Internal debugging flag
         $chunk = $this->GetBooleanRequestParameter("chunk", true);
         if ($pageNo >= 0 && $pageSize === -1) {
             $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "pagesize"), $mimeType);
         }
         if ($filter !== "") {
             $query->SetFilter($filter);
         }
         $limit = -1;
         if ($maxFeatures !== "") {
             $limit = intval($maxFeatures);
         }
         if ($propList !== "") {
             $propNames = explode(",", $propList);
             //If you have a comma in your property names, it's your own fault :)
             foreach ($propNames as $propName) {
                 $query->AddFeatureProperty($propName);
             }
         }
         if ($orderby !== "") {
             $orderPropNames = explode(",", $orderby);
             //If you have a comma in your property names, it's your own fault :)
             $orderProps = new MgStringCollection();
             foreach ($orderPropNames as $propName) {
                 $orderProps->Add($propName);
             }
             $orderOpt = MgOrderingOption::Ascending;
             if (strtolower($orderOptions) === "desc") {
                 $orderOpt = MgOrderingOption::Descending;
             }
             $query->SetOrderingFilter($orderProps, $orderOpt);
         }
         $transform = null;
         if ($transformto !== "") {
             $transform = MgUtils::GetTransform($featSvc, $resId, $schemaName, $className, $transformto);
         }
         if ($bbox !== "") {
             $parts = explode(",", $bbox);
             if (count($parts) == 4) {
                 $wktRw = new MgWktReaderWriter();
                 $geom = $wktRw->Read(MgUtils::MakeWktPolygon($parts[0], $parts[1], $parts[2], $parts[3]));
                 //Transform the bbox if we have the flag indicating so
                 $bboxIsTargetCs = $this->GetBooleanRequestParameter("bboxistargetcs", false);
                 if ($bboxIsTargetCs) {
                     //Because it has been declared the bbox is in target coordiantes, we have to transform that bbox back to the
                     //source, which means we need an inverse transform
                     $invTx = MgUtils::GetTransform($featSvc, $resId, $schemaName, $className, $transformto, true);
                     $geom = $geom->Transform($invTx);
                 }
                 $clsDef = $featSvc->GetClassDefinition($resId, $schemaName, $className);
                 $query->SetSpatialFilter($clsDef->GetDefaultGeometryPropertyName(), $geom, MgFeatureSpatialOperations::EnvelopeIntersects);
             }
         }
         $reader = $featSvc->SelectFeatures($resId, "{$schemaName}:{$className}", $query);
         $owriter = null;
         if ($chunk === "0") {
             $owriter = new MgSlimChunkWriter($this->app);
         } else {
             $owriter = new MgHttpChunkWriter();
         }
         if ($pageSize > 0) {
             if ($pageNo < 1) {
                 $pageNo = 1;
             }
             $pageReader = new MgPaginatedFeatureReader($reader, $pageSize, $pageNo, $limit);
             $result = new MgReaderChunkedResult($featSvc, $pageReader, $limit, $owriter, $this->app->localizer);
         } else {
             $result = new MgReaderChunkedResult($featSvc, $reader, $limit, $owriter, $this->app->localizer);
         }
         $result->CheckAndSetDownloadHeaders($this->app, $format);
         if ($transform != null) {
             $result->SetTransform($transform);
         }
         if ($fmt === "html") {
             $result->SetHtmlParams($this->app);
         }
         $result->Output($format);
     } catch (MgException $ex) {
         $this->OnException($ex, $mimeType);
     }
 }
示例#3
0
    $svc->CreateFeatureSource($id, $params);
    $startTime = microtime(true);
    $props = $svc->UpdateFeatures($id, $cmdColl, false);
    $endTime = microtime(true);
    $diffTime = $endTime - $startTime;
    $reader = $props->GetItem(0)->GetValue();
    while ($reader->ReadNext() == true) {
        $key = $reader->GetInt32("KEY");
    }
    $reader->Close();
    // Now select a few of the feature and make sure we get everything back correctly.
    $query = new MgFeatureQueryOptions();
    $query->AddFeatureProperty("NAME");
    $query->AddFeatureProperty("KEY");
    $query->AddFeatureProperty("GEOM");
    $query->SetFilter("");
    $reader = $svc->SelectFeatures($id, "Buffer", $query);
    while ($reader->ReadNext() == true) {
        $geomText = '';
        $agfStream = $reader->GetGeometry("GEOM");
        $geom = $agf->Read($agfStream);
        $geomText = $wkt->Write($geom);
        echo $reader->GetInt32("KEY") . " " . $reader->GetString("NAME") . " " . $geomText . "\n";
    }
    echo "Time for " . $i . " ops was " . $diffTime . " seconds\n";
    echo "Average throughput of " . $i / $diffTime . " features per second\n";
} catch (MgException $exc) {
    echo "First failure on insert... caught...\n";
    echo $exc->GetExceptionMessage() . "\n";
    echo $exc->GetDetails() . "\n";
    echo $exc->GetStackTrace() . "\n";
示例#4
0
 function GetFileExtension($markupLayerResId)
 {
     $featureService = $this->site->CreateService(MgServiceType::FeatureService);
     $query = new MgFeatureQueryOptions();
     $query->SetFilter("LayerDefinition = '{$markupLayerResId}'");
     $fr = $featureService->SelectFeatures($this->markupRegistryId, "Default:MarkupRegistry", $query);
     $fdoProvider = "";
     if ($fr->ReadNext()) {
         $fdoProvider = $fr->GetString("FdoProvider");
     }
     $fr->Close();
     if (strcmp("OSGeo.SDF", $fdoProvider) == 0) {
         return ".sdf";
     } else {
         if (strcmp("OSGeo.SQLite", $fdoProvider) == 0) {
             return ".sqlite";
         } else {
             if (strcmp("OSGeo.SHP", $fdoProvider) == 0) {
                 return ".zip";
             } else {
                 return "";
             }
         }
     }
 }
示例#5
0
     //CREATERUNTIMEMAP shortcut, this information does not exist yet, so fetch and stash
     $mappings = GetLayerPropertyMappings($resourceService, $oLayer);
     $_SESSION['property_mappings'][$oLayer->GetObjectId()] = $mappings;
 }
 if (count($mappings) > 0) {
     foreach ($mappings as $name => $value) {
         if ($geomName != $name) {
             $queryOptions->AddFeatureProperty($name);
             //echo "$name $value <br>\n";
         }
     }
 }
 //Add geometry property in all cases.
 $queryOptions->AddFeatureProperty($geomName);
 $filter = $selection->GenerateFilter($oLayer, $class);
 $queryOptions->SetFilter($filter);
 $featureReader = $featureService->SelectFeatures($featureResId, $class, $queryOptions);
 //$featureReader = $selection->GetSelectedFeatures($oLayer, $class, true );//this doesn't seem to work but would replace much of the above code
 $layerName = $oLayer->GetName();
 array_push($properties->layers, $layerName);
 // TODO: Check if computed properties are needed?
 $bComputedProperties = false;
 $bNeedsTransform = false;
 $srsLayer = NULL;
 if ($bComputedProperties) {
     $spatialContext = $featureService->GetSpatialContexts($featureResId, true);
     $srsLayerWkt = false;
     if ($spatialContext != null && $spatialContext->ReadNext() != null) {
         $srsLayerWkt = $spatialContext->GetCoordinateSystemWkt();
         /* skip this layer if the srs is empty */
     }
示例#6
0
 $sel->AddFeatureIdInt32($slayer, "IntKey", 20);
 echo "XML FeatureSet is\n" . $sel->ToXml() . "\n";
 echo "\nString Filter: " . $sel->GenerateFilter($slayer, "StringKey") . "\n\n";
 echo "Building Selection from XML\n";
 $sel2 = new MgSelection($map, $sel->ToXml());
 // Test basic methods
 $layerColl = $sel2->GetLayers();
 $newLayer = $layerColl->GetItem(0);
 echo "First layer selected is " . $newLayer->GetName() . "\n";
 echo "BadKey Filter: " . $sel2->GenerateFilter($slayer, "BadKey") . "\n";
 $filter = $sel2->GenerateFilter($slayer, "IntKey");
 echo "\nString Filter: " . $filter . "\n\n";
 $query = new MgFeatureQueryOptions();
 $query->AddFeatureProperty("KEY");
 $query->AddFeatureProperty("NAME");
 $query->SetFilter($filter);
 echo "Selected features\n";
 $reader = $fsvc->SelectFeatures($id, "IntKey", $query);
 while ($reader->ReadNext() == true) {
     echo $reader->GetString("NAME") . "\n";
 }
 echo "MgSelection from Reader\n";
 $reader = $fsvc->SelectFeatures($id, "IntKey", $query);
 $selection = new MgSelection($map);
 $layer1 = $map->GetLayers()->GetItem(0);
 $selection->AddFeatures($layer1, $reader, 0);
 echo $selection->ToXml();
 $envelope = $selection->GetExtents($fsvc);
 $ll = $envelope->GetLowerLeftCoordinate();
 $ur = $envelope->GetUpperRightCoordinate();
 echo "(" . $ll->GetX() . "," . $ll->GetY() . ") - (" . $ur->GetX() . "," . $ur->GetY() . ")\n";
示例#7
0
文件: theme.php 项目: kanbang/Colt
 function GetPropertyMinMaxCount()
 {
     $resourceService = $this->site->CreateService(MgServiceType::ResourceService);
     $map = new MgMap();
     $map->Open($resourceService, $this->args['MAPNAME']);
     $layer = $map->GetLayers()->GetItem($this->args['LAYERNAME']);
     $featureService = $this->site->CreateService(MgServiceType::FeatureService);
     $resId = new MgResourceIdentifier($layer->GetFeatureSourceId());
     $filter = $layer->GetFilter();
     // Note: Should be able to do this:
     //
     //      $minValue = 0;
     //      $maxValue = 0;
     //      $count = 0;
     //
     //      $aggregateOptions = new MgFeatureAggregateOptions();
     //      $aggregateOptions->AddComputedProperty('min', 'Min(' . $this->args['PROPERTYNAME'] . ')');
     //      $aggregateOptions->AddComputedProperty('max', 'Max(' . $this->args['PROPERTYNAME'] . ')');
     //      $aggregateOptions->AddComputedProperty('count', 'Count(' . $this->args['PROPERTYNAME'] . ')');
     //
     //      $dataReader = $featureService->SelectAggregate($resId, $layer->GetFeatureClassName(), $aggregateOptions);
     //
     //      if ($dataReader->ReadNext())
     //      {
     //          $minValue = $this->GetFeaturePropertyValue($dataReader, 'min');
     //          $maxValue = $this->GetFeaturePropertyValue($dataReader, 'max');
     //          $count = $this->GetFeaturePropertyValue($dataReader, 'count');
     //      }
     //      $dataReader->Close();
     //
     // However due to a bug, Min/Max do not work on string types, so we have to do this:
     unset($minValue);
     unset($maxValue);
     $count = 0;
     $queryOptions = new MgFeatureQueryOptions();
     $queryOptions->AddFeatureProperty($this->args['PROPERTYNAME']);
     if ($filter != '') {
         $queryOptions->SetFilter($filter);
     }
     $featureReader = $featureService->SelectFeatures($resId, $layer->GetFeatureClassName(), $queryOptions);
     while ($featureReader->ReadNext()) {
         $value = $this->GetFeaturePropertyValue($featureReader, $this->args['PROPERTYNAME']);
         if ($value != null) {
             if (!isset($maxValue) && !isset($minValue)) {
                 $maxValue = $value;
                 $minValue = $value;
             }
             if ($value > $maxValue) {
                 $maxValue = $value;
             }
             if ($value < $minValue) {
                 $minValue = $value;
             }
         }
         $count++;
     }
     $featureReader->Close();
     if (!isset($maxValue) && !isset($minValue)) {
         $maxValue = "";
         $minValue = "";
     }
     return array($minValue, $maxValue, $count);
 }
示例#8
0
 private function TranslateToSelectionXml($siteConn, $mapName, $featFilter, $bAppend)
 {
     $resSvc = $siteConn->CreateService(MgServiceType::ResourceService);
     $map = new MgMap($siteConn);
     $map->Open($mapName);
     $sel = new MgSelection($map);
     $layers = $map->GetLayers();
     //If appending, load the current selection first
     if ($bAppend) {
         $sel->Open($resSvc, $mapName);
     }
     $doc = new DOMDocument();
     $doc->loadXML($featFilter);
     /*
             Document structure
             
             /SelectionUpdate
        /Layer
            /Name
            /Feature [0...n]
                /ID
                    /Name
                    /Value
            /SelectionFilter [0...n]
     */
     $root = $doc->documentElement;
     if ($root->tagName != "SelectionUpdate") {
         $this->BadRequest($this->app->localizer->getText("E_INVALID_DOCUMENT"), MgMimeType::Xml);
     }
     $layerNodes = $root->childNodes;
     for ($i = 0; $i < $layerNodes->length; $i++) {
         $layerNode = $layerNodes->item($i);
         if ($layerNode->tagName == "Layer") {
             //$this->app->log->debug("Found //SelectionUpdate/Layer");
             $featureNodes = $layerNode->childNodes;
             for ($j = 0; $j < $featureNodes->length; $j++) {
                 $featureNode = $featureNodes->item($j);
                 if ($featureNode->tagName == "Name") {
                     //$this->app->log->debug("Found //SelectionUpdate/Layer/Name");
                     $layerName = $featureNode->nodeValue;
                     $lidx = $layers->IndexOf($layerName);
                     if ($lidx < 0) {
                         $this->BadRequest($this->app->localizer->getText("E_LAYER_NOT_FOUND_IN_MAP", $layerName), MgMimeType::Xml);
                     }
                     $layer = $layers->GetItem($lidx);
                     $clsDef = $layer->GetClassDefinition();
                     $clsIdProps = $clsDef->GetIdentityProperties();
                 } else {
                     if ($featureNode->tagName == "SelectionFilter") {
                         $query = new MgFeatureQueryOptions();
                         $query->SetFilter($featureNode->nodeValue);
                         $fr = $layer->SelectFeatures($query);
                         $sel->AddFeatures($layer, $fr, 0);
                     } else {
                         if ($featureNode->tagName == "Feature") {
                             //$this->app->log->debug("Found //SelectionUpdate/Layer/Feature");
                             $idNodes = $featureNode->childNodes;
                             if ($idNodes->length == 1) {
                                 $idNode = $idNodes->item(0);
                                 if ($idNode->tagName == "ID") {
                                     //$this->app->log->debug("Found //SelectionUpdate/Layer/Feature/ID");
                                     $nameNode = null;
                                     $valueNode = null;
                                     for ($nv = 0; $nv < $idNode->childNodes->length; $nv++) {
                                         $children = $idNode->childNodes;
                                         $child = $children->item($nv);
                                         if ($child->tagName == "Name") {
                                             //$this->app->log->debug("Found //SelectionUpdate/Layer/Feature/ID/Name");
                                             $nameNode = $child;
                                         } else {
                                             if ($child->tagName == "Value") {
                                                 //$this->app->log->debug("Found //SelectionUpdate/Layer/Feature/ID/Value");
                                                 $valueNode = $child;
                                             }
                                         }
                                     }
                                     //Name/Value nodes must be specified
                                     if ($nameNode == null || $valueNode == null) {
                                         $this->BadRequest($this->app->localizer->getText("E_INVALID_DOCUMENT"), MgMimeType::Xml);
                                     }
                                     //Property must exist
                                     $pidx = $clsIdProps->IndexOf($nameNode->nodeValue);
                                     if ($pidx < 0) {
                                         $this->BadRequest($this->app->localizer->getText("E_PROPERTY_NOT_FOUND_IN_CLASS", $nameNode->nodeValue, $clsDef->GetName()), MgMimeType::Xml);
                                     }
                                     $propDef = $clsIdProps->GetItem($pidx);
                                     $value = $valueNode->nodeValue;
                                     $propType = $propDef->GetDataType();
                                     //$this->app->log->debug("Value is: $value");
                                     //$this->app->log->debug("Property type: $propType");
                                     switch ($propType) {
                                         case MgPropertyType::Int16:
                                             //$this->app->log->debug("=== ADD INT16: $value ===");
                                             $sel->AddFeatureIdInt16($layer, $layer->GetFeatureClassName(), intval($value));
                                             break;
                                         case MgPropertyType::Int32:
                                             //$this->app->log->debug("=== ADD INT32: $value ===");
                                             $sel->AddFeatureIdInt32($layer, $layer->GetFeatureClassName(), intval($value));
                                             break;
                                         case MgPropertyType::Int64:
                                             //$this->app->log->debug("=== ADD INT64: $value ===");
                                             $sel->AddFeatureIdInt64($layer, $layer->GetFeatureClassName(), intval($value));
                                             break;
                                         case MgPropertyType::String:
                                             //$this->app->log->debug("=== ADD STRING: $value ===");
                                             $sel->AddFeatureIdString($layer, $layer->GetFeatureClassName(), $value);
                                             break;
                                         case MgPropertyType::Single:
                                         case MgPropertyType::Double:
                                             //$this->app->log->debug("=== ADD DOUBLE: $value ===");
                                             $sel->AddFeatureIdInt64($layer, $layer->GetFeatureClassName(), floatval($value));
                                             break;
                                             //case MgPropertyType::DateTime:
                                             //    break;
                                     }
                                 }
                             } else {
                                 if ($idNodes->length > 1) {
                                     throw new Exception($this->app->localizer->getText("E_MULTIPLE_IDENTITY_PROPS_NOT_SUPPORTED"));
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return $sel->ToXml();
 }
示例#9
0
    $map = new MgMap($siteConnection);
    $map->Open($mapName);
    // Get the geometry for the boundaries of District 1
    $districtQuery = new MgFeatureQueryOptions();
    $districtQuery->SetFilter("Autogenerated_SDF_ID = 1");
    $layer = $map->GetLayers()->GetItem('Districts');
    $featureReader = $layer->SelectFeatures($districtQuery);
    $featureReader->ReadNext();
    $districtGeometryData = $featureReader->GetGeometry('Data');
    // Convert the AGF binary data to MgGeometry.
    $agfReaderWriter = new MgAgfReaderWriter();
    $districtGeometry = $agfReaderWriter->Read($districtGeometryData);
    // Create a filter to select the desired features. Combine
    // a basic filter and a spatial filter.
    $queryOptions = new MgFeatureQueryOptions();
    $queryOptions->SetFilter("RNAME LIKE 'SCHMITT%'");
    $queryOptions->SetSpatialFilter('SHPGEOM', $districtGeometry, MgFeatureSpatialOperations::Inside);
    // Get the features from the feature source,
    // turn it into a selection, then save the selection as XML.
    $layer = $map->GetLayers()->GetItem('Parcels');
    $featureReader = $layer->SelectFeatures($queryOptions);
    $layer = $map->GetLayers()->GetItem('Parcels');
    $selection = new MgSelection($map);
    $selection->AddFeatures($layer, $featureReader, 0);
    $selectionXml = $selection->ToXml();
    echo 'Selecting parcels owned by Schmitt in District&nbsp;1';
} catch (MgException $e) {
    echo $e->GetExceptionMessage();
    echo $e->GetDetails();
}
?>
示例#10
0
 /**
  * Queries the configured feature source and returns a MgReader based on the current GET query parameters and adapter configuration
  */
 protected function CreateQueryOptions($single)
 {
     $query = new MgFeatureQueryOptions();
     $this->EnsureQualifiedClassName();
     $tokens = explode(":", $this->className);
     $clsDef = null;
     $clsDef = $this->featSvc->GetClassDefinition($this->featureSourceId, $tokens[0], $tokens[1]);
     if ($single === true) {
         if ($this->featureId == null) {
             throw new Exception($this->app->localizer->getText("E_NO_FEATURE_ID_SET"));
         }
         $idType = MgPropertyType::String;
         if ($this->featureIdProp == null) {
             $idProps = $clsDef->GetIdentityProperties();
             if ($idProps->GetCount() == 0) {
                 throw new Exception($this->app->localizer->getText("E_CANNOT_QUERY_NO_ID_PROPS", $this->className, $this->featureSourceId->ToString()));
             } else {
                 if ($idProps->GetCount() > 1) {
                     throw new Exception($this->app->localizer->getText("E_CANNOT_QUERY_MULTIPLE_ID_PROPS", $this->className, $this->featureSourceId->ToString()));
                 } else {
                     $idProp = $idProps->GetItem(0);
                     $this->featureIdProp = $idProp->GetName();
                     $idType = $idProp->GetDataType();
                 }
             }
         } else {
             $props = $clsDef->GetProperties();
             $iidx = $props->IndexOf($this->featureIdProp);
             if ($iidx >= 0) {
                 $propDef = $props->GetItem($iidx);
                 if ($propDef->GetPropertyType() != MgFeaturePropertyType::DataProperty) {
                     throw new Exception($this->app->localizer->getText("E_ID_PROP_NOT_DATA", $this->featureIdProp));
                 }
             } else {
                 throw new Exception($this->app->localizer->getText("E_ID_PROP_NOT_FOUND", $this->featureIdProp));
             }
         }
         if ($idType == MgPropertyType::String) {
             $query->SetFilter($this->featureIdProp . " = '" . $this->featureId . "'");
         } else {
             $query->SetFilter($this->featureIdProp . " = " . $this->featureId);
         }
     } else {
         $flt = $this->app->request->get("filter");
         if ($flt != null) {
             $query->SetFilter($flt);
         }
         $bbox = $this->app->request->get("bbox");
         if ($bbox != null) {
             $parts = explode(",", $bbox);
             if (count($parts) == 4) {
                 $wktRw = new MgWktReaderWriter();
                 $geom = $wktRw->Read(MgUtils::MakeWktPolygon($parts[0], $parts[1], $parts[2], $parts[3]));
                 $query->SetSpatialFilter($clsDef->GetDefaultGeometryPropertyName(), $geom, MgFeatureSpatialOperations::EnvelopeIntersects);
             }
         }
     }
     if (isset($this->app->ComputedProperties)) {
         $compProps = $this->app->ComputedProperties;
         foreach ($compProps as $alias => $expression) {
             $this->computedPropertyList[$alias] = $expression;
         }
     }
     $bAppliedComputedProperties = false;
     if (count($this->computedPropertyList) > 0) {
         foreach ($this->computedPropertyList as $alias => $expression) {
             $query->AddComputedProperty($alias, $expression);
             $bAppliedComputedProperties = true;
         }
     }
     //If computed properties were applied, add all properties from the class definition if no
     //explicit property list supplied
     if ($bAppliedComputedProperties && count($this->propertyList) == 0) {
         $clsProps = $clsDef->GetProperties();
         for ($i = 0; $i < $clsProps->GetCount(); $i++) {
             $propDef = $clsProps->GetItem($i);
             $query->AddFeatureProperty($propDef->GetName());
         }
     } else {
         if (count($this->propertyList) > 0) {
             foreach ($this->propertyList as $propName) {
                 $query->AddFeatureProperty($propName);
             }
         }
     }
     $orderby = $this->app->request->get("orderby");
     $orderOptions = $this->app->request->get("orderoption");
     if ($orderby != null) {
         if ($orderOptions == null) {
             $orderOptions = "asc";
         }
         $orderPropNames = explode(",", $orderby);
         //If you have a comma in your property names, it's your own fault :)
         $orderProps = new MgStringCollection();
         foreach ($orderPropNames as $propName) {
             $orderProps->Add($propName);
         }
         $orderOpt = MgOrderingOption::Ascending;
         if (strtolower($orderOptions) === "desc") {
             $orderOpt = MgOrderingOption::Descending;
         }
         $query->SetOrderingFilter($orderProps, $orderOpt);
     }
     return $query;
 }
示例#11
0
    // ---------------------------------------------------------
    if ($layers) {
        $queryOptions = new MgFeatureQueryOptions();
        for ($i = 0; $i < $layers->GetCount(); $i++) {
            // Only check selected features in the Parcels layer.
            $layer = $layers->GetItem($i);
            if ($layer && $layer->GetName() == 'Parcels') {
                // Create a filter containing the IDs of the selected features on this layer
                $layerClassName = $layer->GetFeatureClassName();
                $selectionString = $selection->GenerateFilter($layer, $layerClassName);
                // Get the feature resource for the selected layer
                $layerFeatureId = $layer->GetFeatureSourceId();
                $layerFeatureResource = new MgResourceIdentifier($layerFeatureId);
                // Apply the filter to the feature resource for the selected layer. This returns
                // an MgFeatureReader of all the selected features.
                $queryOptions->SetFilter($selectionString);
                $featureReader = $featureService->SelectFeatures($layerFeatureResource, $layerClassName, $queryOptions);
                // Process each item in the MgFeatureReader, displaying the owner name
                while ($featureReader->ReadNext()) {
                    $val = $featureReader->GetString('NAME') . '<br />&nbsp;&nbsp;' . $featureReader->GetString('RPROPAD');
                    echo $val . '<br />';
                }
            }
        }
    } else {
        echo 'No selected layers';
    }
    echo '</p>';
} catch (MgException $e) {
    echo '<p>' . $e->GetExceptionMessage() . '</p>';
    echo '<p>' . $e->GetDetails() . '</p>';
示例#12
0
文件: search.php 项目: kanbang/Colt
     if (get_magic_quotes_gpc() == "1") {
         //Unescape single quotes
         $filter = str_replace("\\'", "'", $filter);
         //Unescape double quotes
         $filter = str_replace('\\"', '"', $filter);
         //remove additional backslash
         $filter = str_replace("\\", "", $filter);
     }
 }
 //substitute the input tag with the actual user input to make up the filter
 $filter = str_replace('$USER_VARIABLE', $userInput, $filter);
 //parse the match label string, which defines what columns to be displayed
 $displayAll = count($resProps) == 0;
 //query the features
 $opts = new MgFeatureQueryOptions();
 $opts->SetFilter($filter);
 $featureClassName = $layer->GetFeatureClassName();
 $srcId = new MgResourceIdentifier($layer->GetFeatureSourceId());
 $features = $featureSrvc->SelectFeatures($srcId, $featureClassName, $opts);
 $hasResult = $features->ReadNext();
 if ($hasResult) {
     $colCount = $displayAll ? $features->GetPropertyCount() : count($resProps);
     //output the beginning of the document (head section and beginning of body section)
     $templ = file_get_contents("../viewerfiles/search.templ");
     $templ = Localize($templ, $locale, GetClientOS());
     print sprintf($templ, $colCount, $target, $popup);
     $classDef = $features->GetClassDefinition();
     $idProps = $classDef->GetIdentityProperties();
     $idPropNames = array();
     for ($j = 0; $j < $idProps->GetCount(); $j++) {
         $idProp = $idProps->GetItem($j);
示例#13
0
 function SelectFeatures($paramSet)
 {
     try {
         $repId = null;
         $this->unitTestParamVm->Execute("Select ParamValue from Params WHERE ParamSet={$paramSet} AND ParamName=\"RESOURCEID\"");
         $this->arrayParam["RESOURCEID"] = $this->unitTestParamVm->GetString("ParamValue");
         $this->unitTestParamVm->Execute("Select ParamValue from Params WHERE ParamSet={$paramSet} AND ParamName=\"CLASSNAME\"");
         $this->arrayParam["CLASSNAME"] = $this->unitTestParamVm->GetString("ParamValue");
         //TODO: used the value retrieved from the database to create the MgStringCollection object
         if (SQLITE_ROW == $this->unitTestParamVm->Execute("Select ParamValue from Params WHERE ParamSet={$paramSet} AND ParamName=\"PROPERTIES\"")) {
             $this->arrayParam["PROPERTIES"] = $this->unitTestParamVm->GetString("ParamValue");
         }
         if (SQLITE_ROW == $this->unitTestParamVm->Execute("Select ParamValue from Params WHERE ParamSet={$paramSet} AND ParamName=\"FILTER\"")) {
             $this->arrayParam["FILTER"] = $this->unitTestParamVm->GetString("ParamValue");
         }
         $queryOptions = new MgFeatureQueryOptions();
         //TODO: Set query options
         if (array_key_exists("FILTER", $this->arrayParam)) {
             $queryOptions->SetFilter($this->arrayParam["FILTER"]);
         }
         //PROPERTIES should be stored in the database as comma separated string without spaces
         if (array_key_exists("PROPERTIES", $this->arrayParam)) {
             $stringArray = explode(",", $this->arrayParam["PROPERTIES"]);
             for ($i = 0; $i < count($stringArray); $i++) {
                 $queryOptions->AddFeatureProperty($stringArray[$i]);
             }
         }
         if (array_key_exists("RESOURCEID", $this->arrayParam)) {
             $repId = new MgResourceIdentifier($this->arrayParam["RESOURCEID"]);
         }
         $featureReader = $this->featureSrvc->SelectFeatures($repId, $this->arrayParam['CLASSNAME'], $queryOptions);
         $byteReader = $featureReader->ToXml();
         $featureReader->Close();
         return Utils::GetResponse($byteReader);
     } catch (MgException $e) {
         return new Result(get_class($e), "text/plain");
     } catch (SqliteException $s) {
         return new Result($s->GetExceptionMessage(), "text/plain");
     }
 }
示例#14
0
文件: query.php 项目: kanbang/Colt
 function Execute()
 {
     $result = array();
     $resourceService = $this->site->CreateService(MgServiceType::ResourceService);
     $map = new MgMap();
     $map->Open($resourceService, $this->args['MAPNAME']);
     $layer = $map->GetLayers()->GetItem($this->args['LAYERNAME']);
     $featureService = $this->site->CreateService(MgServiceType::FeatureService);
     $resId = new MgResourceIdentifier($layer->GetFeatureSourceId());
     $featureClass = $layer->GetFeatureClassName();
     $featureGeometry = $layer->GetFeatureGeometryName();
     // Initialize the coordinate system transform
     $schemaAndClass = explode(":", $featureClass);
     $classDef = $featureService->GetClassDefinition($resId, $schemaAndClass[0], $schemaAndClass[1]);
     $geomProp = $classDef->GetProperties()->GetItem($featureGeometry);
     $spatialContext = $geomProp->GetSpatialContextAssociation();
     $csTransform = null;
     $csInverseTransform = null;
     $coordSysFactory = new MgCoordinateSystemFactory();
     $scReader = $featureService->GetSpatialContexts($resId, false);
     while ($scReader->ReadNext() && $csTransform == null) {
         if ($scReader->GetName() == $spatialContext) {
             $source = $coordSysFactory->Create($scReader->GetCoordinateSystemWkt());
             $target = $coordSysFactory->Create($map->GetMapSRS());
             $csTransform = new MgCoordinateSystemTransform($source, $target);
             $csInverseTransform = new MgCoordinateSystemTransform($target, $source);
         }
     }
     $scReader->Close();
     // Execute the query
     $queryMax = (int) $this->args['QUERYMAX'];
     $queryOptions = new MgFeatureQueryOptions();
     if ($this->args['USEPROPERTYFILTER'] == 'true') {
         $propertyFilter = $this->args['PROPERTYNAME'];
         if ($this->args['ISSTRING'] == 'true') {
             $propertyFilter .= sprintf($this->strExpressions[$this->args['OPERATOR']], $this->args['VALUE']);
         } else {
             $propertyFilter .= sprintf($this->numExpressions[$this->args['OPERATOR']], $this->args['VALUE']);
         }
         $queryOptions->SetFilter($propertyFilter);
     }
     if ($this->args['USESPATIALFILTER'] == 'true') {
         $polygon = $this->CreatePolygonFromGeomText($this->args['GEOMTEXT']);
         $polygon = $polygon->Transform($csInverseTransform);
         $queryOptions->SetSpatialFilter($featureGeometry, $polygon, MgFeatureSpatialOperations::Intersects);
     }
     $count = 0;
     $geometryReaderWriter = new MgAgfReaderWriter();
     $featureReader = $featureService->SelectFeatures($resId, $layer->GetFeatureClassName(), $queryOptions);
     while ($featureReader->ReadNext() && ($queryMax <= 0 || $count < $queryMax)) {
         $displayValue = $this->GetFeaturePropertyValue($featureReader, $this->args['OUTPUTPROPERTY']);
         $byteReader = $featureReader->GetGeometry($featureGeometry);
         $geometry = $geometryReaderWriter->Read($byteReader);
         $centerPoint = $geometry->GetCentroid();
         $centerPoint = $centerPoint->Transform($csTransform);
         $idList = $this->GetFeatureIdList($map, $layer, $featureReader);
         array_push($result, new Feature($displayValue, $centerPoint, $idList));
         $count++;
     }
     return $result;
 }
示例#15
0
 private function LoadRelatedFeatures($reader, $related)
 {
     //Set up queries for any relations that are defined
     foreach ($this->relations as $relName => $rel) {
         $relFilterParts = array();
         $bQuery = false;
         //At least one source property must have a value before we continue because finding related
         //records where sourceID is null in target is kind of pointless
         foreach ($rel->KeyMap as $sourceProp => $targetProp) {
             if (!$reader->IsNull($sourceProp)) {
                 $value = self::GetPropertyValue($reader, $sourceProp);
                 if ($value !== "") {
                     $bQuery = true;
                     if ($reader->GetPropertyType($sourceProp) == MgPropertyType::String) {
                         array_push($relFilterParts, "\"{$targetProp}\" = '{$value}'");
                     } else {
                         array_push($relFilterParts, "\"{$targetProp}\" = {$value}");
                     }
                 } else {
                     if ($reader->GetPropertyType($sourceProp) == MgPropertyType::String) {
                         array_push($relFilterParts, "\"{$targetProp}\" = ''");
                     } else {
                         array_push($relFilterParts, "\"{$targetProp}\" NULL");
                     }
                 }
             } else {
                 array_push($relFilterParts, "\"{$targetProp}\" NULL");
             }
         }
         if ($bQuery === false) {
             continue;
         }
         //Fire off related query and stash in map for template
         $relQuery = new MgFeatureQueryOptions();
         $relFilter = implode(" AND ", $relFilterParts);
         $relQuery->SetFilter($relFilter);
         try {
             $relReader = $this->featSvc->SelectFeatures($rel->FeatureSource, $rel->FeatureClass, $relQuery);
             $related->Add($relName, new MgFeatureReaderModel(new MgFormatterSet($this->app), $relReader, -1, 0, null));
         } catch (MgException $ex) {
             throw new Exception($this->app->localizer->getText("E_QUERY_SETUP", $relFilter, $ex->GetDetails()));
         }
     }
 }
示例#16
0
文件: Query.php 项目: kanbang/Colt
 //TODO: need this for DWF or Grid layers?
 $xpathQuery = $xpathObj->query($xpathStr);
 $layerFilter = '';
 if ($xpathQuery->length > 0) {
     $layerFilter = $xpathQuery->item(0)->nodeValue;
 }
 /* create the combined filter value*/
 $combinedFilter = '';
 if ($filter != '' && $layerFilter != '') {
     $combinedFilter = "(" . $filter . ") AND (" . $layerFilter . ")";
 } else {
     $combinedFilter = $filter . $layerFilter;
 }
 if ($combinedFilter != '') {
     //echo "/* setting combinedFilter:".$combinedFilter."*/";
     $queryOptions->SetFilter($combinedFilter);
 }
 if ($spatialFilter !== false) {
     $spatialContext = $featureService->GetSpatialContexts($featureResId, true);
     $srsLayerWkt = false;
     if ($spatialContext != null && $spatialContext->ReadNext() != null) {
         $srsLayerWkt = $spatialContext->GetCoordinateSystemWkt();
         /* skip this layer if the srs is empty */
     }
     if ($srsLayerWkt == null) {
         $srsLayerWkt = $srsDefMap;
     }
     /* create a coordinate system from the layer's SRS wkt */
     $srsLayer = $srsFactory->Create($srsLayerWkt);
     $verMajor = subStr(GetSiteVersion(), 0, 1);
     if ($verMajor == '1') {
示例#17
0
 $inputGeometries = new MgGeometryCollection();
 while ($featureReader->ReadNext()) {
     $featureGeometryData = $featureReader->GetGeometry('SHPGEOM');
     $featureGeometry = $agfReaderWriter->Read($featureGeometryData);
     $inputGeometries->Add($featureGeometry);
 }
 $geometryFactory = new MgGeometryFactory();
 $mergedGeometries = $geometryFactory->CreateMultiGeometry($inputGeometries);
 // Create a buffer from the merged geometries
 $bufferDist = $srs->ConvertMetersToCoordinateSystemUnits($bufferRingSize);
 $bufferGeometry = $mergedGeometries->Buffer($bufferDist, $srsMeasure);
 // Create a filter to select parcels within the buffer. Combine
 // a basic filter and a spatial filter to select all parcels
 // within the buffer that are of type "MFG".
 $queryOptions = new MgFeatureQueryOptions();
 $queryOptions->SetFilter("RTYPE = 'MFG'");
 $queryOptions->SetSpatialFilter('SHPGEOM', $bufferGeometry, MgFeatureSpatialOperations::Inside);
 /*
 // Old way, pre MapGuide OS 2.0. Kept here for reference
 $featureResId = new MgResourceIdentifier("Library://Samples/Sheboygan/Data/Parcels.FeatureSource");
 $featureReader = $featureService->SelectFeatures($featureResId, "Parcels", $queryOptions);
 */
 // New way, post MapGuide OS 2.0
 $featureReader = $layer->SelectFeatures($queryOptions);
 // Get the features from the feature source,
 // determine the centroid of each selected feature, and
 // add a point to the ParcelMarker layer to mark the
 // centroid.
 // Collect all the points into an MgFeatureCommandCollection,
 // so they can all be added in one operation.
 $parcelMarkerCommands = new MgFeatureCommandCollection();