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); } }
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 ""; } } } }
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()); // 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']); $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); }
$properties->layers = array(); //process header('Content-type: application/json'); header('X-JSON: true'); $layers = $selection->GetLayers(); $result = NULL; if ($layers != null) { $nLayers = $layers->GetCount(); // echo "/* nLayers:".$nLayers."*/"; for ($i = 0; $i < $nLayers; $i++) { $oLayer = $layers->GetItem($i); $featureResId = new MgResourceIdentifier($oLayer->GetFeatureSourceId()); /* the class that is used for this layer will be used to select features */ $class = $oLayer->GetFeatureClassName(); /* select the features */ $queryOptions = new MgFeatureQueryOptions(); $geomName = $oLayer->GetFeatureGeometryName(); //TODO : seems that property mapping breaks the selection ???? //could it be that $selection->AddFeatures($layerObj, $featureReader, 0) is //the one causing a problem when the properies are limited ? if (isset($_SESSION['property_mappings']) && isset($_SESSION['property_mappings'][$oLayer->GetObjectId()])) { $mappings = $_SESSION['property_mappings'][$oLayer->GetObjectId()]; } else { //This is normally pre-stashed by LoadMap.php, but if the client is using the new //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) {
$slayer = $map->GetLayers()->GetItem(0); $sel->AddFeatureIdInt32($slayer, "IntKey", 1); $sel->AddFeatureIdInt32($slayer, "IntKey", 10); $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);
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; }
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(); }
$selection = new MgSelection($map, $_POST['SELECTION']); $layers = $selection->GetLayers(); } else { $layers = 0; } // --------------------------------------------------------- // --------------------------------------------------------- // Use the following code for AJAX Viewers only. // This does not require passing selection data via HTTP POST. // // $selection = new MgSelection($map); // $selection->Open($resourceService, $mapName); // $layers = $selection->GetLayers(); // --------------------------------------------------------- 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
$siteConnection->Open($userInfo); $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 1'; } catch (MgException $e) { echo $e->GetExceptionMessage(); echo $e->GetDetails(); }
$measure = $srsDs->GetMeasure(); } else { $measure = null; } // create a SRS transformer if necessary. if ($srsDefDs != $srsDefMap) { $srsXform = $srsFactory->GetTransform($srsDs, $srsMap); } else { $srsXform = null; } $featureClassName = $selLayer->GetFeatureClassName(); $filter = $sel->GenerateFilter($selLayer, $featureClassName); if ($filter == "") { continue; } $query = new MgFeatureQueryOptions(); $query->SetFilter($filter); $featureSource = new MgResourceIdentifier($selLayer->GetFeatureSourceId()); $features = $featureSrvc->SelectFeatures($featureSource, $featureClassName, $query); if ($features->ReadNext()) { $classDef = $features->GetClassDefinition(); $geomPropName = $classDef->GetDefaultGeometryPropertyName(); do { if (strlen($geomPropName) == 0) { $geomPropName = $selLayer->GetFeatureGeometryName(); } $geomReader = $features->GetGeometry($geomPropName); $geom = $agfRW->Read($geomReader); if (!$merge) { $geomBuffer = $geom->Buffer($dist, $measure); if ($geomBuffer != null) {
} else { 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++) {
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"); } }
$featureSourceName = "Session:" . $sessionID . "//" . $layerName . ".FeatureSource"; $featureSourceId = new MgResourceIdentifier($featureSourceName); CreateFeatureSource($map, $featureSourceId, $layerName, $featureService, MgFeatureGeometricType::Surface, $schemaName); //create the output layer definition of poylgon type $layerDefinition = "Session:" . $sessionID . "//" . $layerName . ".LayerDefinition"; $layerId = new MgResourceIdentifier($layerDefinition); BuildLayerContent($resourceService, $layerId, $featureSourceName, $schemaName, $layerName, $fillColor, $borderColor); $layer = new MGLayer($layerId, $resourceService); $layer->SetName($layerName); $layer->SetLegendLabel($layerName); $layer->SetDisplayInLegend(true); $layer->SetSelectable(true); $layers->Insert(0, $layer); } //loop through the selection of the input layer. If no selection, select all features $queryOptions = new MgFeatureQueryOptions(); $selection = new MgSelection($map); $selection->Open($resourceService, $mapName); $selLayers = $selection->GetLayers(); /* if we are merging, put all the geometries into a single geometry collection */ $inputGeometries = new MgGeometryCollection(); /* store the insert commands for creating buffers */ $oCommandsColl = new MgFeatureCommandCollection(); $nCount = $selLayers->GetCount(); for ($i = 0; $i < $nCount; $i++) { $selLayer = $selLayers->GetItem($i); $featureClassName = $selLayer->GetFeatureClassName(); $filter = $selection->GenerateFilter($selLayer, $featureClassName); if ($filter == '') { continue;
private function PutVectorTileXYZ($map, $groupName, $siteConn, $metersPerUnit, $csFactory, $path, $boundsMinx, $boundsMinY, $boundsMaxX, $boundsMaxY, $layerNames) { $wktRw = new MgWktReaderWriter(); $agfRw = new MgAgfReaderWriter(); $resSvc = $siteConn->CreateService(MgServiceType::ResourceService); $featSvc = $siteConn->CreateService(MgServiceType::FeatureService); $mapCsWkt = $map->GetMapSRS(); $layers = $map->GetLayers(); $groups = $map->GetLayerGroups(); $baseGroup = $groups->GetItem($groupName); $layerCount = $layers->GetCount(); $firstFeature = true; $scale = self::GetScaleFromBounds($map, self::XYZ_TILE_WIDTH, self::XYZ_TILE_HEIGHT, $metersPerUnit, $boundsMinx, $boundsMinY, $boundsMaxX, $boundsMaxY); $fp = fopen($path, "w"); fwrite($fp, '{ "type": "FeatureCollection", "features": ['); for ($i = 0; $i < $layerCount; $i++) { $layer = $layers->GetItem($i); $parentGroup = $layer->GetGroup(); if ($parentGroup != null && $parentGroup->GetObjectId() == $baseGroup->GetObjectId()) { if (!self::IsLayerVisibleAtScale($layer, $resSvc, $scale)) { continue; } //If list of layer names specified, skip if this layer is not in that list if ($layerNames != null) { $bFound = false; foreach ($layerNames as $layerName) { if ($layer->GetName() == $layerName) { $bFound = true; break; } } if (!$bFound) { continue; } } $wktPoly = MgUtils::MakeWktPolygon($boundsMinx, $boundsMinY, $boundsMaxX, $boundsMaxY); $geom = $wktRw->Read($wktPoly); $clsDef = $layer->GetClassDefinition(); $clsProps = $clsDef->GetProperties(); $idProps = $clsDef->GetIdentityProperties(); $idName = NULL; if ($idProps->GetCount() == 1) { $idp = $idProps->GetItem(0); $idName = $idp->GetName(); } $fsId = new MgResourceIdentifier($layer->GetFeatureSourceId()); //Set up forward and inverse transforms. Inverse for transforming map bounding box //Forward for transforming source geometries to map space $xform = self::GetTransform($featSvc, $fsId, $clsDef, $mapCsWkt, $csFactory); $query = new MgFeatureQueryOptions(); $geomName = $layer->GetFeatureGeometryName(); if ($xform != null) { $sourceCs = $xform->GetSource(); $targetCs = $xform->GetTarget(); $invXform = $csFactory->GetTransform($targetCs, $sourceCs); $txgeom = $geom->Transform($invXform); $query->SetSpatialFilter($geomName, $txgeom, MgFeatureSpatialOperations::EnvelopeIntersects); } else { $query->SetSpatialFilter($geomName, $geom, MgFeatureSpatialOperations::EnvelopeIntersects); } for ($p = 0; $p < $clsProps->GetCount(); $p++) { $propDef = $clsProps->GetItem($p); $query->AddFeatureProperty($propDef->GetName()); } //If we're rendering a vector tile for a single layer, we don't need these special attributes if ($layerNames == NULL || count($layerNames) > 1) { $query->AddComputedProperty("_displayIndex", $layerCount - $i); $query->AddComputedProperty("_layer", "'" . $layer->GetName() . "'"); $query->AddComputedProperty("_selectable", $layer->GetSelectable() ? "true" : "false"); } $reader = $layer->SelectFeatures($query); $read = 0; while ($reader->ReadNext()) { $read++; if (!$reader->IsNull($geomName)) { if (!$firstFeature) { fwrite($fp, ","); } try { $output = MgGeoJsonWriter::FeatureToGeoJson($reader, $agfRw, $xform, $idName); fwrite($fp, $output); $firstFeature = false; } catch (MgException $ex) { } } } $reader->Close(); } } fwrite($fp, ']}'); fclose($fp); return $path; }
$cmd = new MgInsertFeatures("Buffer", $batchProp); $cmdColl = new MgFeatureCommandCollection(); $cmdColl->Add($cmd); try { $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) {
/** * 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; }
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); } }
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())); } } }
if ($featureReader) { $featureReader->Close(); } } catch (MgException $e) { //what should we do with general exceptions? echo "/*general exception:"; echo "ERROR: " . $e->GetExceptionMessage(); echo $e->GetDetails() . "*/"; if ($featureReader) { $featureReader->Close(); } } } if ($bExtendSelection) { $selection = new MgSelection($map); $queryOptions = new MgFeatureQueryOptions(); $layers = $map->GetLayers(); foreach ($aLayers as $szLayer => $aLayer) { $oLayer = $layers->GetItem($szLayer); foreach ($aLayer as $szClass => $aFilter) { /* get the feature source from the layer */ $featureResId = new MgResourceIdentifier($oLayer->GetFeatureSourceId()); $featureGeometryName = $oLayer->GetFeatureGeometryName(); $szFilter = implode(' OR ', $aFilter); $queryOptions->setFilter($szFilter); /* the class that is used for this layer will be used to select features */ $class = $oLayer->GetFeatureClassName(); /* select the features */ $featureReader = $featureService->SelectFeatures($featureResId, $class, $queryOptions); $selection->AddFeatures($oLayer, $featureReader, $maxFeatures);
// merge them into a single geometry. $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.