function GetMapLayerNames() { $layerNames = array(); $resourceService = $this->site->CreateService(MgServiceType::ResourceService); $map = new MgMap($this->site); $map->Open($this->args['MAPNAME']); $layers = $map->GetLayers(); for ($i = 0; $i < $layers->GetCount(); $i++) { $layer = $layers->GetItem($i); //TODO: Exclude Raster and Drawing Layers??? if((substr($layer->GetName(), 0, 1) != "_") && (substr(strtoupper($layer->GetFeatureSourceId()), 0, 7) != "SESSION") && ($layer->IsVisible()) && $layer->GetSelectable()) { $layerNames[$layer->GetName()] = $layer->GetLegendLabel(); } } asort($layerNames); return $layerNames; }
function GetSelectionXML() { $json = new Services_JSON(); $resourceService = $this->site->CreateService(MgServiceType::ResourceService); $featureService = $this->site->CreateService(MgServiceType::FeatureService); $map = new MgMap(); $map->Open($resourceService, $this->args['MAPNAME']); $layer = $map->GetLayers()->GetItem($this->args['LAYERNAME']); $resId = new MgResourceIdentifier($layer->GetFeatureSourceId()); $featureClass = $layer->GetFeatureClassName(); $schemaAndClass = explode(":", $featureClass); $classDef = $featureService->GetClassDefinition($resId, $schemaAndClass[0], $schemaAndClass[1]); $properties = new MgPropertyCollection(); $idList = $json->decode($this->args['IDLIST']); foreach ($idList as $key => $value) { switch ($classDef->GetProperties()->GetItem($key)->GetDataType()) { case MgPropertyType::Boolean: $properties->Add(new MgBooleanProperty($key, $value)); break; case MgPropertyType::Byte: $properties->Add(new MgByteProperty($key, $value)); break; case MgPropertyType::Single: $properties->Add(new MgSingleProperty($key, $value)); break; case MgPropertyType::Double: $properties->Add(new MgDoubleProperty($key, $value)); break; case MgPropertyType::Int16: $properties->Add(new MgInt16Property($key, $value)); break; case MgPropertyType::Int32: $properties->Add(new MgInt32Property($key, $value)); break; case MgPropertyType::Int64: $properties->Add(new MgInt64Property($key, $value)); break; case MgPropertyType::String: $properties->Add(new MgStringProperty($key, $value)); break; case MgPropertyType::DateTime: $properties->Add(new MgDateTimeProperty($key, $value)); break; case MgPropertyType::Null: case MgPropertyType::Blob: case MgPropertyType::Clob: case MgPropertyType::Feature: case MgPropertyType::Geometry: case MgPropertyType::Raster: break; } } $selection = new MgSelection($map); $selection->AddFeatureIds($layer, $featureClass, $properties); return $selection->ToXml(); }
</head> <body class="AppFrame"> <h1 class="AppHeading">Layer Visibility</h1> <?php require_once '../common/common.php'; try { MgInitializeWebTier($webconfigFilePath); $args = $_SERVER['REQUEST_METHOD'] == "POST" ? $_POST : $_GET; $sessionId = $args['SESSION']; $mapName = $args['MAPNAME']; $userInfo = new MgUserInformation($sessionId); $siteConnection = new MgSiteConnection(); $siteConnection->Open($userInfo); $map = new MgMap($siteConnection); $map->Open($mapName); $layers = $map->GetLayers(); // Get layer collection echo "<p>Layers, in draw order:</p>"; echo '<table class="taskPane" cellspacing="0">'; echo '<tr><th class="rowHead">Layer</th><th>GetVisible()</th><th>IsVisible()</th></tr>'; $count = $layers->GetCount(); for ($i = 0; $i < $count; $i++) { $layer = $layers->GetItem($i); echo "<tr><td class=\"rowHead\">" . $layer->GetName() . "</td><td>" . ($layer->GetVisible() ? 'on' : 'off') . "</td><td>" . ($layer->IsVisible() ? 'on' : 'off') . "</td></tr>\n"; } echo '</table>'; } catch (MgException $e) { echo "<p><strong>Error:</strong> "; echo $e->GetDetails(); echo "</p>"; }
function GetOpenMarkup() { $openMarkup = array(); $resourceService = $this->site->CreateService(MgServiceType::ResourceService); $map = new MgMap(); $map->Open($resourceService, $this->args['MAPNAME']); $layerGroups = $map->GetLayerGroups(); if ($layerGroups->Contains('_Markup')) { $layers = $map->GetLayers(); for ($i = 0; $i < $layers->GetCount(); $i++) { $layer = $layers->GetItem($i); if ($layer->GetGroup() != null and $layer->GetGroup()->GetName() == '_Markup') { $openMarkup[$this->GetResourceIdPrefix() . $layer->GetLegendLabel() . '.LayerDefinition'] = $layer->GetLegendLabel(); } } asort($openMarkup); } return $openMarkup; }
function GetSelectionXML() { $resourceService = $this->site->CreateService(MgServiceType::ResourceService); $map = new MgMap(); $map->Open($resourceService, $this->args['MAPNAME']); $markupLayer = $map->GetLayers()->GetItem('_' . $this->GetMarkupName()); $selection = new MgSelection($map); $className = $markupLayer->GetFeatureClassName(); $ids = $this->args['MARKUPFEATURE']; if (is_array($ids)) { foreach ($ids as $id) { $selection->AddFeatureIdInt32($markupLayer, $className, (int) $id); } } else { $selection->AddFeatureIdInt32($markupLayer, $className, (int) $ids); } return $selection->ToXML(); }
function ApplyTheme() { $resourceService = $this->site->CreateService(MgServiceType::ResourceService); $featureService = $this->site->CreateService(MgServiceType::FeatureService); $map = new MgMap(); $map->Open($resourceService, $this->args['MAPNAME']); $layers = $map->GetLayers(); $layer = $layers->GetItem($this->args['LAYERNAME']); $resId = new MgResourceIdentifier($layer->GetFeatureSourceId()); $layerDefResId = $layer->GetLayerDefinition(); $byteReader = $resourceService->GetResourceContent($layerDefResId); // Load the Layer Definition and Navigate to the specified <VectorScaleRange> $doc = DOMDocument::loadXML($byteReader->ToString()); $nodeList = $doc->getElementsByTagName('VectorScaleRange'); $vectorScaleRangecElement = $nodeList->item($this->args['SCALERANGEINDEX']); $areaTypeStyle = $vectorScaleRangecElement->getElementsByTagName('AreaTypeStyle')->item(0); // Remove any existing <AreaRule> elements. $areaRuleList = $areaTypeStyle->getElementsByTagName('AreaRule'); $ruleCount = $areaRuleList->length; for ($index = 0; $index < $ruleCount; $index++) { $areaTypeStyle->removeChild($areaRuleList->item(0)); } // Now create the new <AreaRule> elements. $areaRuleTemplate = file_get_contents("templates/arearuletemplate.xml"); $aggregateOptions = new MgFeatureAggregateOptions(); $portion = 0.0; $increment = $this->args['NUMRULES'] > 1 ? $increment = 1.0 / ($this->args['NUMRULES'] - 1) : 1.0; if ($this->args['DISTRO'] == 'INDIV_DIST') { $aggregateOptions->AddFeatureProperty($this->args['PROPERTYNAME']); $aggregateOptions->SelectDistinct(true); $dataReader = $featureService->SelectAggregate($resId, $layer->GetFeatureClassName(), $aggregateOptions); while ($dataReader->ReadNext()) { $value = $this->GetFeaturePropertyValue($dataReader, $this->args['PROPERTYNAME']); $filterText = '"' . $this->args['PROPERTYNAME'] . '" = '; if ($this->args['DATATYPE'] == MgPropertyType::String) { $filterText .= "'" . $value . "'"; } else { $filterText .= $value; } $areaRuleXML = sprintf($areaRuleTemplate, $this->args['PROPERTYNAME'] . ': ' . $value, $filterText, $this->InterpolateColor($portion, $this->args['FILLFROM'], $this->args['FILLTO'], $this->args['FILLTRANS']), $this->InterpolateColor($portion, $this->args['LINEFROM'], $this->args['LINETO'], 0)); $areaDoc = DOMDocument::loadXML($areaRuleXML); $areaNode = $doc->importNode($areaDoc->documentElement, true); $areaTypeStyle->appendChild($areaNode); $portion += $increment; } $dataReader->Close(); } else { $values = array(); $aggregateOptions->AddComputedProperty('THEME_VALUE', $this->args['DISTRO'] . '("' . $this->args['PROPERTYNAME'] . '",' . $this->args['NUMRULES'] . ',' . $this->args['MINVALUE'] . ',' . $this->args['MAXVALUE'] . ')'); $dataReader = $featureService->SelectAggregate($resId, $layer->GetFeatureClassName(), $aggregateOptions); while ($dataReader->ReadNext()) { $value = $this->GetFeaturePropertyValue($dataReader, 'THEME_VALUE'); array_push($values, $value); } $dataReader->Close(); for ($i = 0; $i < count($values) - 1; $i++) { $filterText = '"' . $this->args['PROPERTYNAME'] . '" >= ' . $values[$i] . ' AND "' . $this->args['PROPERTYNAME']; if ($i == count($values) - 1) { $filterText .= '" <= ' . $values[$i + 1]; } else { $filterText .= '" < ' . $values[$i + 1]; } $areaRuleXML = sprintf($areaRuleTemplate, $this->args['PROPERTYNAME'] . ': ' . $values[$i] . ' - ' . $values[$i + 1], $filterText, $this->InterpolateColor($portion, $this->args['FILLFROM'], $this->args['FILLTO'], $this->args['FILLTRANS']), $this->InterpolateColor($portion, $this->args['LINEFROM'], $this->args['LINETO'], 0)); $areaDoc = DOMDocument::loadXML($areaRuleXML); $areaNode = $doc->importNode($areaDoc->documentElement, true); $areaTypeStyle->appendChild($areaNode); $portion += $increment; } } // Now save our new layer definition to the session and add it to the map. $layerDefinition = $doc->saveXML(); $uniqueName = $this->MakeUniqueLayerName($map, $this->args['LAYERNAME'], $this->args['THEMENAME']); $legendLabel = $layer->GetLegendLabel(); if (strlen(trim($this->args['THEMENAME'])) > 0) { $legendLabel .= ' (' . $this->args['THEMENAME'] . ')'; } $layerResId = new MgResourceIdentifier('Session:' . $this->args['SESSION'] . '//' . $uniqueName . '.LayerDefinition'); $byteSource = new MgByteSource($layerDefinition, strlen($layerDefinition)); $resourceService->SetResource($layerResId, $byteSource->GetReader(), null); $newLayer = new MgLayer($layerResId, $resourceService); $newLayer->SetName($uniqueName); $newLayer->SetLegendLabel($legendLabel); $newLayer->SetDisplayInLegend($layer->GetDisplayInLegend()); $newLayer->SetVisible(true); $newLayer->SetSelectable($layer->GetLegendLabel()); $layers->Insert($layers->IndexOf($layer), $newLayer); $map->Save($resourceService); return $uniqueName; }
$featureService->UpdateFeatures($bufferFeatureResId, $commands, false); } catch (MgObjectNotFoundException $e) { // When an MgObjectNotFoundException is thrown, the layer // does not exist and must be created. $bufferFeatureResId = new MgResourceIdentifier("Session:" . $sessionId . "//Buffer.FeatureSource"); CreateBufferFeatureSource($featureService, $mapWktSrs, $bufferFeatureResId); $bufferLayer = CreateBufferLayer($resourceService, $bufferFeatureResId, $sessionId); $map->GetLayers()->Insert(0, $bufferLayer); } */ // New way, post MapGuide 2.0 $layerIndex = $map->GetLayers()->IndexOf('Buffer'); if ($layerIndex < 0) { // The layer does not exist and must be created. $bufferFeatureResId = new MgResourceIdentifier("Session:" . $sessionId . "//Buffer.FeatureSource"); CreateBufferFeatureSource($featureService, $mapWktSrs, $bufferFeatureResId); $bufferLayer = CreateBufferLayer($resourceService, $bufferFeatureResId, $sessionId); $map->GetLayers()->Insert(0, $bufferLayer); } else { $bufferLayer = $map->GetLayers()->GetItem($layerIndex); $commands = new MgFeatureCommandCollection(); $commands->Add(new MgDeleteFeatures('BufferClass', "ID like '%'")); $bufferLayer->UpdateFeatures($commands); } for ($i = 0; $i < $selectedLayers->GetCount(); $i++) { // Only check selected features in the Parcels layer. $layer = $selectedLayers->GetItem($i);
$fsvc->CreateFeatureSource($id, $params); // We need to add some data to the sdf before using it. The spatial context // reader must have an extent. $cmdColl = new MgFeatureCommandCollection(); for ($i = 1; $i <= 20; $i++) { $insert = $intFeature->InsertCommand($i); $cmdColl->Add($insert); } echo "Updating features\n"; $fsvc->UpdateFeatures($id, $cmdColl, false); $mapId = new MgResourceIdentifier("Library://TrevorWekel/NewSdf.MapDefinition"); $map = new MgMap(); $map->Create($rsvc, $mapId, "NewMap"); echo "Building Selection from Add()\n"; $sel = new MgSelection($map); $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();
function GetSelectionXML() { $resourceService = $this->site->CreateService(MgServiceType::ResourceService); $map = new MgMap(); $map->Open($resourceService, $this->args['MAPNAME']); $markupLayer = $map->GetLayers()->GetItem('_' . $this->GetMarkupName()); $selection = new MgSelection($map); $selection->AddFeatureIdInt32($markupLayer, $markupLayer->GetFeatureClassName(), (int) $this->args['MARKUPFEATURE']); return $selection->ToXML(); }
$args = $_SERVER['REQUEST_METHOD'] == "POST" ? $_POST : $_GET; $sessionId = $args['SESSION']; $mapName = $args['MAPNAME']; try { // Initialize the Web Extensions and connect to the Server using // the Web Extensions session identifier stored in PHP session state. MgInitializeWebTier($webconfigFilePath); $userInfo = new MgUserInformation($sessionId); $siteConnection = new MgSiteConnection(); $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);
require_once $fusionMGpath . 'Utilities.php'; require_once $fusionMGpath . 'JSON.php'; require_once 'classes/featureinfo.php'; $args = $_SERVER['REQUEST_METHOD'] == "POST" ? $_POST : $_GET; try { $responseType = 'text/plain'; $response = ''; $site = new MgSiteConnection(); $site->Open(new MgUserInformation($args['SESSION'])); $resourceService = $site->CreateService(MgServiceType::ResourceService); $featureService = $site->CreateService(MgServiceType::FeatureService); $layerName = $args['LAYERNAME']; $mapName = $args['MAPNAME']; $map = new MgMap($site); $map->Open($mapName); $layer = $map->GetLayers()->GetItem($layerName); $className = $layer->GetFeatureClassName(); $selection = new MgSelection($map); $selection->Open($resourceService, $mapName); $properties = new stdClass(); if ($selection->Contains($layer, $className)) { $featureReader = $selection->GetSelectedFeatures($layer, $className, new MgStringCollection()); /* Get the map SRS - we use this to convert distances */ $srsFactory = new MgCoordinateSystemFactory(); //safely get an SRS ... (in Utilities) $srsDefMap = GetMapSRS($map); $srsMap = $srsFactory->Create($srsDefMap); $featureResId = new MgResourceIdentifier($layer->GetFeatureSourceId()); $spatialContext = $featureService->GetSpatialContexts($featureResId, true); $srsLayerWkt = false; if ($spatialContext != null && $spatialContext->ReadNext() != null) {
$featureService = $siteConnection->CreateService(MgServiceType::FeatureService); // Converts a boolean to "yes" or "no" // --from MG Web Tier API Reference function BooleanToString($boolean) { if (is_bool($boolean)) { return $boolean ? "true" : "false"; } else { return "ERROR in BooleanToString."; } } //Get a runtime map from a map definition $map = new MgMap(); $map->Open($resourceService, $mapName); //Get the layer $layerCollection = $map->GetLayers(); try { $layer = $layerCollection->GetItem($_REQUEST['layer']); if ($layer == null) { echo '<Error>Layer ' . $_REQUEST['layer'] . ' Not Found</Error>'; exit; } if (isset($_REQUEST['selectable'])) { if (strcasecmp($_REQUEST['selectable'], 'true') == 0) { $layer->SetSelectable(true); } else { $layer->SetSelectable(false); } $map->Save($resourceService); } //property mappings from the session
public function GetTileXYZ($resId, $groupName, $x, $y, $z, $type, $layerNames = NULL) { $fmt = $this->ValidateRepresentation($type, array("json", "png", "png8", "jpg", "gif")); $path = self::GetTilePath($this->app, $resId, $groupName, $z, $x, $y, $type, $layerNames); clearstatcache(); $dir = dirname($path); $lockPath = "{$dir}/lock_" . $y . ".lck"; $attempts = 0; while (!@is_dir($dir)) { try { mkdir($dir, 0777, true); } catch (Exception $e) { //Another tile request may have already created this since $attempts++; //Bail after MAX_RETRY_ATTEMPTS if ($attempts >= self::MAX_RETRY_ATTEMPTS) { $this->ServerError($this->app->localizer->getText("E_FAILED_TO_CREATE_DIR_AFTER_N_ATTEMPTS", $attempts), $this->GetMimeTypeForFormat($type)); } } } //If there's a dangling lock file, attempt to remove it if (file_exists($lockPath)) { unlink($lockPath); } $fpLockFile = fopen($lockPath, "a+"); //Message of any exception caught will be set to this variable $tileError = null; $requestId = rand(); $this->app->log->debug("({$requestId}) Checking if {$path} exists"); $attempts = 0; while (!file_exists($path)) { //Bail after MAX_RETRY_ATTEMPTS if ($attempts >= self::MAX_RETRY_ATTEMPTS) { $this->ServerError($this->app->localizer->getText("E_FAILED_TO_GENERATE_TILE_AFTER_N_ATTEMPTS", $attempts), $this->GetMimeTypeForFormat($type)); } $attempts++; $this->app->log->debug("({$requestId}) {$path} does not exist. Locking for writing"); $bLocked = false; flock($fpLockFile, LOCK_EX); fwrite($fpLockFile, "."); $bLocked = true; $this->app->log->debug("({$requestId}) Acquired lock for {$path}. Checking if path exists again."); //check once more to see if the cache file was created while waiting for //the lock clearstatcache(); if (!file_exists($path)) { try { $this->app->log->debug("({$requestId}) Rendering tile to {$path}"); $bOldPath = true; if ($type != "json") { //if this is MGOS 3.0 and we're dealing with a tile set, we invoke GETTILEIMAGE as that we can pass in Tile Set Definition //resource ids without issues. We cannot create MgMaps from Tile Set Definitions that are not using the default tile provider. // //The given tile set is assumed to be using the XYZ provider, the case where the Tile Set Definition is using the default provider //is not handled if ($this->app->MG_VERSION[0] >= 3 && $resId->GetResourceType() == "TileSetDefinition") { $bOldPath = false; $sessionId = ""; if ($resId->GetRepositoryType() === MgRepositoryType::Session && $this->app->request->get("session") == null) { $sessionId = $resId->GetRepositoryName(); } $resIdStr = $resId->ToString(); $that = $this; $this->EnsureAuthenticationForHttp(function ($req, $param) use($that, $resIdStr, $groupName, $x, $y, $z, $requestId, $path) { $param->AddParameter("OPERATION", "GETTILEIMAGE"); $param->AddParameter("VERSION", "1.2.0"); $param->AddParameter("MAPDEFINITION", $resIdStr); $param->AddParameter("BASEMAPLAYERGROUPNAME", $groupName); $param->AddParameter("SCALEINDEX", $z); $param->AddParameter("TILEROW", $x); $param->AddParameter("TILECOL", $y); $that->app->log->debug("({$requestId}) Executing GETTILEIMAGE"); $that->ExecuteHttpRequest($req, function ($result, $status) use($path) { if ($status == 200) { //Need to dump the rendered tile to the specified path so the caching stuff below can still do its thing $resultObj = $result->GetResultObject(); $sink = new MgByteSink($resultObj); $sink->ToFile($path); } }); }, true, "", $sessionId); //Tile access can be anonymous, so allow for it if credentials/session specified, but if this is a session-based Map Definition, use the session id as the nominated one } } //Pre MGOS 3.0 code path if ($bOldPath) { $this->app->log->debug("({$requestId}) Going down old code path"); $this->EnsureAuthenticationForSite("", true); $siteConn = new MgSiteConnection(); $siteConn->Open($this->userInfo); $map = new MgMap($siteConn); $map->Create($resId, "VectorTileMap"); $renderSvc = $siteConn->CreateService(MgServiceType::RenderingService); $groups = $map->GetLayerGroups(); $baseGroup = $groups->GetItem($groupName); //Will throw MgObjectNotFoundException -> 404 if no such group exists $factory = new MgCoordinateSystemFactory(); $mapCsWkt = $map->GetMapSRS(); $mapCs = $factory->Create($mapCsWkt); $mapExtent = $map->GetMapExtent(); $mapExLL = $mapExtent->GetLowerLeftCoordinate(); $mapExUR = $mapExtent->GetUpperRightCoordinate(); $metersPerUnit = $mapCs->ConvertCoordinateSystemUnitsToMeters(1.0); $this->app->log->debug("({$requestId}) Calc bounds from XYZ"); //XYZ to lat/lon math. From this we can convert to the bounds in the map's CS // //Source: http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames $n = pow(2, $z); $lonMin = $x / $n * 360.0 - 180.0; $latMin = rad2deg(atan(sinh(pi() * (1 - 2 * $y / $n)))); $lonMax = ($x + 1) / $n * 360.0 - 180.0; $latMax = rad2deg(atan(sinh(pi() * (1 - 2 * ($y + 1) / $n)))); $boundsMinX = min($lonMin, $lonMax); $boundsMinY = min($latMin, $latMax); $boundsMaxX = max($lonMax, $lonMin); $boundsMaxY = max($latMax, $latMin); if ($mapCs->GetCsCode() != "LL84") { $llCs = $factory->CreateFromCode("LL84"); $trans = $factory->GetTransform($llCs, $mapCs); $ul = $trans->Transform($lonMin, $latMin); $lr = $trans->Transform($lonMax, $latMax); $boundsMinX = min($lr->GetX(), $ul->GetX()); $boundsMinY = min($lr->GetY(), $ul->GetY()); $boundsMaxX = max($lr->GetX(), $ul->GetX()); $boundsMaxY = max($lr->GetY(), $ul->GetY()); } //Set all layers under group to be visible $layers = $map->GetLayers(); $layerCount = $layers->GetCount(); $groupCount = $groups->GetCount(); //Turn all groups that are not the given group to be hidden for ($i = 0; $i < $groupCount; $i++) { $group = $groups->GetItem($i); if ($group->GetName() != $groupName) { $group->SetVisible(false); } else { $group->SetVisible(true); } } for ($i = 0; $i < $layerCount; $i++) { $layer = $layers->GetItem($i); $group = $layer->GetGroup(); if (null == $group) { continue; } if ($group->GetName() != $groupName && $layer->GetLayerType() == MgLayerType::Dynamic) { $layer->SetVisible(false); continue; } if ($layer->GetLayerType() == MgLayerType::Dynamic) { $layer->SetVisible(true); } } if ($type == "json") { //error_log("($requestId) Render vector tile"); $this->PutVectorTileXYZ($map, $groupName, $siteConn, $metersPerUnit, $factory, $path, $boundsMinX, $boundsMinY, $boundsMaxX, $boundsMaxY, $layerNames); } else { $format = strtoupper($type); //error_log("($requestId) Render image tile"); $this->PutTileImageXYZ($map, $groupName, $renderSvc, $path, $format, $boundsMinX, $boundsMinY, $boundsMaxX, $boundsMaxY, $layerNames, $requestId); } } } catch (MgException $ex) { if ($bLocked) { $this->app->log->debug("({$requestId}) MgException caught " . $ex->GetDetails() . "\n" . $ex->getTraceAsString() . "\n. Releasing lock for {$path}"); $tileError = $ex->GetExceptionMessage(); flock($fpLockFile, LOCK_UN); $bLocked = false; } if ($ex instanceof MgResourceNotFoundException || $ex instanceof MgObjectNotFoundException) { $this->NotFound($ex->GetExceptionMessage(), $this->GetMimeTypeForFormat($fmt)); } else { if ($ex instanceof MgConnectionFailedException) { $this->ServiceUnavailable($ex->GetExceptionMessage(), $this->GetMimeTypeForFormat($fmt)); } } } catch (Exception $ex) { if ($bLocked) { $tileError = get_class($ex) . " - " . $ex->getMessage(); $this->app->log->debug("({$requestId}) Exception caught ({$tileError}). Releasing lock for {$path}"); flock($fpLockFile, LOCK_UN); $bLocked = false; } } } if ($bLocked) { $this->app->log->debug("({$requestId}) Releasing lock for {$path}"); flock($fpLockFile, LOCK_UN); $bLocked = false; } } //An exception occurred, try to clean up lock before bailing if ($tileError != null) { try { fclose($fpLockFile); unlink($lockPath); } catch (Exception $ex) { $this->app->log->debug("({$requestId}) Failed to delete lock file. Perhaps another concurrent request to the same tile is happening?"); } throw new Exception($tileError); } $modTime = filemtime($path); $this->app->lastModified($modTime); $this->app->log->debug("({$requestId}) Acquiring shared lock for {$path}"); //acquire shared lock for reading to prevent a problem that could occur //if a tile exists but is only partially generated. flock($fpLockFile, LOCK_SH); $this->app->log->debug("({$requestId}) Outputting {$path}"); $ext = strtoupper(pathinfo($path, PATHINFO_EXTENSION)); $mimeType = ""; switch ($ext) { case "PNG": //MgImageFormats::Png: $mimeType = MgMimeType::Png; break; case "GIF": //MgImageFormats::Gif: $mimeType = MgMimeType::Gif; break; case "JPG": //MgImageFormats::Jpeg: $mimeType = MgMimeType::Jpeg; break; case "JSON": $mimeType = MgMimeType::Json; break; } $this->app->response->header("Content-Type", $mimeType); $this->app->expires("+6 months"); $this->app->response->header("Cache-Control", "max-age=31536000, must-revalidate"); $this->app->response->setBody(file_get_contents($path)); $this->app->log->debug("({$requestId}) Releasing shared lock for {$path}"); //Release lock flock($fpLockFile, LOCK_UN); //Try to delete the lock file try { fclose($fpLockFile); unlink($lockPath); } catch (Exception $ex) { $this->app->log->debug("({$requestId}) Failed to delete lock file. Perhaps another concurrent request to the same tile is happening?"); } }
public function UpdateMapLayersAndGroups($sessionId, $mapName, $format) { //Check for unsupported representations $fmt = $this->ValidateRepresentation($format, array("xml", "json")); try { $this->EnsureAuthenticationForSite($sessionId); $siteConn = new MgSiteConnection(); $siteConn->Open($this->userInfo); $resSvc = $siteConn->CreateService(MgServiceType::ResourceService); $map = new MgMap($siteConn); $map->Open($mapName); if ($fmt == "json") { $body = $this->app->request->getBody(); $json = json_decode($body); if ($json == NULL) { throw new Exception($this->app->localizer->getText("E_MALFORMED_JSON_BODY")); } } else { $body = $this->app->request->getBody(); $jsonStr = MgUtils::Xml2Json($body); $json = json_decode($jsonStr); } if (!isset($json->UpdateMap)) { throw new Exception($this->app->localizer->getText("E_MALFORMED_JSON_BODY")); } /* Expected structure /UpdateMap /Operation [1...n] /Type - [AddLayer|UpdateLayer|RemoveLayer|AddGroup|UpdateGroup|RemoveGroup] /Name /ResourceId /SetLegendLabel /SetDisplayInLegend /SetExpandInLegend /SetVisible /SetSelectable /InsertAt */ $layers = $map->GetLayers(); $groups = $map->GetLayerGroups(); $um = $json->UpdateMap; $updateStats = new stdClass(); $updateStats->AddedLayers = 0; $updateStats->UpdatedLayers = 0; $updateStats->RemovedLayers = 0; $updateStats->AddedGroups = 0; $updateStats->UpdatedGroups = 0; $updateStats->RemovedGroups = 0; $this->app->log->debug("Operations found: " . count($um->Operation)); for ($i = 0; $i < count($um->Operation); $i++) { $op = $um->Operation[$i]; switch ($op->Type) { case "AddLayer": $resId = new MgResourceIdentifier($op->ResourceId); $layer = new MgLayer($resId, $resSvc); $layer->SetName($op->Name); self::ApplyCommonLayerProperties($layer, $op, $groups); if (isset($op->InsertAt)) { $layers->Insert(intval($op->InsertAt), $layer); } else { $layers->Add($layer); } $this->app->log->debug("Add Layer: " . $op->Name); $updateStats->AddedLayers++; break; case "UpdateLayer": $layer = $layers->GetItem($op->Name); if (self::ApplyCommonLayerProperties($layer, $op, $groups)) { $this->app->log->debug("Updated Layer: " . $op->Name); $updateStats->UpdatedLayers++; } break; case "RemoveLayer": $layer = $layers->GetItem($op->Name); if ($layers->Remove($layer)) { $this->app->log->debug("Removed Layer: " . $op->Name); $updateStats->RemovedLayers++; } break; case "AddGroup": $group = new MgLayerGroup($op->Name); self::ApplyCommonGroupProperties($group, $op, $groups); if (isset($op->InsertAt)) { $groups->Insert(intval($op->InsertAt), $group); } else { $groups->Add($group); } $this->app->log->debug("Add Group: " . $op->Name); $updateStats->AddedGroups++; break; case "UpdateGroup": $gidx = $groups->IndexOf($op->Name); if ($gidx < 0) { if ($op->AddIfNotExists) { $group = new MgLayerGroup($op->Name); self::ApplyCommonGroupProperties($group, $op, $groups); if (isset($op->InsertAt)) { $groups->Insert(intval($op->InsertAt), $group); } else { $groups->Add($group); } $this->app->log->debug("Add Group: " . $op->Name); $updateStats->AddedGroups++; } else { throw new Exception($this->app->localizer->getText("E_GROUP_NOT_FOUND", $op->Name)); } } else { $group = $groups->GetItem($gidx); if (self::ApplyCommonGroupProperties($group, $op, $groups)) { $this->app->log->debug("Updated Group: " . $op->Name); $updateStats->UpdatedGroups++; } } break; case "RemoveGroup": $group = $groups->GetItem($op->Name); if ($groups->Remove($group)) { $this->app->log->debug("Removed Group: " . $op->Name); $updateStats->RemovedGroups++; } break; } } if ($updateStats->AddedLayers > 0 || $updateStats->UpdatedLayers > 0 || $updateStats->RemovedLayers > 0 || $updateStats->AddedGroups > 0 || $updateStats->UpdatedGroups > 0 || $updateStats->RemovedGroups > 0) { $map->Save(); } $response = "<UpdateMapResult>"; $response .= "<AddedLayers>"; $response .= $updateStats->AddedLayers; $response .= "</AddedLayers>"; $response .= "<UpdatedLayers>"; $response .= $updateStats->UpdatedLayers; $response .= "</UpdatedLayers>"; $response .= "<RemovedLayers>"; $response .= $updateStats->RemovedLayers; $response .= "</RemovedLayers>"; $response .= "<AddedGroups>"; $response .= $updateStats->AddedGroups; $response .= "</AddedGroups>"; $response .= "<UpdatedGroups>"; $response .= $updateStats->UpdatedGroups; $response .= "</UpdatedGroups>"; $response .= "<RemovedGroups>"; $response .= $updateStats->RemovedGroups; $response .= "</RemovedGroups>"; $response .= "</UpdateMapResult>"; $bs = new MgByteSource($response, strlen($response)); $bs->SetMimeType(MgMimeType::Xml); $br = $bs->GetReader(); if ($format == "json") { $this->OutputXmlByteReaderAsJson($br); } else { $this->OutputByteReader($br); } } catch (MgException $ex) { $this->OnException($ex, $this->GetMimeTypeForFormat($format)); } }
function ApplyTheme() { $resourceService = $this->site->CreateService(MgServiceType::ResourceService); $featureService = $this->site->CreateService(MgServiceType::FeatureService); $map = new MgMap($this->site); $map->Open($this->args['MAPNAME']); $layers = $map->GetLayers(); $layer = $layers->GetItem($this->args['LAYERNAME']); $resId = new MgResourceIdentifier($layer->GetFeatureSourceId()); $layerDefResId = $layer->GetLayerDefinition(); $byteReader = $resourceService->GetResourceContent($layerDefResId); $filter = $layer->GetFilter(); // Load the Layer Definition and Navigate to the specified <VectorScaleRange> $doc = new DOMDocument(); $doc->loadXML($byteReader->ToString()); $version = $doc->documentElement->getAttribute('version'); $template = 'templates/arearuletemplate-'.$version.'.xml'; $layerDefList = $doc->getElementsByTagName('VectorLayerDefinition'); $layerDef = $layerDefList->item(0); $nodeList = $layerDef->getElementsByTagName('VectorScaleRange'); $vectorScaleRangecElement = $nodeList->item($this->args['SCALERANGEINDEX']); $listLength = $nodeList->length; for($index = 0; $index < $listLength; $index++) { $layerDef->removeChild($nodeList->item(0)); } $layerDef->appendChild($vectorScaleRangecElement); $areaTypeStyle = $vectorScaleRangecElement->getElementsByTagName('AreaTypeStyle')->item(0); // Remove any existing <AreaRule> elements. if($areaTypeStyle != null) { $areaRuleList = $areaTypeStyle->getElementsByTagName('AreaRule'); $ruleCount = $areaRuleList->length; for($index = 0; $index < $ruleCount; $index++) { $areaTypeStyle->removeChild($areaRuleList->item(0)); } $hasChild = $areaTypeStyle->hasChildNodes(); if($hasChild) { $element = $areaTypeStyle->childNodes->item(0); } } $CompositeTypeStyles = $vectorScaleRangecElement->getElementsByTagName('CompositeTypeStyle'); $isEnhancedStyle = ($CompositeTypeStyles->length != 0); // Remove any existing <CompositeTypeStyle> elements with Polygon <GeometryContext>. if($isEnhancedStyle) { $template = 'templates/arearuletemplate-'.$version.'-Enhanced.xml'; $styleCount = $CompositeTypeStyles->length; for($index = 0; $index < $styleCount; $index++) { $CompositeTypeStyle = $CompositeTypeStyles->item($index); $GeometryContexts = $CompositeTypeStyle->getElementsByTagName('GeometryContext'); $contextCount = $GeometryContexts->length; for($i = 0; $i < $contextCount; $i++) { $GeometryContext = $GeometryContexts->item($i); if($GeometryContext->nodeValue == 'Polygon') { $vectorScaleRangecElement->removeChild($CompositeTypeStyle); $index--; $styleCount--; break; } } } } // Now create the new <AreaRule> or <CompositeTypeStyle> elements. $areaRuleTemplate = file_get_contents($template); $aggregateOptions = new MgFeatureAggregateOptions(); $portion = 0.0; $increment = ($this->args['NUMRULES'] > 1) ? $increment = 1.0 / ($this->args['NUMRULES'] - 1) : 1.0; if ($this->args['DISTRO'] == 'INDIV_DIST') { $values = array(); $aggregateOptions->AddComputedProperty('THEME_VALUE', 'UNIQUE("' . $this->args['PROPERTYNAME'] . '")'); if($filter != '') $aggregateOptions->SetFilter($filter); $dataReader = $layer->SelectAggregate($aggregateOptions); while ($dataReader->ReadNext()) { $value = $this->GetFeaturePropertyValue($dataReader, 'THEME_VALUE'); array_push($values, $value); } $dataReader->Close(); if ($this->args['DATATYPE'] == MgPropertyType::String) sort($values, SORT_STRING); else sort($values, SORT_NUMERIC); for ($i = 0; $i < count($values); $i++) { $filterText = '"' . $this->args['PROPERTYNAME'] . '" = '; if ($this->args['DATATYPE'] == MgPropertyType::String) $filterText .= "'" . $values[$i] . "'"; else $filterText .= $values[$i]; $areaRuleXML = sprintf($areaRuleTemplate, $this->args['PROPERTYNAME'] . ': ' . $values[$i], $filterText, $this->InterpolateColor($portion, $this->args['FILLFROM'], $this->args['FILLTO'], $this->args['FILLTRANS']), $this->InterpolateColor($portion, $this->args['LINEFROM'], $this->args['LINETO'], 0)); $areaDoc = new DOMDocument(); $areaDoc->loadXML($areaRuleXML); $areaNode = $doc->importNode($areaDoc->documentElement, true); if($areaTypeStyle != null) { if($hasChild) { $areaTypeStyle->insertBefore($areaNode, $element); } else { $areaTypeStyle->appendChild($areaNode); } } if($isEnhancedStyle) { $compositeTypeStyle = $doc->createElement('CompositeTypeStyle'); $compositeTypeStyle->appendChild($areaNode); $vectorScaleRangecElement->appendChild($compositeTypeStyle); } $portion += $increment; } } else { $values = array(); $aggregateOptions->AddComputedProperty('THEME_VALUE', $this->args['DISTRO'] . '("' . $this->args['PROPERTYNAME'] . '",' . $this->args['NUMRULES'] . ',' . $this->args['MINVALUE'] . ',' . $this->args['MAXVALUE'] . ')'); if($filter != '') $aggregateOptions->SetFilter($filter); $dataReader = $layer->SelectAggregate($aggregateOptions); while ($dataReader->ReadNext()) { $value = $this->GetFeaturePropertyValue($dataReader, 'THEME_VALUE'); array_push($values, $value); } $dataReader->Close(); for ($i = 0; $i < count($values) - 1; $i++) { $filterText = '"' . $this->args['PROPERTYNAME'] . '" >= ' . $values[$i] . ' AND "' . $this->args['PROPERTYNAME']; if ($i == count($values) - 2) $filterText .= '" <= ' . $values[$i + 1]; else $filterText .= '" < ' . $values[$i + 1]; $areaRuleXML = sprintf($areaRuleTemplate, $this->args['PROPERTYNAME'] . ': ' . $values[$i] . ' - ' . $values[$i + 1], $filterText, $this->InterpolateColor($portion, $this->args['FILLFROM'], $this->args['FILLTO'], $this->args['FILLTRANS']), $this->InterpolateColor($portion, $this->args['LINEFROM'], $this->args['LINETO'], 0)); $areaDoc = new DOMDocument(); $areaDoc->loadXML($areaRuleXML); $areaNode = $doc->importNode($areaDoc->documentElement, true); if($areaTypeStyle != null) { if($hasChild) { $areaTypeStyle->insertBefore($areaNode, $element); } else { $areaTypeStyle->appendChild($areaNode); } } if($isEnhancedStyle) { $compositeTypeStyle = $doc->createElement('CompositeTypeStyle'); $compositeTypeStyle->appendChild($areaNode); $vectorScaleRangecElement->appendChild($compositeTypeStyle); } $portion += $increment; } } // Now save our new layer definition to the session and add it to the map. $layerDefinition = $doc->saveXML(); $uniqueName = $this->MakeUniqueLayerName($map, $this->args['LAYERNAME'], $this->args['THEMENAME']); $legendLabel = $layer->GetLegendLabel(); if (strlen(trim($this->args['THEMENAME'])) > 0 ) $legendLabel .= ' (' . $this->args['THEMENAME'] . ')'; $layerResId = new MgResourceIdentifier('Session:' . $this->args['SESSION'] . '//' . $uniqueName . '.LayerDefinition'); $byteSource = new MgByteSource($layerDefinition, strlen($layerDefinition)); $resourceService->SetResource($layerResId, $byteSource->GetReader(), null); $newLayer = new MgLayer($layerResId, $resourceService); $newLayer->SetName($uniqueName); $newLayer->SetLegendLabel($legendLabel); $newLayer->SetDisplayInLegend($layer->GetDisplayInLegend()); $newLayer->SetVisible(true); $newLayer->SetSelectable($layer->GetLegendLabel()); $layers->Insert($layers->IndexOf($layer), $newLayer); $map->Save(); return $uniqueName; }