function CreatePolygon($coordinates) { $geometryFactory = new MgGeometryFactory(); $coordinateCollection = new MgCoordinateCollection(); $linearRingCollection = new MgLinearRingCollection(); for ($index = 0; $index < count($coordinates); ++$index) { $coordinate = $geometryFactory->CreateCoordinateXY(ParseLocaleDouble($coordinates[$index]), ParseLocaleDouble($coordinates[++$index])); $coordinateCollection->Add($coordinate); } $coordinateCollection->Add($geometryFactory->CreateCoordinateXY(ParseLocaleDouble($coordinates[0]), ParseLocaleDouble($coordinates[1]))); $linearRingCollection = $geometryFactory->CreateLinearRing($coordinateCollection); $captureBox = $geometryFactory->CreatePolygon($linearRingCollection, null); return $captureBox; }
private function CreatePolygonFromGeomText($geomText) { $geometryFactory = new MgGeometryFactory(); $vertices = explode(',', $geomText); $count = $vertices[0]; $coords = new MgCoordinateCollection(); for ($i = 0; $i < $count; $i++) { $coord = $geometryFactory->CreateCoordinateXY((double) $vertices[$i * 2 + 1], (double) $vertices[$i * 2 + 2]); $coords->Add($coord); } $linearRing = $geometryFactory->CreateLinearRing($coords); $polygon = $geometryFactory->CreatePolygon($linearRing, null); return $polygon; }
$layerName = 'Library://TrevorWekel/NewSdf.FeatureSource'; $id = new MgResourceIdentifier($layerName); try { $svc->CreateFeatureSource($id, $params); } catch (MgException $exc) { echo $exc->GetExceptionMessage() . "\n"; echo $exc->GetDetails() . "\n"; return; } echo "Created featuresource\n"; // We need to add some data to the sdf before using it. The spatial context // reader must have an extent. $batchProp = new MgBatchPropertyCollection(); $wkt = new MgWktReaderWriter(); $agf = new MgAgfReaderWriter(); $fact = new MgGeometryFactory(); echo "Created wkt/agf\n"; $count = 100; $i = 0; for ($i = 1; $i <= $count; $i++) { $bufferProps = new MgPropertyCollection(); $nameProp = new MgStringProperty("NAME", "NewName_" . $i); $bufferProps->Add($nameProp); $x = 120 + $i / $count; $y = 100 + $i / $count; //$wktText = "POLYGON ((20 20, 20 100, {$x} {$y}, 140 20, 20 20))"; //$geom = $wkt->Read($wktText); $coord = $fact->CreateCoordinateXY($x, $y); $geom = $fact->CreatePoint($coord); $geomReader = $agf->Write($geom); $geomProp = new MgGeometryProperty("GEOM", $geomReader);
private function CreatePolygonFromGeomText($geomText) { $geometryFactory = new MgGeometryFactory(); $vertices = explode(',', $geomText); $count = $vertices[0]; $coords = new MgCoordinateCollection(); for ($i = 0; $i < $count; $i++) { $coord = $geometryFactory->CreateCoordinateXY((double) $vertices[($i * 2) + 1], (double) $vertices[($i * 2) + 2]); $coords->Add($coord); } //Some provider such as SQL Server Spatial, ODBC requires the polygon's start point must be the same as end point. if(($count>2) && (($coords->GetItem(0)->GetX() != $coords->GetItem($count-1)->GetX()) || ($coords->GetItem(0)->GetY() != $coords->GetItem($count-1)->GetY()))) { $coord = $geometryFactory->CreateCoordinateXY($coords->GetItem(0)->GetX(), $coords->GetItem(0)->GetY()); $coords->Add($coord); } $linearRing = $geometryFactory->CreateLinearRing($coords); $polygon = $geometryFactory->CreatePolygon($linearRing, null); return $polygon; }
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; }
public function GeneratePlotFromMapDefinition($resId, $format) { $fmt = $this->ValidateRepresentation($format, array("dwf", "pdf")); $x = $this->GetRequestParameter("x", ""); $y = $this->GetRequestParameter("y", ""); $scale = $this->GetRequestParameter("scale", ""); if ($x == "") { $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "x"), MgMimeType::Html); } if ($y == "") { $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "y"), MgMimeType::Html); } if ($scale == "") { $this->BadRequest($this->app->localizer->getText("E_MISSING_REQUIRED_PARAMETER", "scale"), MgMimeType::Html); } $this->EnsureAuthenticationForSite(); $siteConn = new MgSiteConnection(); $siteConn->Open($this->userInfo); $map = new MgMap($siteConn); $map->Create($resId, "Plot"); $title = $this->GetRequestParameter("title", ""); $paperSize = $this->GetRequestParameter("papersize", 'A4'); $orientation = $this->GetRequestParameter("orientation", 'P'); $marginLeft = floatval($this->GetRequestParameter("marginleft", 0.5)); $marginRight = floatval($this->GetRequestParameter("marginright", 0.5)); $marginTop = floatval($this->GetRequestParameter("margintop", $title == "" ? 0.5 : 1.0)); $marginBottom = floatval($this->GetRequestParameter("marginbottom", 0.5)); $geomFact = new MgGeometryFactory(); $center = $geomFact->CreateCoordinateXY(floatval($x), floatval($y)); if ($fmt == "dwf") { $size = MgUtils::GetPaperSize($this->app, $paperSize); //If landscape, flip the width/height $width = $orientation == 'L' ? MgUtils::MMToIn($size[1]) : MgUtils::MMToIn($size[0]); $height = $orientation == 'L' ? MgUtils::MMToIn($size[0]) : MgUtils::MMToIn($size[1]); $printLayoutStr = $this->GetRequestParameter("printlayout", null); $mappingSvc = $siteConn->CreateService(MgServiceType::MappingService); $dwfVersion = new MgDwfVersion("6.01", "1.2"); $plotSpec = new MgPlotSpecification($width, $height, MgPageUnitsType::Inches); $plotSpec->SetMargins($marginLeft, $marginTop, $marginRight, $marginBottom); $layout = null; if ($printLayoutStr != null) { $layoutRes = new MgResourceIdentifier($printLayoutStr); $layout = new MgLayout($layoutRes, $title, MgPageUnitsType::Inches); } $br = $mappingSvc->GeneratePlot($map, $center, floatval($scale), $plotSpec, $layout, $dwfVersion); //Apply download headers $downloadFlag = $this->app->request->params("download"); if ($downloadFlag && ($downloadFlag === "1" || $downloadFlag === "true")) { $name = $this->app->request->params("downloadname"); if (!$name) { $name = "download"; } $name .= ".dwf"; $this->app->response->header("Content-Disposition", "attachment; filename=" . $name); } $this->OutputByteReader($br); } else { //pdf //FIXME: Initial visibility state is inconsistent (probably because this map hasn't been rendered //yet). As a result, adding layered PDF support won't really work here. /* $bLayered = $this->app->request->params("layeredpdf"); if ($bLayered == null) $bLayered = false; else $bLayered = ($bLayered == "1" || $bLayered == "true"); */ $renderingService = $siteConn->CreateService(MgServiceType::RenderingService); $plotter = new MgPdfPlotter($this->app, $renderingService, $map); $plotter->SetTitle($title); $plotter->SetPaperType($paperSize); $plotter->SetOrientation($orientation); $plotter->ShowCoordinates(true); $plotter->ShowNorthArrow(true); $plotter->ShowScaleBar(true); $plotter->ShowDisclaimer(true); //$plotter->SetLayered($bLayered); $plotter->SetMargins($marginTop, $marginBottom, $marginLeft, $marginRight); //Apply download headers $downloadFlag = $this->app->request->params("download"); if ($downloadFlag && ($downloadFlag === "1" || $downloadFlag === "true")) { $name = $this->app->request->params("downloadname"); if (!$name) { $name = "download"; } $name .= ".pdf"; $plotter->Plot($center, floatval($scale), $name); } else { $plotter->Plot($center, floatval($scale)); } } }
function AddPolygon() { $geometryFactory = new MgGeometryFactory(); $agfWriter = new MgAgfReaderWriter(); $vertices = explode(',', $this->args['GEOMETRY']); $count = $vertices[0]; $coords = new MgCoordinateCollection(); for ($i = 0; $i < $count; $i++) { $coord = $geometryFactory->CreateCoordinateXY((double) $vertices[$i * 2 + 1], (double) $vertices[$i * 2 + 2]); $coords->Add($coord); } // Add the first vertex to make the ring close if ($count > 2) { $coord = $geometryFactory->CreateCoordinateXY((double) $vertices[1], (double) $vertices[2]); $coords->Add($coord); } $linearRing = $geometryFactory->CreateLinearRing($coords); $polygon = $geometryFactory->CreatePolygon($linearRing, null); $trans = $this->GetTransform(); if (null != $trans) { $polygon = $polygon->Transform($trans); } $byteReader = $agfWriter->Write($polygon); $propertyValues = new MgPropertyCollection(); $propertyValues->Add(new MgStringProperty('Text', $this->args['TEXT'])); $propertyValues->Add(new MgGeometryProperty('Geometry', $byteReader)); $this->InsertMarkupFeature($propertyValues); }
function MultiGeometryFromSelection($featureSrvc, $map, $selText) { $sel = new MgSelection($map, $selText); $selLayers = $sel->GetLayers(); $geomColl = new MgGeometryCollection(); $agfRW = new MgAgfReaderWriter(); $simplyPolygonOnly = true; for ($i = 0; $i < $selLayers->GetCount(); $i++) { $layer = $selLayers->GetItem($i); $filter = $sel->GenerateFilter($layer, $layer->GetFeatureClassName()); $query = new MgFeatureQueryOptions(); $query->SetFilter($filter); $featureSource = new MgResourceIdentifier($layer->GetFeatureSourceId()); $features = $featureSrvc->SelectFeatures($featureSource, $layer->GetFeatureClassName(), $query); if ($features) { $classDef = $features->GetClassDefinition(); $geomPropName = $classDef->GetDefaultGeometryPropertyName(); $j = 0; while ($features->ReadNext()) { $geomReader = $features->GetGeometry($geomPropName); $geom = $agfRW->Read($geomReader); $type = $geom->GetGeometryType(); if ($type == MgGeometryType::MultiPolygon || $type == MgGeometryType::CurvePolygon || $type == MgGeometryType::MultiCurvePolygon) { $simplyPolygonOnly = false; } else { if ($type != MgGeometryType::Polygon) { continue; } } $geomColl->Add($geom); } } } if ($geomColl->GetCount() == 0) { return null; } $gf = new MgGeometryFactory(); if ($simplyPolygonOnly) { $polyColl = new MgPolygonCollection(); for ($i = 0; $i < $geomColl->GetCount(); $i++) { $polyColl->Add($geomColl->GetItem($i)); } return $gf->CreateMultiPolygon($polyColl); } else { return $gf->CreateMultiGeometry($geomColl); } }
$bufferLayer->SetDisplayInLegend(true); $map->Save($resourceService); */ // New way, post MapGuide 2.0 // Get the selected features from the MgSelection object $featureReader = $selection->GetSelectedFeatures($layer, $layer->GetFeatureClassName(), false); // Process each item in the MgFeatureReader. Get the // geometries from all the selected features and // merge them into a single geometry. $inputGeometries = new MgGeometryCollection(); while ($featureReader->ReadNext()) { $featureGeometryData = $featureReader->GetGeometry('SHPGEOM'); $featureGeometry = $agfReaderWriter->Read($featureGeometryData); $inputGeometries->Add($featureGeometry); } $geometryFactory = new MgGeometryFactory(); $mergedGeometries = $geometryFactory->CreateMultiGeometry($inputGeometries); // Add buffer features to the temporary feature source. // Create multiple concentric buffers to show area. // If the stylization for the layer draws the features // partially transparent, the concentric rings will be // progressively darker towards the center. // The stylization is set in the layer template file, which // is used in function CreateBufferLayer(). $commands = new MgFeatureCommandCollection(); for ($bufferRing = 0; $bufferRing < $bufferRingCount; $bufferRing++) { $bufferDist = $srs->ConvertMetersToCoordinateSystemUnits($bufferRingSize * ($bufferRing + 1)); $bufferGeometry = $mergedGeometries->Buffer($bufferDist, $srsMeasure); $properties = new MgPropertyCollection(); $properties->Add(new MgGeometryProperty('BufferGeometry', $agfReaderWriter->Write($bufferGeometry))); $commands->Add(new MgInsertFeatures('BufferClass', $properties));
if ($addressLayer == null) { CreateAddressMarkerFeatureSource($featureService, $addressMarkerDataResId); $addressLayer = CreateAddressMarkerLayer($resourceService, $addressMarkerDataResId, $mgSessionId); $map->GetLayers()->Insert(0, $addressLayer); } else { if ($addressLayer->GetVisible()) { // If the layer exists and is visible, then display the // previous results. EmitAddressResults($featureService, $addressMarkerDataResId, $mgSessionId); } } // Insert the results of the Geo-Code into the temporary // feature source and ensure the address marker layer // is visible. $geometryReaderWriter = new MgAgfReaderWriter(); $geometryFactory = new MgGeometryFactory(); $addrPoint = $geometryFactory->CreatePoint($geometryFactory->CreateCoordinateXY((double) $long, (double) $lat)); $properties = new MgPropertyCollection(); $properties->Add(new MgStringProperty('Address', $address1)); $properties->Add(new MgGeometryProperty('Location', $geometryReaderWriter->Write($addrPoint))); $commands = new MgFeatureCommandCollection(); $commands->Add(new MgInsertFeatures('AddressMarker', $properties)); $featureService->UpdateFeatures($addressMarkerDataResId, $commands, false); $addressLayer->SetVisible(true); $addressLayer->ForceRefresh(); $map->Save($resourceService); $success = true; } else { echo '<tr><td>Address not found: ' . $address . '<hr></td></tr>'; $success = false; }
} $inputGeometries->Add($geom); } } while ($features->ReadNext()); $features->Close(); } } if ($merge) { if ($inputGeometries->GetCount() > 0) { $dist = $srsMap->ConvertMetersToCoordinateSystemUnits($distance); if (!$arbitraryMapSrs) { $measure = $srsMap->GetMeasure(); } else { $measure = null; } $geomFactory = new MgGeometryFactory(); $geomBuffer = $geomFactory->CreateMultiGeometry($inputGeometries)->Buffer($dist, $measure); if ($geomBuffer != null) { AddFeatureToCollection($propCollection, $agfRW, $featId, $geomBuffer); $bufferFeatures = 1; } } } if ($propCollection->GetCount() > 0) { $commands->Add(new MgInsertFeatures($featureName, $propCollection)); //Insert the features in the temporary data source // $res = $featureSrvc->UpdateFeatures($dataSourceId, $commands, false); } // Save the new map state //
$featureReader->Close(); } if ($merge) { if ($inputGeometries->GetCount() > 0) { $dist = $srsMap->ConvertMetersToCoordinateSystemUnits($distance); if (!$arbitraryMapSrs) { $verMajor = subStr(GetSiteVersion(), 0, 1); if ($verMajor == '1') { $measure = new MgCoordinateSystemMeasure($srsMap); } else { $measure = $srsMap->GetMeasure(); } } else { $measure = null; } $geomFactory = new MgGeometryFactory(); $oGeom = $geomFactory->CreateMultiGeometry($inputGeometries); $oNewGeom = $oGeom->Buffer($dist, $measure); $geomProp = new MgGeometryProperty("GEOM", $agfRW->Write($oNewGeom)); $oPropertyColl = new MgPropertyCollection(); $oPropertyColl->Add($geomProp); $oCommandsColl->Add(new MgInsertFeatures($schemaName . ':' . $layerName, $oPropertyColl)); } } $result = $featureService->UpdateFeatures($featureSourceId, $oCommandsColl, false); $layer->ForceRefresh(); $map->Save($resourceService); echo "<Buffer>"; echo "<Layer>" . $layerId->ToString(); echo "</Layer>"; echo "</Buffer>";
function GetProfilingResults() { //profiling map parameters global $mapResourceId; global $mapProfileResult; global $scale; global $centerPoint; global $clientWidth; global $clientHeigth; list($x, $y) = explode("*", $centerPoint); $x = trim($x); $y = trim($y); $geometryFactory = new MgGeometryFactory(); //[centerPoint] $coordNewCenter = $geometryFactory->CreateCoordinateXY($x, $y); //[backgroundColor] $bgc = GetBackGroundColor($mapResourceId); //[imageFormat] $imageFormat = "PNG"; //userInfo are saved in the session global $userInfo; //connect to the site and get a resource service instance //create profiling service too $siteConn = new MgSiteConnection(); $siteConn->Open($userInfo); $resourceService = $siteConn->CreateService(MgServiceType::ResourceService); $profilingService = $siteConn->CreateService(MgServiceType::ProfilingService); //the profiling result is saved as xml file, the file name is unique //the format is like this "YYYYMMDDHHMMSS10" $newXmlFileId = date("YmdHis") . rand(10, 99); $resourceID = new MgResourceIdentifier($mapResourceId); // Get a runtime map from a map definition $map = new MgMap(); $map->Create($resourceService, $resourceID, $newXmlFileId); //The result will not show base layers RemoveBaseLayers($map); //get the profiling map result $byteReader = $profilingService->ProfileRenderMap($map, NULL, $coordNewCenter, $scale, $clientWidth, $clientHeigth, $bgc, $imageFormat, false); //read the content into a string $profilingResourceContent = ""; $chunk = ""; do { $chunkSize = $byteReader->Read($chunk, 4096); $profilingResourceContent = $profilingResourceContent . $chunk; } while ($chunkSize != 0); //save the file on the server $newXmlFileName = "profilingmapxml/" . $newXmlFileId . ".xml"; $fp = fopen($newXmlFileName, "w"); fwrite($fp, $profilingResourceContent); fclose($fp); //put the file name in the session $_SESSION["ProfilingResultFile"] = $newXmlFileName; //read the result into the DOM $resultSource = new DOMDocument(); $resultSource->load($newXmlFileName); $mapProfileResult->ReadFromXML($resultSource); $mapProfileResult->GetBaseLayerCount(); }
// 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; $envelopeOffsetX = $imageWidth / $imageHeight * $envelopeOffsetY; $envelope = new MgEnvelope($mapCenterX - $envelopeOffsetX, $mapCenterY - $envelopeOffsetY, $mapCenterX + $envelopeOffsetX, $mapCenterY + $envelopeOffsetY); // Render the image and send it to the browser. $byteReader = $renderingService->RenderMap($map, $selection, $envelope, $imageWidth, $imageHeight, $color, 'PNG'); header("Content-type: " . $byteReader->GetMimeType()); $buffer = ''; while ($byteReader->Read($buffer, 50000) != 0) {
if ($units == "km") { $distance *= 0.001; } //get kilometers if ($units == "ft") { $distance *= 3.2808399; } //get feet if ($units == "usft") { $distance *= 3.2808333; } //get US survey feet $total += $distance; //create the line string geometry representing this segment // $geomFactory = new MgGeometryFactory(); $coordinates = new MgCoordinateCollection(); $coordinates->Add($geomFactory->CreateCoordinateXY($x1, $y1)); $coordinates->Add($geomFactory->CreateCoordinateXY($x2, $y2)); $geom = $geomFactory->CreateLineString($coordinates); if ($segId == 1) { //first segment // if (!DataSourceExists($resourceSrvc, $dataSourceId)) { //create feature source // $classDef = new MgClassDefinition(); $classDef->SetName($featureName); $classDef->SetDescription(GetLocalizedString("MEASUREFEATURECLASS", $locale)); $classDef->SetDefaultGeometryPropertyName("GEOM"); //Set KEY property