Esempio n. 1
0
 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);
 }
Esempio n. 2
0
/**
  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;
}
Esempio n. 3
0
 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 ConvertWktToEpsg($wkt, $format)
 {
     //Check for unsupported representations
     $fmt = $this->ValidateRepresentation($format, array("xml", "json"));
     $factory = new MgCoordinateSystemFactory();
     $cs = $factory->Create($wkt);
     $body = MgBoxedValue::Int32($cs->GetEpsgCode(), $fmt);
     if ($fmt == "xml") {
         $this->app->response->header("Content-Type", MgMimeType::Xml);
     } else {
         $this->app->response->header("Content-Type", MgMimeType::Json);
     }
     $this->app->response->setBody($body);
 }
 private function _GetKmlForMap($map, $sessionId, $format = "kml", $chunk = "1")
 {
     if ($chunk === "0") {
         $writer = new MgSlimChunkWriter($this->app);
     } else {
         $writer = new MgHttpChunkWriter();
     }
     $doc = new MgKmlDocument($writer);
     $csFactory = new MgCoordinateSystemFactory();
     $doc->StartDocument();
     $doc->WriteString("<visibility>1</visibility>");
     $layers = $map->GetLayers();
     $extent = $map->GetMapExtent();
     if ($extent != NULL) {
         $wkt = $map->GetMapSRS();
         if ($wkt != NULL && strlen($wkt) > 0) {
             $mapCs = $csFactory->Create($wkt);
             $llCs = $csFactory->CreateFromCode("LL84");
             $trans = $csFactory->GetTransform($mapCs, $llCs);
             $trans->IgnoreDatumShiftWarning(true);
             $trans->IgnoreOutsideDomainWarning(true);
             $extent = $trans->Transform($extent);
         }
     }
     $numLayers = $layers->GetCount();
     for ($i = 0; $i < $numLayers; $i++) {
         $layer = $layers->GetItem($i);
         $this->AppendLayer($layer, $extent, $numLayers - $i, $format, $sessionId, $writer);
     }
     $doc->EndDocument();
 }
Esempio n. 7
0
 /**
  * Builds a coordinate system transform from the class definition's coordinate system to the target
  * coordinate system indicated by the given coordinate system code
  */
 public static function GetTransform($featSvc, $resId, $schemaName, $className, $transformto, $bInvert = false)
 {
     $transform = null;
     $factory = new MgCoordinateSystemFactory();
     $targetWkt = $factory->ConvertCoordinateSystemCodeToWkt($transformto);
     $clsDef = $featSvc->GetClassDefinition($resId, $schemaName, $className);
     //Has a designated geometry property, use it's spatial context
     if ($clsDef->GetDefaultGeometryPropertyName() !== "") {
         $props = $clsDef->GetProperties();
         $idx = $props->IndexOf($clsDef->GetDefaultGeometryPropertyName());
         if ($idx >= 0) {
             $geomProp = $props->GetItem($idx);
             $scName = $geomProp->GetSpatialContextAssociation();
             $scReader = $featSvc->GetSpatialContexts($resId, false);
             while ($scReader->ReadNext()) {
                 if ($scReader->GetName() === $scName) {
                     if ($scReader->GetCoordinateSystemWkt() !== $targetWkt) {
                         $targetCs = $factory->CreateFromCode($transformto);
                         $sourceCs = $factory->Create($scReader->GetCoordinateSystemWkt());
                         if ($bInvert) {
                             $transform = $factory->GetTransform($targetCs, $sourceCs);
                         } else {
                             $transform = $factory->GetTransform($sourceCs, $targetCs);
                         }
                         break;
                     }
                 }
             }
             $scReader->Close();
         }
     }
     return $transform;
 }
Esempio n. 8
0
 /**
  * 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);
     }
 }
Esempio n. 9
0
     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();
     $classDef->SetName($featureName);
     $classDef->SetDescription(GetLocalizedString("BUFFERCLASSDESCR", $locale));
     $classDef->SetDefaultGeometryPropertyName("GEOM");
Esempio n. 10
0
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;
}
Esempio n. 11
0
<!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;
}
?>
Esempio n. 12
0
  * 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
      */
     $bValidLayer = false;
     $j = 2;
     while (!$bValidLayer) {
         $layer = $layers->GetItem($layerName);
 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?");
     }
 }
Esempio n. 14
0
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";
    echo "ERROR: " . $e->GetMessage() . "\n";
    echo $e->GetDetails() . "\n";
Esempio n. 15
0
     $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))."',";
 echo "mapTitle:'" . addslashes($mapTitle) . "',";
Esempio n. 16
0
 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;
 }
Esempio n. 17
0
     $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 '%'"));
     
Esempio n. 18
0
 $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 {
             $layerObj = $mapLayers->GetItem($i);
         }
         $bVisFlag = $layerObj->IsVisible() || $bQueryHiddenLayers;
Esempio n. 19
0
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);
    $envelopeOffsetY = $mapHeightInMapUnits / 2;