function GetTransform() { $coordSysFactory = new MgCoordinateSystemFactory(); $resourceService = $this->site->CreateService(MgServiceType::ResourceService); $featureService = $this->site->CreateService(MgServiceType::FeatureService); $featureSourceId = $this->GetFeatureSource(); $wkt = null; //Get the WKT from spatial context, because SDF only supports one spatial context it will be the first one $scReader = $featureService->GetSpatialContexts($featureSourceId, true); if ($scReader->ReadNext()) { $wkt = $scReader->GetCoordinateSystemWkt(); } $scReader->Close(); $map = new MgMap(); $map->Open($resourceService, $this->args['MAPNAME']); if (null == $wkt) { return null; } //It's bunk. Assume map SRS if (strcmp($wkt, $map->GetMapSRS()) == 0) { return null; } //Identical. No transformation needed $source = $coordSysFactory->Create($map->GetMapSRS()); if (null != $wkt) { $target = $coordSysFactory->Create($wkt); } return $coordSysFactory->GetTransform($source, $target); }
public function TransformCoordinates() { $source = $this->app->request->post("from"); $target = $this->app->request->post("to"); $coordList = $this->app->request->post("coords"); $format = $this->app->request->post("format"); if ($format == null) { $format = "xml"; } $fmt = $this->ValidateRepresentation($format, array("xml", "json")); if ($source == null) { $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "from"), $this->GetMimeTypeForFormat($format)); } if ($target == null) { $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "to"), $this->GetMimeTypeForFormat($format)); } if ($coordList == null) { $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "coords"), $this->GetMimeTypeForFormat($format)); } try { $factory = new MgCoordinateSystemFactory(); $sourceCs = $factory->CreateFromCode($source); $targetCs = $factory->CreateFromCode($target); $trans = $factory->GetTransform($sourceCs, $targetCs); $coords = explode(",", $coordList); $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?><CoordinateCollection>"; foreach ($coords as $coordPair) { $tokens = explode(" ", trim($coordPair)); $tokenCount = count($tokens); if ($tokenCount === 2) { $txCoord = $trans->Transform(floatval($tokens[0]), floatval($tokens[1])); $output .= "<Coordinate><X>" . $txCoord->GetX() . "</X><Y>" . $txCoord->GetY() . "</Y></Coordinate>"; } else { //TODO: We should accept a partial response, but there's currently no way an empty <Coordinate/> tag survives the //XML to JSON conversion, so we have to throw lest we return an inconsisten partial result $this->ServerError($this->app->localizer->getText("E_INVALID_COORDINATE_PAIR", $coordPair, $tokenCount), $this->GetMimeTypeForFormat($format)); } } $output .= "</CoordinateCollection>"; if ($fmt === "json") { $this->app->response->header("Content-Type", MgMimeType::Json); $json = MgUtils::Xml2Json($output); $this->app->response->write($json); } else { $this->app->response->header("Content-Type", MgMimeType::Xml); $this->app->response->write($output); } } catch (MgException $ex) { $this->OnException($ex, $this->GetMimeTypeForFormat($format)); } }
/** * Handles GET requests for this adapter. Overridable. Does nothing if not overridden. */ public function HandleGet($single) { try { //Apply any overrides from query string $ovWidth = $this->app->request->get("width"); $ovHeight = $this->app->request->get("height"); $ovDpi = $this->app->request->get("dpi"); $ovScale = $this->app->request->get("scale"); if ($ovWidth != null) { $this->imgWidth = $ovWidth; } if ($ovHeight != null) { $this->imgHeight = $ovHeight; } if ($ovDpi != null) { $this->dpi = $ovDpi; } if ($ovScale != null) { $this->viewScale = intval($ovScale); } $site = $this->siteConn->GetSite(); $this->sessionId = $site->GetCurrentSession(); $bCreatedSession = false; if ($this->sessionId === "") { $this->sessionId = $site->CreateSession(); $bCreatedSession = true; } $userInfo = new MgUserInformation($this->sessionId); $siteConn = new MgSiteConnection(); $siteConn->Open($userInfo); $this->resSvc = $siteConn->CreateService(MgServiceType::ResourceService); $this->featSvc = $siteConn->CreateService(MgServiceType::FeatureService); $mapName = "MapImageAdapter"; $this->map = new MgMap($siteConn); $this->map->Create($this->mapDefId, $mapName); $this->sel = new MgSelection($this->map); $mapId = new MgResourceIdentifier("Session:" . $this->sessionId . "//{$mapName}.Map"); $this->map->Save($this->resSvc, $mapId); $layers = $this->map->GetLayers(); $idx = $layers->IndexOf($this->selLayerName); if ($idx < 0) { throw new Exception($this->app->localizer->getText("E_LAYER_NOT_FOUND_IN_MAP", $this->selLayerName)); } $layer = $layers->GetItem($idx); if ($layer->GetFeatureSourceId() !== $this->featureSourceId->ToString()) { throw new Exception($this->app->localizer->getText("E_LAYER_NOT_POINTING_TO_EXPECTED_FEATURE_SOURCE", $this->selLayerName, $this->featureSourceId->ToString(), $layer->GetFeatureSourceId())); } $this->selLayer = $layer; $query = $this->CreateQueryOptions($single); $reader = $this->featSvc->SelectFeatures($this->featureSourceId, $this->className, $query); $start = -1; $end = -1; $read = 0; $limit = $this->limit; $pageNo = $this->app->request->get("page"); if ($pageNo == null) { $pageNo = 1; } else { $pageNo = intval($pageNo); } $bEndOfReader = false; if ($this->pageSize > 0) { if ($pageNo > 1) { $skipThisMany = ($pageNo - 1) * $this->pageSize - 1; //echo "skip this many: $skipThisMany<br/>"; $bEndOfReader = true; while ($reader->ReadNext()) { if ($read == $skipThisMany) { $bEndOfReader = false; $limit = min($skipThisMany + $this->pageSize, $this->limit - 1) - $read; break; } $read++; } } else { //first page, set limit to page size $limit = $this->pageSize; } } //echo "read: $read, limit: $limit, pageSize: ".$this->pageSize." result limit: ".$this->limit; //die; $this->sel->AddFeatures($this->selLayer, $reader, $limit); $reader->Close(); $this->sel->Save($this->resSvc, $mapName); $extents = $this->sel->GetExtents($this->featSvc); $extLL = $extents->GetLowerLeftCoordinate(); $extUR = $extents->GetUpperRightCoordinate(); $x = ($extLL->GetX() + $extUR->GetX()) / 2.0; $y = ($extLL->GetY() + $extUR->GetY()) / 2.0; if ($this->viewScale === 0) { $csFactory = new MgCoordinateSystemFactory(); $cs = $csFactory->Create($this->map->GetMapSRS()); $metersPerUnit = $cs->ConvertCoordinateSystemUnitsToMeters(1.0); $mcsH = $extUR->GetY() - $extLL->GetY(); $mcsW = $extUR->GetX() - $extLL->GetX(); $mcsH = $mcsH * $this->zoomFactor; $mcsW = $mcsW * $this->zoomFactor; $metersPerPixel = 0.0254 / $this->dpi; if ($this->imgHeight * $mcsW > $this->imgWidth * $mcsH) { $this->viewScale = $mcsW * $metersPerUnit / ($this->imgWidth * $metersPerPixel); } else { $this->viewScale = $mcsH * $metersPerUnit / ($this->imgHeight * $metersPerPixel); } // height-limited } $req = new MgHttpRequest(""); $param = $req->GetRequestParam(); $param->AddParameter("OPERATION", "GETMAPIMAGE"); $param->AddParameter("VERSION", "1.0.0"); $param->AddParameter("SESSION", $this->sessionId); $param->AddParameter("LOCALE", $this->app->config("Locale")); $param->AddParameter("CLIENTAGENT", "MapGuide REST Extension"); $param->AddParameter("CLIENTIP", $this->GetClientIp()); $param->AddParameter("FORMAT", $this->imgFormat); $param->AddParameter("MAPNAME", $mapName); $param->AddParameter("KEEPSELECTION", "1"); $param->AddParameter("SETDISPLAYWIDTH", $this->imgWidth); $param->AddParameter("SETDISPLAYHEIGHT", $this->imgHeight); $param->AddParameter("SETDISPLAYDPI", $this->dpi); $param->AddParameter("SETVIEWCENTERX", $x); $param->AddParameter("SETVIEWCENTERY", $y); $param->AddParameter("SETVIEWSCALE", $this->viewScale); $param->AddParameter("BEHAVIOR", 3); //Layers + Selection //Apply file download parameters if specified if ($this->app->request->params("download") === "1" || $this->app->request->params("download") === "true") { $param->AddParameter("X-DOWNLOAD-ATTACHMENT", "true"); if ($this->app->request->params("downloadname")) { $param->AddParameter("X-DOWNLOAD-ATTACHMENT-NAME", $this->app->request->params("downloadname")); } } $this->ExecuteHttpRequest($req); if ($bCreatedSession === true) { $conn2 = new MgSiteConnection(); $user2 = new MgUserInformation($this->sessionId); $conn2->Open($user2); $site2 = $conn2->GetSite(); $site2->DestroySession($this->sessionId); } } catch (MgException $ex) { $this->OnException($ex); } }
* Purpose: Measure a feature *****************************************************************************/ include 'Common.php'; include 'Utilities.php'; try { if (!isset($_REQUEST['session']) || !isset($_REQUEST['mapname']) || !isset($_REQUEST['x1']) || !isset($_REQUEST['y1']) || !isset($_REQUEST['x2']) || !isset($_REQUEST['y2'])) { echo "<Error>Arguments missing </Error>"; exit; } $x1 = $_REQUEST['x1']; $y1 = $_REQUEST['y1']; $x2 = $_REQUEST['x2']; $y2 = $_REQUEST['y2']; $map = new MgMap(); $map->Open($resourceService, $mapName); $srsFactory = new MgCoordinateSystemFactory(); $srs = GetMapSRS($map); $srsMap = $srsFactory->Create($srs); $srsType = $srsMap->GetType(); if ($srsType == MgCoordinateSystemType::Geographic) { $distance = $srsMap->MeasureGreatCircleDistance($x1, $y1, $x2, $y2); } else { $distance = $srsMap->MeasureEuclideanDistance($x1, $y1, $x2, $y2); } $distance = $srsMap->ConvertCoordinateSystemUnitsToMeters($distance); header('Content-type: text/x-json'); header('X-JSON: true'); echo "{distance:{$distance}}"; exit; } catch (MgException $e) { echo "last error";
/** keep all the attributes of selected features in an array */ function BuildSelectionArray($featureReader, $layerName, $properties, $bComputedProperties, $srsLayer, $bNeedsTransform, $layerObj, $isLayerNameEncoded) { $agf = new MgAgfReaderWriter(); $srsFactory = new MgCoordinateSystemFactory(); if ($isLayerNameEncoded) { // Add prefix to avoid layer name beginning with number // So $isLayerNameEncoded should be true when and only when the properties will be stored in session $layerName = GetEncodedLayerName($layerName); } $properties->{$layerName}->propertynames = array(); $properties->{$layerName}->propertyvalues = array(); $properties->{$layerName}->propertytypes = array(); $properties->{$layerName}->numelements = 0; $properties->{$layerName}->values = array(); $properties->{$layerName}->metadatanames = array(); array_push($properties->{$layerName}->metadatanames, 'dimension'); array_push($properties->{$layerName}->metadatanames, 'bbox'); array_push($properties->{$layerName}->metadatanames, 'center'); array_push($properties->{$layerName}->metadatanames, 'area'); array_push($properties->{$layerName}->metadatanames, 'length'); if (isset($_SESSION)) { $mappings = $_SESSION['property_mappings'][$layerObj->GetObjectId()]; foreach ((array) $mappings as $name => $value) { $propType = $featureReader->GetPropertyType($name); array_push($properties->{$layerName}->propertynames, $name); array_push($properties->{$layerName}->propertyvalues, $value); array_push($properties->{$layerName}->propertytypes, $propType); } } $srsTarget = null; $srsXform = null; while ($featureReader->ReadNext()) { $properties->{$layerName}->values[$properties->{$layerName}->numelements] = array(); $properties->{$layerName}->metadata[$properties->{$layerName}->numelements] = array(); $dimension = ''; $bbox = ''; $center = ''; $area = ''; $length = ''; if ($bComputedProperties) { $classDef = $featureReader->GetClassDefinition(); $geomName = $classDef->GetDefaultGeometryPropertyName(); if ($geomName != '') { $geomByteReader = $featureReader->GetGeometry($geomName); /* is this needed? We declare one outside the loop too?*/ $agf = new MgAgfReaderWriter(); $geom = $agf->Read($geomByteReader); $envelope = $geom->Envelope(); $ll = $envelope->GetLowerLeftCoordinate(); $ur = $envelope->GetUpperRightCoordinate(); $bbox = $ll->GetX() . ',' . $ll->GetY() . ',' . $ur->GetX() . ',' . $ur->GetY(); $centroid = $geom->GetCentroid()->GetCoordinate(); $center = $centroid->GetX() . ',' . $centroid->GetY(); /* 0 = point, 1 = curve, 2 = surface */ $dimension = $geom->GetDimension(); if ($geom->GetDimension() > 0) { //conver the geometry to UTM auto so that local measurements //are accruate in meters if ($bNeedsTransform && $srsTarget == null && $srsXform == null) { $wkt = getUtmWkt($centroid->GetX(), $centroid->GetY()); $srsTarget = $srsFactory->Create($wkt); $verMajor = subStr(GetSiteVersion(), 0, 1); if ($verMajor == '1') { $srsXform = new MgCoordinateSystemTransform($srsLayer, $srsTarget); } else { $srsXform = $srsFactory->GetTransform($srsLayer, $srsTarget); } } if ($srsXform != null) { try { $ageom = $geom->Transform($srsXform); $geom = $ageom; } catch (MgException $ee) { echo "/*transform exception:"; echo "ERROR: " . $ee->GetExceptionMessage() . "\n"; echo $ee->GetDetails() . "\n*/"; } } if ($geom->GetDimension() > 1) { $area = $geom->GetArea(); } if ($geom->GetDimension() > 0) { $length = $geom->GetLength(); } } } } array_push($properties->{$layerName}->metadata[$properties->{$layerName}->numelements], $dimension); array_push($properties->{$layerName}->metadata[$properties->{$layerName}->numelements], $bbox); array_push($properties->{$layerName}->metadata[$properties->{$layerName}->numelements], $center); array_push($properties->{$layerName}->metadata[$properties->{$layerName}->numelements], $area); array_push($properties->{$layerName}->metadata[$properties->{$layerName}->numelements], $length); $numproperties = count($properties->{$layerName}->propertynames); for ($j = 0; $j < $numproperties; $j++) { $propname = $properties->{$layerName}->propertynames[$j]; $value = GetPropertyValueFromFeatReader($featureReader, $properties->{$layerName}->propertytypes[$j], $propname); $value = htmlentities($value, ENT_COMPAT, 'UTF-8'); $value = addslashes($value); $value = preg_replace("/\r?\n/", "<br>", $value); array_push($properties->{$layerName}->values[$properties->{$layerName}->numelements], $value); //$properties->$layerName->values[$properties->$layerName->numelements][$propname] = $value; } $properties->{$layerName}->numelements = $properties->{$layerName}->numelements + 1; } return $properties; }
function DownloadMarkupAsKml($kmz = false) { $kmlService = $this->site->CreateService(MgServiceType::KmlService); $resourceService = $this->site->CreateService(MgServiceType::ResourceService); $map = new MgMap(); $map->Open($resourceService, $this->args['MAPNAME']); $markupLayerResId = new MgResourceIdentifier($this->args['MARKUPLAYER']); $downloadName = $markupLayerResId->GetName() . "." . ($kmz ? "kmz" : "kml"); //Find layer under _Markup with this layer def id $layerGroups = $map->GetLayerGroups(); if (!$layerGroups->Contains("_Markup")) { throw new Exception(GetLocalizedString("REDLINENOOPENLAYERS", $locale)); } $layers = $map->GetLayers(); $markupLayer = null; for ($i = 0; $i < $layers->GetCount(); $i++) { $layer = $layers->GetItem($i); $ldfId = $layer->GetLayerDefinition(); if (strcmp($ldfId->ToString(), $markupLayerResId->ToString()) == 0) { $markupLayer = $layer; break; } } if ($markupLayer == null) { throw new Exception(GetLocalizedString("REDLINEOPENLAYERNOTFOUND", $locale)); } //View extent crunching time $geomFact = new MgGeometryFactory(); $csFactory = new MgCoordinateSystemFactory(); $mapCs = $csFactory->Create($map->GetMapSRS()); $metersPerUnit = $mapCs->ConvertCoordinateSystemUnitsToMeters(1.0); $mapScale = $map->GetViewScale(); $devW = $map->GetDisplayWidth(); $devH = $map->GetDisplayHeight(); $mapDpi = $map->GetDisplayDpi(); $metersPerPixel = 0.0254 / $mapDpi; $mcsW = $mapScale * $devW * $metersPerPixel / $metersPerUnit; $mcsH = $mapScale * $devH * $metersPerPixel / $metersPerUnit; $center = $map->GetViewCenter(); $coord = $center->GetCoordinate(); $coord0 = $geomFact->CreateCoordinateXY($coord->GetX() - 0.5 * $mcsW, $coord->GetY() - 0.5 * $mcsH); $coord1 = $geomFact->CreateCoordinateXY($coord->GetX() + 0.5 * $mcsW, $coord->GetY() + 0.5 * $mcsH); $bbox = new MgEnvelope($coord0, $coord1); //Call the service API $br = $kmlService->GetFeaturesKml($markupLayer, $bbox, $devW, $devH, $mapDpi, 0, $kmz ? "KMZ" : "KML"); $len = $br->GetLength(); $outputBuffer = ''; $buffer = ''; while ($br->Read($buffer, 50000) != 0) { $outputBuffer .= $buffer; } header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename={$downloadName}"); header("Content-Length: " . strlen($outputBuffer)); echo $outputBuffer; }
private function DescribeRuntimeMapXml($mapDefinition, $map, $sessionId, $mapName, $iconFormat, $iconWidth, $iconHeight, $reqFeatures, $iconsPerScaleRange, $resSvc, $mappingSvc) { //TODO: Caching opportunity here $admin = new MgServerAdmin(); $admin->Open($this->userInfo); $siteVersion = $admin->GetSiteVersion(); $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; $xml .= "<RuntimeMap xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"RuntimeMap-2.6.0.xsd\">\n"; // ---------------------- Site Version --------------------------- // $xml .= "<SiteVersion>{$siteVersion}</SiteVersion>\n"; // ---------------------- Session ID --------------------------- // $xml .= "<SessionId>{$sessionId}</SessionId>\n"; // ---------------------- Map Name --------------------------- // $xml .= "<Name>{$mapName}</Name>\n"; // ---------------------- Map Definition --------------------------- // $xml .= "<MapDefinition>{$mapDefinition}</MapDefinition>\n"; // ---------------------- Background Color --------------------------- // $bgColor = $map->GetBackgroundColor(); $xml .= "<BackgroundColor>{$bgColor}</BackgroundColor>\n"; // ---------------------- Display DPI --------------------------- // $dpi = $map->GetDisplayDpi(); $xml .= "<DisplayDpi>{$dpi}</DisplayDpi>"; // ---------------------- Icon MIME Type --------------------------- // if (($reqFeatures & self::REQUEST_LAYER_ICONS) == self::REQUEST_LAYER_ICONS) { switch ($iconFormat) { case "JPG": $xml .= "<IconMimeType>" . MgMimeType::Jpeg . "</IconMimeType>\n"; break; case "GIF": $xml .= "<IconMimeType>" . MgMimeType::Gif . "</IconMimeType>\n"; break; case "PNG8": $xml .= "<IconMimeType>" . MgMimeType::Png . "</IconMimeType>\n"; break; default: $xml .= "<IconMimeType>" . MgMimeType::Png . "</IconMimeType>\n"; break; } } // ---------------------- Coordinate System --------------------------- // $csFactory = new MgCoordinateSystemFactory(); $metersPerUnit = 1.0; $wkt = $map->GetMapSRS(); $csCode = ""; $epsg = ""; try { $cs = $csFactory->Create($wkt); $metersPerUnit = $cs->ConvertCoordinateSystemUnitsToMeters(1.0); $epsg = $cs->GetEpsgCode(); $csCode = $cs->GetCsCode(); } catch (MgException $ex) { } $xml .= "<CoordinateSystem>\n<Wkt>{$wkt}</Wkt>\n<MentorCode>{$csCode}</MentorCode>\n<EpsgCode>{$epsg}</EpsgCode>\n<MetersPerUnit>{$metersPerUnit}</MetersPerUnit>\n</CoordinateSystem>"; // ---------------------- Map Extents--------------------------- // $extents = $map->GetMapExtent(); $ll = $extents->GetLowerLeftCoordinate(); $ur = $extents->GetUpperRightCoordinate(); $minX = $ll->GetX(); $minY = $ll->GetY(); $maxX = $ur->GetX(); $maxY = $ur->GetY(); $xml .= "<Extents>\n<LowerLeftCoordinate><X>{$minX}</X><Y>{$minY}</Y></LowerLeftCoordinate>\n<UpperRightCoordinate><X>{$maxX}</X><Y>{$maxY}</Y></UpperRightCoordinate></Extents>\n"; $layerDefinitionMap = array(); // ---------------------- Optional things if requested --------------------------- // if (($reqFeatures & self::REQUEST_LAYER_STRUCTURE) == self::REQUEST_LAYER_STRUCTURE) { $layers = $map->GetLayers(); $layerCount = $layers->GetCount(); //Build our LayerDefinition map for code below that requires it if (($reqFeatures & self::REQUEST_LAYER_ICONS) == self::REQUEST_LAYER_ICONS) { $layerIds = new MgStringCollection(); for ($i = 0; $i < $layerCount; $i++) { $layer = $layers->GetItem($i); $ldfId = $layer->GetLayerDefinition(); $layerIds->Add($ldfId->ToString()); } $layerContents = $resSvc->GetResourceContents($layerIds, null); $layerIdCount = $layerIds->GetCount(); for ($i = 0; $i < $layerIdCount; $i++) { $ldfId = $layerIds->GetItem($i); $content = $layerContents->GetItem($i); $layerDefinitionMap[$ldfId] = $content; } } // ----------- Some pre-processing before we do groups/layers ------------- // $groups = $map->GetLayerGroups(); $groupCount = $groups->GetCount(); for ($i = 0; $i < $groupCount; $i++) { $group = $groups->GetItem($i); $parent = $group->GetGroup(); $xml .= self::CreateGroupItem($group, $parent); } $doc = new DOMDocument(); for ($i = 0; $i < $layerCount; $i++) { $layer = $layers->GetItem($i); $parent = $layer->GetGroup(); $ldf = $layer->GetLayerDefinition(); $layerId = $ldf->ToString(); $layerDoc = null; if (array_key_exists($layerId, $layerDefinitionMap)) { $doc->loadXML($layerDefinitionMap[$layerId]); $layerDoc = $doc; } $xml .= self::CreateLayerItem($reqFeatures, $iconsPerScaleRange, $iconFormat, $iconWidth, $iconHeight, $layer, $parent, $layerDoc, $mappingSvc); } } else { //Base Layer Groups need to be outputted regardless, otherwise a client application doesn't have enough information to build GETTILEIMAGE requests $groups = $map->GetLayerGroups(); $groupCount = $groups->GetCount(); for ($i = 0; $i < $groupCount; $i++) { $group = $groups->GetItem($i); if ($group->GetLayerGroupType() != MgLayerGroupType::BaseMap) { continue; } $parent = $group->GetGroup(); $xml .= self::CreateGroupItem($group, $parent); } } // ------------------------ Finite Display Scales (if any) ------------------------- // $fsCount = $map->GetFiniteDisplayScaleCount(); if ($fsCount > 0) { for ($i = 0; $i < $fsCount; $i++) { $xml .= "<FiniteDisplayScale>"; $xml .= $map->GetFiniteDisplayScaleAt($i); $xml .= "</FiniteDisplayScale>"; } } $xml .= "</RuntimeMap>"; $bs = new MgByteSource($xml, strlen($xml)); $bs->SetMimeType(MgMimeType::Xml); $br = $bs->GetReader(); return $br; }
public function GetLayerKml($resId, $format = "kml") { //Check for unsupported representations $fmt = $this->ValidateRepresentation($format, array("kml", "kmz")); $width = $this->GetRequestParameter("width", null); $height = $this->GetRequestParameter("height", null); $drawOrder = $this->GetRequestParameter("draworder", null); $dpi = $this->GetRequestParameter("dpi", 96); $bbox = $this->GetRequestParameter("bbox", null); $extents = null; if ($width == null) { $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "width"), $this->GetMimeTypeForFormat($format)); } if ($height == null) { $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "height"), $this->GetMimeTypeForFormat($format)); } if ($drawOrder == null) { $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "draworder"), $this->GetMimeTypeForFormat($format)); } if ($bbox == null) { $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "bbox"), $this->GetMimeTypeForFormat($format)); } else { $parts = explode(",", $bbox); if (count($parts) == 4) { $extents = new MgEnvelope($parts[0], $parts[1], $parts[2], $parts[3]); } } $sessionId = ""; if ($resId->GetRepositoryType() == MgRepositoryType::Session) { $sessionId = $resId->GetRepositoryName(); } else { $sessionId = $this->GetRequestParameter("session", ""); } $this->EnsureAuthenticationForSite($sessionId, true); $siteConn = new MgSiteConnection(); if ($sessionId !== "") { $userInfo = new MgUserInformation($sessionId); $siteConn->Open($userInfo); } else { $siteConn->Open($this->userInfo); $site = $siteConn->GetSite(); $sessionId = $site->CreateSession(); $userInfo = new MgUserInformation($sessionId); $siteConn->Open($userInfo); } $csFactory = new MgCoordinateSystemFactory(); $csObj = $csFactory->CreateFromCode("LL84"); $scale = MgUtils::GetScale($extents, $csObj, $width, $height, $dpi); $writer = new MgSlimChunkWriter($this->app); $doc = new MgKmlDocument($writer); $resSvc = $siteConn->CreateService(MgServiceType::ResourceService); $featSvc = $siteConn->CreateService(MgServiceType::FeatureService); $ldfContent = $resSvc->GetResourceContent($resId); $xml = new DOMDocument(); $xml->loadXML($ldfContent->ToString()); $destExtent = self::GetLayerExtent($csFactory, $xml, $csObj, $featSvc, $resSvc); $doc->StartDocument(); $doc->WriteString("<visibility>1</visibility>"); if ($destExtent != null) { $widthMeters = $csObj->ConvertCoordinateSystemUnitsToMeters($destExtent->GetWidth()); $heightMeters = $csObj->ConvertCoordinateSystemUnitsToMeters($destExtent->GetHeight()); $dimension = sqrt($widthMeters * $heightMeters); $vlNodes = $xml->getElementsByTagName("VectorLayerDefinition"); $glNodes = $xml->getElementsByTagName("GridLayerDefinition"); $dlNodes = $xml->getElementsByTagName("DrawingLayerDefinition"); if ($vlNodes->length == 1) { $scaleRangeNodes = $vlNodes->item(0)->getElementsByTagName("VectorScaleRange"); for ($i = 0; $i < $scaleRangeNodes->length; $i++) { $scaleRange = $scaleRangeNodes->item($i); $minElt = $scaleRange->getElementsByTagName('MinScale'); $maxElt = $scaleRange->getElementsByTagName('MaxScale'); $minScale = "0"; $maxScale = 'infinity'; // as MDF's VectorScaleRange::MAX_MAP_SCALE if ($minElt->length > 0) { $minScale = $minElt->item(0)->nodeValue; } if ($maxElt->length > 0) { $maxScale = $maxElt->item(0)->nodeValue; } if ($minScale != 'infinity') { $minScale = intval($minScale); } if ($maxScale != 'infinity') { $maxScale = intval($maxScale); } else { $maxScale = 1000000000000.0; } // as MDF's VectorScaleRange::MAX_MAP_SCALE if ($scale > $minScale && $scale <= $maxScale) { $this->AppendScaleRange($resId, $destExtent, $dimension, $minScale, $maxScale, $dpi, $drawOrder, $format, $sessionId, $doc); } } } else { if ($glNodes->length == 1) { } } } $doc->EndDocument(); }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> <?php include "initwebtier.php"; $code = ""; $wkt = ""; $errorMsg = ""; $status = ""; try { echo "<b>Coordinate System API: ConvertCoordinateSystemCodeToWkt</b><br><br>"; $factory = new MgCoordinateSystemFactory(); $code = $_GET['CODE']; $wkt = $factory->ConvertCoordinateSystemCodeToWkt($code); $status = "Pass"; } catch (MgException $e) { $errorMsg = $e->GetExceptionMessage(); $status = "Fail"; } catch (Exception $e) { $errorMsg = $e->getMessage(); $status = "Fail"; } echo "<b>Code:</b><br>"; echo "{$code}<br><br>"; echo "<b>OGC WKT:</b><br>"; echo "{$wkt}<br><br>"; echo "<b>Status:</b><br>"; echo "{$status}<br><br>"; if ($errorMsg != "") { echo "<b>Error:</b><br>"; echo $errorMsg;
$sel = new MgSelection($map); $sel->Save($resourceService, $mapName); $map->Save($resourceService, $mapStateId); } else { $map = new MgMap(); $map->Open($resourceService, $mapName); $mapTitle = $map->GetName(); $mapid = $map->GetMapDefinition()->ToString(); } $extents = $map->GetMapExtent(); @($oMin = $extents->GetLowerLeftCoordinate()); @($oMax = $extents->GetUpperRightCoordinate()); @($srs = $map->GetMapSRS()); $epsgCode = ""; if ($srs != "") { @($csFactory = new MgCoordinateSystemFactory()); @($cs = $csFactory->Create($srs)); @($metersPerUnit = $cs->ConvertCoordinateSystemUnitsToMeters(1.0)); try { $epsgCode = $csFactory->ConvertWktToEpsgCode($srs); // Convert EPSG code 3857 to the equivalent code 900913 that is understood by OpenLayers if ($epsgCode == 3857) { $epsgCode = 900913; // We need to set the srs code to null because OpenLayers doesn't know the srs code. $srs = ""; } } catch (MgException $e) { //just catch the exception and set epsgCode to empty string } // $unitsType = $cs->GetUnits(); } else {
curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $data = curl_exec($ch); curl_close($ch); if (strpos($data, "Not found") !== false) { return null; } else { return $data; } } $file = fopen("csmap2proj4.js", "w"); fwrite($file, "/*\n csmap2proj4.js - A Mentor code to proj4 string lookup table\n\n This file was generated by CsMap2Proj.php\n */\n"); $grandTotal = 0; $mappedTotal = 0; $csFactory = new MgCoordinateSystemFactory(); $csCategories = $csFactory->EnumerateCategories(); for ($k = 0; $k < $csCategories->GetCount(); $k++) { $category = $csCategories->GetItem($k); echo ">>> Fetching CS-Map coordinate systems: {$category} <<<\n"; $csCodes = $csFactory->EnumerateCoordinateSystems($category); $mapped = 0; $grandTotal += $csCodes->GetCount(); for ($i = 0; $i < $csCodes->GetCount(); $i++) { $csProps = $csCodes->GetItem($i); for ($j = 0; $j < $csProps->GetCount(); $j++) { $prop = $csProps->GetItem($j); if (strcmp(strtolower($prop->GetName()), "code") == 0) { try { $csCode = $prop->GetValue(); $csWkt = $csFactory->ConvertCoordinateSystemCodeToWkt($csCode);
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> <?php include "initwebtier.php"; $code = ""; $wkt = ""; $errorMsg = ""; $status = ""; try { echo "<b>Coordinate System API: ConvertWktToEpsgCode</b><br><br>"; $factory = new MgCoordinateSystemFactory(); $wkt = $_GET['WKT']; $code = $factory->ConvertWktToEpsgCode($wkt); $status = "Pass"; } catch (MgException $e) { $errorMsg = $e->GetExceptionMessage(); $status = "Fail"; } catch (Exception $e) { $errorMsg = $e->getMessage(); $status = "Fail"; } echo "<b>OGC WKT:</b><br>"; echo "{$wkt}<br><br>"; echo "<b>EPSG Code:</b><br>"; echo "{$code}<br><br>"; echo "<b>Status:</b><br>"; echo "{$status}<br><br>"; if ($errorMsg != "") { echo "<b>Error:</b><br>"; echo $errorMsg;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> <?php include "initwebtier.php"; $errorMsg = ""; $status = ""; try { echo "<b>Coordinate System API: EnumerateCategories</b><br><br>"; $factory = new MgCoordinateSystemFactory(); // Get the list of categories $categories = $factory->EnumerateCategories(); $count = $categories->GetCount(); echo "<b>Coordinate System Categories: </b>{$count}<br>"; for ($i = 1; $i <= $count; $i++) { $category = $categories->GetItem($i - 1); echo "<b>{$i}: </b>{$category}<br>"; } echo "<br>"; $status = "Pass"; } catch (MgException $e) { $errorMsg = $e->GetExceptionMessage(); $status = "Fail"; } catch (Exception $e) { $errorMsg = $e->getMessage(); $status = "Fail"; } echo "<b>Status:</b><br>"; echo "{$status}<br><br>"; if ($errorMsg != "") { echo "<b>Error:</b><br>";
echo "<Error>Arguments missing </Error>"; exit; } /* if merge is set, buffer the entire selection as one instead of creating buffers * on each selected feature */ $merge = isset($_REQUEST['merge']) && $_REQUEST['merge'] == 1 ? true : false; $layerName = $_REQUEST['layer']; $distance = $_REQUEST['distance']; $fillColor = $_REQUEST['fillcolor']; $borderColor = $_REQUEST['bordercolor']; $schemaName = 'BufferSchema'; $map = new MgMap(); $map->Open($resourceService, $mapName); /* Get the map SRS - we use this to convert distances */ $srsFactory = new MgCoordinateSystemFactory(); //safely get an SRS ... (in Utilities) $srsDefMap = GetMapSRS($map); $mapSrsUnits = ""; $srsMap = $srsFactory->Create($srsDefMap); $arbitraryMapSrs = $srsMap->GetType() == MgCoordinateSystemType::Arbitrary; if ($arbitraryMapSrs) { $mapSrsUnits = $srsMap->GetUnits(); } $featureService = $siteConnection->CreateService(MgServiceType::FeatureService); $agfRW = new MgAgfReaderWriter(); $layers = $map->GetLayers(); try { /* if the layer already exists, we'll clear the existing features * from it and reset the content */
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?"); } }
$selText = ""; GetRequestParameters(); try { //load the map runtime state // $map = new MgMap(); $map->Open($resourceService, $mapName); // Create the selection set $selection = new MgSelection($map); if ($selText != "") { $selection->FromXml($selText); } //now return a data struture which is the same as Query.php $featureService = $siteConnection->CreateService(MgServiceType::FeatureService); /* 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); /*holds selection array*/ $properties = NULL; $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++) {
echo "<b>{$propertyName}: </b>{$val}<br>"; } } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> <?php include "initwebtier.php"; $category = ""; $errorMsg = ""; $status = ""; try { echo "<b>Coordinate System API: EnumerateCoordinateSystems</b><br><br>"; $factory = new MgCoordinateSystemFactory(); // Get the list of coordinate systems for the specified category $category = $_GET['CATEGORY']; $systems = $factory->EnumerateCoordinateSystems($category); $count = $systems->GetCount(); echo "<b>Category: </b>{$category}<br>"; echo "<b>Coordinate Systems: </b>{$count}<br><br>"; for ($i = 1; $i <= $count; $i++) { $system = $systems->GetItem($i - 1); echo "<b>Coordinate System {$i}</b><br>"; printPropertyCollection($system); echo "<br>"; } echo "<br>"; $status = "Pass"; } catch (MgException $e) {
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> <?php include "initwebtier.php"; $wkt = ""; $errorMsg = ""; $status = ""; try { echo "<b>Coordinate System API: CheckWkt</b><br><br>"; $factory = new MgCoordinateSystemFactory(); $wkt = $_GET['WKT']; $mgcoordinatesystem = $factory->Create($wkt); $status = "Pass"; } catch (MgException $e) { $errorMsg = $e->GetExceptionMessage(); $status = "Fail"; } catch (Exception $e) { $errorMsg = $e->getMessage(); $status = "Fail"; } echo "<b>OGC WKT:</b><br>"; echo "{$wkt}<br><br>"; echo "<b>Status:</b><br>"; echo "{$status}<br><br>"; if ($errorMsg != "") { echo "<b>Error:</b><br>"; echo $errorMsg; } ?>
//miles $distance *= 1609.35; } else { if ($units == "ki") { //kilometers $distance *= 1000; } else { if ($units == "fe") { //feet $distance *= 0.3048; } } } // Get the map SRS // $srsFactory = new MgCoordinateSystemFactory(); $srsDefMap = GetMapSRS($map); $mapSrsUnits = ""; $srsMap = $srsFactory->Create($srsDefMap); $arbitraryMapSrs = $srsMap->GetType() == MgCoordinateSystemType::Arbitrary; if ($arbitraryMapSrs) { $mapSrsUnits = $srsMap->GetUnits(); } //Create/Modify layer definition $layerDefContent = BuildLayerDefinitionContent(); $resourceSrvc->SetResource($layerDefId, $layerDefContent, null); if ($layer == null) { $newBuffer = true; //Targetting a new layer. create a data source for it // $classDef = new MgClassDefinition();
function GetLayerToMapCSTrans($classDef, $geomPropName, $featureSrvc, $fsId, $map) { $props = $classDef->GetProperties(); $geomProp = $props->GetItem($geomPropName); $scAssociation = $geomProp->GetSpatialContextAssociation(); $csrdr = $featureSrvc->GetSpatialContexts($fsId, false); $layerwkt = ''; while($csrdr->ReadNext()) { $csrName = $csrdr->GetName(); if($csrName == $scAssociation) { // Match found for the association $layerwkt = $csrdr->GetCoordinateSystemWkt(); break; } } $csrdr->Close(); $cf = new MgCoordinateSystemFactory(); $layerCS = $cf->Create($layerwkt); $mapCS = $cf->Create($map->GetMapSRS()); $trans = $cf->GetTransform ($layerCS, $mapCS); return $trans; }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> <?php include "initwebtier.php"; $code = ""; $wkt = ""; $errorMsg = ""; $status = ""; try { echo "<b>Coordinate System API: ConvertEpsgCodeToWkt</b><br><br>"; $factory = new MgCoordinateSystemFactory(); $code = $_GET['CODE']; $epsgcode = 0 + $code; // Convert to an integer $wkt = $factory->ConvertEpsgCodeToWkt($epsgcode); $status = "Pass"; } catch (MgException $e) { $errorMsg = $e->GetExceptionMessage(); $status = "Fail"; } catch (Exception $e) { $errorMsg = $e->getMessage(); $status = "Fail"; } echo "<b>EPSG Code:</b><br>"; echo "{$code}<br><br>"; echo "<b>OGC WKT:</b><br>"; echo "{$wkt}<br><br>"; echo "<b>Status:</b><br>"; echo "{$status}<br><br>"; if ($errorMsg != "") {
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> <?php include "initwebtier.php"; $library = ""; $errorMsg = ""; $status = ""; try { echo "<b>Coordinate System API: GetBaseLibrary</b><br><br>"; $factory = new MgCoordinateSystemFactory(); $library = $factory->GetBaseLibrary(); $status = "Pass"; } catch (MgException $e) { $errorMsg = $e->GetExceptionMessage(); $status = "Fail"; } catch (Exception $e) { $errorMsg = $e->getMessage(); $status = "Fail"; } echo "<b>Library:</b><br>"; echo "{$library}<br><br>"; echo "<b>Status:</b><br>"; echo "{$status}<br><br>"; if ($errorMsg != "") { echo "<b>Error:</b><br>"; echo $errorMsg; } ?> </body>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> <?php include "initwebtier.php"; $wkt = ""; $errorMsg = ""; $status = ""; try { echo "<b>Coordinate System API: IsValid</b><br><br>"; $factory = new MgCoordinateSystemFactory(); $wkt = $_GET['WKT']; $result = $factory->IsValid($wkt); if ($result == true) { $status = "Pass"; } else { $status = "Fail"; } } catch (MgException $e) { $errorMsg = $e->GetExceptionMessage(); $status = "Fail"; } catch (Exception $e) { $errorMsg = $e->getMessage(); $status = "Fail"; } echo "<b>OGC WKT:</b><br>"; echo "{$wkt}<br><br>"; echo "<b>Status:</b><br>"; echo "{$status}<br><br>"; if ($errorMsg != "") { echo "<b>Error:</b><br>";
public static function GetFeatureClassMBR($app, $featureSrvc, $featuresId, $schemaName, $className, $geomName = null, $transformToCsCode = null) { $extentGeometryAgg = null; $extentGeometrySc = null; $extentByteReader = null; $mbr = new stdClass(); $csFactory = new MgCoordinateSystemFactory(); $clsDef = $featureSrvc->GetClassDefinition($featuresId, $schemaName, $className); $props = $clsDef->GetProperties(); if ($geomName == null) { $geomName = $clsDef->GetDefaultGeometryPropertyName(); } $geomProp = $props->GetItem($geomName); if ($geomProp->GetPropertyType() != MgFeaturePropertyType::GeometricProperty) { throw new Exception($app->localizer->getText("E_NOT_GEOMETRY_PROPERTY", $geomName)); } $spatialContext = $geomProp->GetSpatialContextAssociation(); // Finds the coordinate system $agfReaderWriter = new MgAgfReaderWriter(); $spatialcontextReader = $featureSrvc->GetSpatialContexts($featuresId, false); while ($spatialcontextReader->ReadNext()) { if ($spatialcontextReader->GetName() == $spatialContext) { $mbr->coordinateSystem = $spatialcontextReader->GetCoordinateSystemWkt(); $mbr->csCode = $csFactory->ConvertWktToCoordinateSystemCode($mbr->coordinateSystem); $mbr->epsg = $csFactory->ConvertWktToEpsgCode($mbr->coordinateSystem); // Finds the extent $extentByteReader = $spatialcontextReader->GetExtent(); break; } } $spatialcontextReader->Close(); if ($extentByteReader != null) { // Get the extent geometry from the spatial context $extentGeometrySc = $agfReaderWriter->Read($extentByteReader); } // Try to get the extents using the selectaggregate as sometimes the spatial context // information is not set $aggregateOptions = new MgFeatureAggregateOptions(); $featureProp = 'SPATIALEXTENTS("' . $geomName . '")'; $aggregateOptions->AddComputedProperty('EXTENTS', $featureProp); try { $dataReader = $featureSrvc->SelectAggregate($featuresId, $className, $aggregateOptions); if ($dataReader->ReadNext()) { // Get the extents information $byteReader = $dataReader->GetGeometry('EXTENTS'); $extentGeometryAgg = $agfReaderWriter->Read($byteReader); } $dataReader->Close(); } catch (MgException $e) { if ($extentGeometryAgg == null) { //We do have one last hope. EXTENT() is an internal MapGuide custom function that's universally supported //as it operates against an underlying select query result. This raw-spins the reader server-side so there //is no server -> web tier transmission overhead involved. try { $aggregateOptions = new MgFeatureAggregateOptions(); $aggregateOptions->AddComputedProperty("COMP_EXTENT", "EXTENT(" . $geomName . ")"); $dataReader = $featureSrvc->SelectAggregate($featuresId, $className, $aggregateOptions); if ($dataReader->ReadNext()) { // Get the extents information $byteReader = $dataReader->GetGeometry('COMP_EXTENT'); $extentGeometryAgg = $agfReaderWriter->Read($byteReader); } $dataReader->Close(); } catch (MgException $e2) { } } } $mbr->extentGeometry = null; // Prefer SpatialExtents() of EXTENT() result over spatial context extent if ($extentGeometryAgg != null) { $mbr->extentGeometry = $extentGeometryAgg; } if ($mbr->extentGeometry == null) { //Stil null? Now try spatial context if ($extentGeometrySc != null) { $mbr->extentGeometry = $extentGeometrySc; } } if ($transformToCsCode != null) { $sourceCs = $csFactory->CreateFromCode($mbr->csCode); $targetCs = $csFactory->CreateFromCode($transformToCsCode); $xform = $csFactory->GetTransform($sourceCs, $targetCs); $mbr->extentGeometry = $mbr->extentGeometry->Transform($xform); $mbr->csCode = $targetCs->GetCsCode(); $mbr->epsg = $targetCs->GetEpsgCode(); } return $mbr; }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> <?php include "initwebtier.php"; $code = ""; $wkt = ""; $errorMsg = ""; $status = ""; try { echo "<b>Coordinate System API: ConvertWktToCoordinateSystemCode</b><br><br>"; $factory = new MgCoordinateSystemFactory(); $wkt = $_GET['WKT']; $code = $factory->ConvertWktToCoordinateSystemCode($wkt); $status = "Pass"; } catch (MgException $e) { $errorMsg = $e->GetExceptionMessage(); $status = "Fail"; } catch (Exception $e) { $errorMsg = $e->getMessage(); $status = "Fail"; } echo "<b>OGC WKT:</b><br>"; echo "{$wkt}<br><br>"; echo "<b>Code:</b><br>"; echo "{$code}<br><br>"; echo "<b>Status:</b><br>"; echo "{$status}<br><br>"; if ($errorMsg != "") { echo "<b>Error:</b><br>"; echo $errorMsg;
$sel->Save($resourceService, $mapName); $map->Save($resourceService, $mapStateId); } else { $map = new MgMap(); $map->Open($resourceService, $mapName); $mapTitle = $map->GetName(); $mapid = $map->GetMapDefinition()->ToString(); } //$sessionId = $map->GetSessionId(); //$mapName = $map->GetName() ; $extents = $map->GetMapExtent(); @($oMin = $extents->GetLowerLeftCoordinate()); @($oMax = $extents->GetUpperRightCoordinate()); @($srs = $map->GetMapSRS()); if ($srs != "") { @($csFactory = new MgCoordinateSystemFactory()); @($cs = $csFactory->Create($srs)); @($metersPerUnit = $cs->ConvertCoordinateSystemUnitsToMeters(1.0)); // $unitsType = $cs->GetUnits(); } else { $metersPerUnit = 1.0; //$unitsType = "Meters"; } header('Content-type: text/x-json'); header('X-JSON: true'); echo "{"; echo "sessionId:'{$sessionID}',"; echo "mapId:'{$mapid}',"; echo "metersPerUnit:{$metersPerUnit},"; //echo "mapTitle:'".addslashes(htmlentities($mapTitle))."',"; //echo "mapName:'".addslashes(htmlentities($mapName))."',";
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; }
if (isset($_POST['SELECTION']) && $_POST['SELECTION'] != '') { $selection = new MgSelection($map, $_POST['SELECTION']); $selectedLayers = $selection->GetLayers(); } else { $selectedLayers = 0; } if ($selectedLayers) { include 'bufferfunctions.php'; $bufferRingSize = 100; // measured in metres $bufferRingCount = 5; // Set up some objects for coordinate conversion $mapWktSrs = $map->GetMapSRS(); $agfReaderWriter = new MgAgfReaderWriter(); $wktReaderWriter = new MgWktReaderWriter(); $coordinateSystemFactory = new MgCoordinateSystemFactory(); $srs = $coordinateSystemFactory->Create($mapWktSrs); $srsMeasure = $srs->GetMeasure(); // Check for a buffer layer. If it exists, delete // the current features. // If it does not exist, create a feature source and // a layer to hold the buffer. /* // Old way, pre MapGuide OS 2.0. Kept here for reference try { $bufferLayer = $map->GetLayers()->GetItem('Buffer'); $bufferFeatureResId = new MgResourceIdentifier($bufferLayer->GetFeatureSourceId()); $commands = new MgFeatureCommandCollection(); $commands->Add(new MgDeleteFeatures('BufferClass', "ID like '%'"));
/* add the features to the map selection and save it*/ $selection = new MgSelection($map); /* if extending the current selection */ $bExtendSelection = isset($_REQUEST['extendselection']) && strcasecmp($_REQUEST['extendselection'], 'true') == 0; if ($bExtendSelection) { $aLayerSelections = array(); $selection->Open($resourceService, $mapName); $aLayers = selectionToArray($selection, array()); } $bComputedProperties = isset($_REQUEST['computed']) && strcasecmp($_REQUEST['computed'], 'true') == 0; $bQueryHiddenLayers = isset($_REQUEST['queryHiddenLayers']) && strcasecmp($_REQUEST['queryHiddenLayers'], 'true') == 0; /*holds selection array*/ $properties = NULL; $properties->layers = array(); /* 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); $mapLayers = $map->GetLayers(); $bAllLayers = false; $nLayers = count($layers); if ($nLayers == 0) { $nLayers = $mapLayers->GetCount(); $bAllLayers = true; } for ($i = 0; $i < $nLayers; $i++) { try { if (!$bAllLayers) { $layerObj = $mapLayers->GetItem($layers[$i]); } else {
$mapCenterY = $args['CENTERY']; 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); // Create the necessary services. $resourceService = $siteConnection->CreateService(MgServiceType::ResourceService); $renderingService = $siteConnection->CreateService(MgServiceType::RenderingService); // Open the map and get its SRS $map = new MgMap(); $map->Open($resourceService, $mapName); $srsWkt = $map->GetMapSRS(); $coordinateSystemFactory = new MgCoordinateSystemFactory(); $srs = $coordinateSystemFactory->Create($srsWkt); if ($xmlSelection != '') { $selection = new MgSelection($map, $xmlSelection); } else { $selection = new MgSelection($map); } $color = new MgColor(205, 189, 156); $geometryFactory = new MgGeometryFactory(); $mapCenterCoordinate = $geometryFactory->CreateCoordinateXY($mapCenterX, $mapCenterY); // Convert the height in pixels to map units. // Create an envelope that contains the image area to display. $displayInInches = $imageHeight / 96; $displayInMeters = $displayInInches * 0.0254; $mapHeightInMeters = $displayInMeters * $mapScale; $mapHeightInMapUnits = $srs->ConvertMetersToCoordinateSystemUnits($mapHeightInMeters);