function gml2wkt($gml) { // Parse GML file include "funcoes_gerais.php"; $k = array_keys($_GET); session_name("i3GeoPHP"); session_id($_GET[$k[0]]); session_start(); //var_dump($_SESSION);exit; $nome = $_SESSION["dir_tmp"] . "/gml_" . nomeRandomico(); $nomegml = $nome . ".gml"; $nomemap = $_SESSION["map_file"]; $gml = str_replace("xsi:schemaLocation", "erro", $gml); gravaDados(array($gml), $nomegml); $map = new mapObj($nomemap); $layer = ms_newLayerObj($map); $layer->setConnectionType(MS_OGR); $layer->set("connection", $nomegml); $layer->set("template", "none.html"); $layer->set("type", MS_LAYER_POLYGON); $layer->set("name", $nome); $layer->set("status", MS_DEFAULT); $layer->setmetadata("tema", $nome); $classe = ms_newClassObj($layer); $novoestilo = ms_newStyleObj($classe); $ncor = $novoestilo->color; $ncor->setrgb(255, 255, 255); //$map->save($nomemap); //exit; $layer->queryByrect($map->extent); $sopen = $layer->open(); $shape = $layer->getShape($layer->getResult(0)); $wkt = $shape->towkt(); return json_encode(array($wkt)); }
function draw_header($map, $img, $width, $height) { /* * Draw the black bar at the top of the screen */ $layer = ms_newLayerObj($map); $layer->set("status", MS_ON); $layer->set("type", MS_LAYER_POLYGON); $layer->set("transform", MS_OFF); $wkt = "POLYGON((0 0, 0 {$height}, {$width} {$height}, {$width} 0, 0 0))"; $layer->addFeature(ms_shapeObjFromWkt($wkt)); $layerc0 = ms_newClassObj($layer); $layerc0s0 = ms_newStyleObj($layerc0); $layerc0s0->color->setRGB(0, 0, 0); $layer->draw($img); }
function mktitle($map, $imgObj, $titlet, $subtitle = "", $width = 640) { $height = $subtitle == "" ? 36 : 53; $layer = ms_newLayerObj($map); $layer->set("status", MS_ON); $layer->set("type", MS_LAYER_POLYGON); $layer->set("transform", MS_OFF); $wkt = "POLYGON((0 0, 0 {$height}, {$width} {$height}, {$width} 0, 0 0))"; $layer->addFeature(ms_shapeObjFromWkt($wkt)); $layerc0 = ms_newClassObj($layer); $layerc0s0 = ms_newStyleObj($layerc0); $layerc0s0->color->setRGB(0, 0, 0); $layer->draw($imgObj); $tlayer = $map->getLayerByName("iem_headerbar_title"); $point = ms_newpointobj(); $point->setXY(82, 22); $point->draw($map, $tlayer, $imgObj, 0, $titlet); if ($subtitle != "") { $point = ms_newpointobj(); $point->setXY(82, 39); $point->draw($map, $tlayer, $imgObj, 1, $subtitle); } }
if ($tipo == "pontos") { $novolayer->set("type", MS_LAYER_POINT); } if ($tipo == "linhas") { $novolayer->set("type", MS_LAYER_LINE); } if ($tipo == "poligonos") { $novolayer->set("type", MS_LAYER_POLYGON); } $novolayer->set("type", $tipo); $novolayer->set("data", $_GET["layerkml"]); $novolayer->setmetadata("TEMALOCAL", "SIM"); $novolayer->setfilter(""); $classe = ms_newClassObj($novolayer); $classe->set("name", ""); $estilo = ms_newStyleObj($classe); if ($tipo == "pontos") { $estilo->set("symbolname", "ponto"); $estilo->set("size", 6); } $estilo->color->setrgb(200, 50, 0); $estilo->outlinecolor->setrgb(0, 0, 0); // le os itens $novolayer->set("status", MS_DEFAULT); $novolayer->set("template", "none.htm"); if (isset($_GET["uploadkmlEPSG"]) && $_GET["uploadkmlEPSG"] != "") { $novolayer->setProjection("init=epsg:" . $_GET["uploadkmlEPSG"]); } //$adiciona = ms_newLayerObj($mapa, $novolayer); } $salvo = $mapa->save($map_file);
$e_style = ms_newStyleObj($e_class); $e_style->color->setRGB(255, 255, 20); $e_style->set("size", 3); $e_style->set("symbolname", 'circle'); $e_shapestart = ms_newShapeObj(MS_SHAPE_POINT); $e_line = ms_newLineObj(); list($px, $py) = split(' ', $_SESSION['track'][0]); $e_line->addXY($px, $py); $e_shapestart->add($e_line); $e_track3 = ms_newLayerObj($e_map); $e_track3->set('name', 'temptrackstart'); $e_track3->set('status', MS_ON); $e_track3->set('type', MS_LAYER_POINT); $e_track3->addFeature($e_shapestart); $e_class3 = ms_newClassObj($e_track3); $e_style3 = ms_newStyleObj($e_class3); $e_style3->set("symbolname", 'flag2'); } $e_image = $e_map->draw(); $image = $e_image->saveWebImage(); $e_ref = $e_map->drawreferencemap(); $refsrc = $e_ref->saveWebImage('MS_PNG', 0, 0, -1); // affichage l?gende if ($e_map->scale < $minscaledispscan100legend) { $smarty->assign('booldisplegscan100', true); } // outil zoom + s?l?ectionn? par d?faut au dela d'une certaine ?chelle if ($e_map->scale > $minscaledispzoomp) { $focus['zoomin'] = "focus"; } // reconstitue la l?gende avec les pictos
function criaCluster($group = "", $filter = "", $maxdistance = 5, $region = 'rectangle', $buffer = 0) { if ($group != "") { $group = "('[" . $group . "]')"; } $cluster = $this->layer->cluster; $par = "BUFFER {$buffer} REGION {$region} MAXDISTANCE {$maxdistance}"; if ($group != "") { $par .= " GROUP " . $group; } if ($filter != "") { $par .= " FILTER " . $filter; } $cluster->updateFromString("CLUSTER {$par} END"); $this->layer->setMetaData("cache", ""); $this->layer->setMetadata("tiles", "NAO"); $this->layer->setMetadata("cortepixels", 0); //apaga as classes pois nao fazem mais sentido if ($group == "") { $numclasses = $this->layer->numclasses; if ($numclasses > 0) { for ($i = 0; $i < $numclasses; ++$i) { $classe = $this->layer->getClass($i); $classe->set("status", MS_DELETE); } } $classe = ms_newClassObj($this->layer); $novoestilo = ms_newStyleObj($classe); $novoestilo->set("size", 6); $novoestilo->set("symbolname", "ponto"); $cor = $novoestilo->color; $cor->setRGB(255, 100, 100); } }
$wcc0s0->color->setRGB(255, 255, 255); $wcc0s0->set("width", 2); $wcc0s0->set("symbol", 'circle'); $wc->draw($img); $map->drawLabelCache($img); $wc = ms_newLayerObj($map); $wc->setConnectionType(MS_POSTGIS); $wc->set("connection", $_DATABASES["postgis"]); $wc->set("status", MS_ON); $sql = sprintf("geom from (select oid, geom from sbw_{$year} WHERE oid = " . $row["oid"] . ") as foo using unique oid using SRID=4326"); $wc->set("data", $sql); $wc->set("type", MS_LAYER_LINE); $wc->setProjection("init=epsg:4326"); $wcc0 = ms_newClassObj($wc); $wcc0->set("name", $row["area"] . " sq km [" . intval($row["area"] / $sz0 * 100) . "%]"); $wcc0s0 = ms_newStyleObj($wcc0); $wcc0s0->color->setRGB(255, 0, 0); $wcc0s0->set("width", 3); $wcc0s0->set("symbol", 'circle'); $wc->draw($img); $map->drawLabelCache($img); $bar640t = $map->getLayerByName("bar640t"); $bar640t->set("status", 1); $bar640t->draw($img); $tlayer = $map->getLayerByName("bar640t-title"); $point = ms_newpointobj(); $point->setXY(2, 8); $point->draw($map, $tlayer, $img, 0, $vtec_status[$row["status"]]); $point = ms_newpointobj(); $point->setXY(2, 25); $d = strftime("%d %b %Y %-2I:%M %p %Z", $ts);
function createClass($layer, $name, $expr, $r, $g, $b, $symbol, $size) { $__layer = $this->map->getlayerbyname($layer); $__class = ms_newClassObj($__layer); $__class->set("name", $name); $__class->setExpression($expr); $__style = ms_newStyleObj($__class); $__style->color->setRGB($r, $g, $b); $__style->set("symbol", $symbol); $__style->set("size", $size); }
function criarNovoEstilo() { global $codigoMap, $codigoLayer, $locaplic; $mapfile = $locaplic . "/temas/" . $codigoMap . ".map"; $mapa = ms_newMapObj($mapfile); $nl = $mapa->getlayerbyname($codigoLayer); $classObj = $nl->getclass($_GET["indiceClasse"]); $numestilos = $classObj->numstyles; $nestilo = ms_newStyleObj($classObj); $mapa->save($mapfile); removeCabecalho($mapfile); $dados[] = array("estilo" => $numestilos); return $dados; }
/** * FOR ZOOM TO SELECTED. * Adds a new layer to the map for highlighting feature */ private function pmap_addResultLayer($reslayer, $shpindexes) { if (isset($_SESSION["resulttilelayers"])) { $resulttilelayers = $_SESSION["resulttilelayers"]; $resulttilelayer = $resulttilelayers[$reslayer]; } else { $resulttilelayers = null; $resulttilelayer = null; } $qLayer = $this->map->getLayerByName($reslayer); $qlayType = $qLayer->type; $layNum = count($this->map->getAllLayerNames()); // Test if layer has the same projection as map $mapProjStr = $this->map->getProjection(); $qLayerProjStr = $qLayer->getProjection(); $changeLayProj = false; if ($mapProjStr && $qLayerProjStr && $mapProjStr != $qLayerProjStr) { $changeLayProj = true; if ($_SESSION['MS_VERSION'] < 6) { $mapProjObj = ms_newprojectionobj($mapProjStr); $qLayerProjObj = ms_newprojectionobj($qLayerProjStr); } else { $mapProjObj = new projectionObj($mapProjStr); $qLayerProjObj = new projectionObj($qLayerProjStr); } } // New result layer if ($_SESSION['PM_TPL_MAP_FILE']) { // load from template map file $hlDynLayer = 0; $hlMap = ms_newMapObj($_SESSION['PM_TPL_MAP_FILE']); $hlMapLayer = $hlMap->getLayerByName("highlight_{$qlayType}"); $hlMapLayer->set("name", "pmapper_reslayer"); $newResLayer = ms_newLayerObj($this->map, $hlMapLayer); } else { // create dynamically $hlDynLayer = 1; $newResLayer = ms_newLayerObj($this->map); $newResLayer->set("name", "pmapper_reslayer"); if ($qlayType == 0) { $newResLayer->set("type", 0); // Point for point layer } elseif ($qlayType == 1 || $qlayType == 2) { $newResLayer->set("type", 1); // Line for line && polygon layers } //##$newResLayer->set("type", $qlayType); // Take always same layer type as layer itself } // Add selected shape to new layer //# when layer is an event theme if ($qLayer->getMetaData("XYLAYER_PROPERTIES") != "") { foreach ($shpindexes as $cStr) { $cList = preg_split('/@/', $cStr); $xcoord = $cList[0]; $ycoord = $cList[1]; $resLine = ms_newLineObj(); // needed to use a line because only a line can be added to a shapeObj $resLine->addXY($xcoord, $ycoord); $resShape = ms_newShapeObj(1); $resShape->add($resLine); $newResLayer->addFeature($resShape); } //# specific for PG layers <==== required for MS >= 5.6 !!! } elseif ($qLayer->connectiontype == 6) { $newResLayer->set("connection", $qLayer->connection); if (method_exists($newResLayer, "setConnectionType")) { $newResLayer->setConnectionType($qLayer->connectiontype); } else { $newResLayer->set("connectiontype", $qLayer->connectiontype); } $data = $qLayer->data; // use layers with complex queries that are too long to select results // cause maxscaledenom is not used... if ($qLayer->getMetaData("PM_RESULT_DATASUBSTITION") != "") { $data = $qLayer->getMetaData("PM_RESULT_DATASUBSTITION"); } $newResLayer->set("data", $data); if ($qLayerProjStr) { $newResLayer->setProjection($qLayerProjStr); } $glList = PMCommon::returnGroupGlayer($reslayer); $glayer = $glList[1]; $layerDbProperties = $glayer->getLayerDbProperties(); $uniqueField = $layerDbProperties['unique_field']; $indexesStr = implode(",", $shpindexes); $idFilter = "({$uniqueField} IN ({$indexesStr}))"; $newResLayer->setFilter($idFilter); //# 'normal' layers } else { // Add selected shape to new layer // Modified by Thomas RAFFIN (SIRAP) // use layers with complex queries that are too long to select results // cause maxscaledenom is not used... $olddata = false; if ($qLayer->getMetaData("PM_RESULT_DATASUBSTITION") != "") { $olddata = $qLayer->data; $qLayer->set("data", $qLayer->getMetaData("PM_RESULT_DATASUBSTITION")); } $qLayer->open(); foreach ($shpindexes as $resShpIdx) { if (preg_match("/@/", $resShpIdx)) { $idxList = explode("@", $resShpIdx); $resTileShpIdx = $idxList[0]; $resShpIdx = $idxList[1]; } else { $resTileShpIdx = $resulttilelayer[$resShpIdx]; } $resShape = PMCommon::resultGetShape($this->msVersion, $qLayer, null, $resShpIdx, $resTileShpIdx); // changed for compatibility with PG layers and MS >= 5.6 // Change projection to map projection if necessary if ($changeLayProj) { // If error appears here for Postgis layers, then DATA is not defined properly as: // "the_geom from (select the_geom, oid, xyz from layer) AS new USING UNIQUE oid USING SRID=4258" if ($resShape) { $resShape->project($qLayerProjObj, $mapProjObj); } } if ($resShape) { $newResLayer->addFeature($resShape); } } $qLayer->close(); // Modified by Thomas RAFFIN (SIRAP) // use layers with complex queries that are too long to select results // cause maxscaledenom is not used... // reset data tag if ($olddata) { $qLayer->set("data", $olddata); } } $newResLayer->set("status", MS_ON); $newResLayerIdx = $newResLayer->index; if ($hlDynLayer) { // SELECTION COLOR $iniClrStr = trim($_SESSION["highlightColor"]); $iniClrList = preg_split('/[\\s,]+/', $iniClrStr); $iniClr0 = $iniClrList[0]; $iniClr1 = $iniClrList[1]; $iniClr2 = $iniClrList[2]; // CREATE NEW CLASS $resClass = ms_newClassObj($newResLayer); $clStyle = ms_newStyleObj($resClass); $clStyle->color->setRGB($iniClr0, $iniClr1, $iniClr2); $clStyle->set("symbolname", "circle"); $symSize = $qlayType < 1 ? 10 : 5; $clStyle->set("size", $symSize); } // Move layer to top (is it working???) while ($newResLayerIdx < $layNum - 1) { $this->map->moveLayerUp($newResLayerIdx); } }
public function generate($idp, $nama_kolom, $nama_menurut, $nama_di, $tipe_data, $nama_kabupaten, $pilihwarna, $kelasLegend, $idpulau, $modelegendcanggih, $datalegendcanggih) { $connection = Yii::$app->db; //$idp ="data_timese_prov"; // $nama_kolom="2011"; //$nama_menurut="Provinsi"; //$nama_di="Indonesia"; //$tipe_data="3"; $namaprovkabkec = "nama_prov"; $datam[][] = array(); $i = 0; $jumlahdata = 0; $layer = 'id_prov'; $layerdatabase = 's00prov'; $query = ''; $where = ""; if ($nama_menurut == "Kabupaten") { $namaprovkabkec = "nama_kab"; $layer = 'id_kab'; $layerdatabase = 's00kab'; $where = "WHERE {$nama_di} = {$idp}.id_prov"; } if ($nama_menurut == "Kecamatan") { $namaprovkabkec = "nama_kec"; $layer = 'id_kec'; $layerdatabase = 's33kec'; if ($nama_kabupaten == "seluruhKabupaten") { $where = "WHERE {$nama_di} = {$idp}.id_prov"; } else { $where = "WHERE {$nama_kabupaten} = {$idp}.id_kab"; } } $wherepulau = ''; if ($idpulau != 0) { $wherepulau = "WHERE {$idp}.{$layer}::varchar LIKE '" . $idpulau . "%'"; } $kelas = $kelasLegend; $json_provinsi = array("status" => "OK", "jumlah" => $kelas, "jumlah2" => 0, "results" => array(), "results2" => array()); if ($tipe_data == "1" | $tipe_data == "3") { if ($nama_di == "Indonesia" | $idpulau != 0) { $query = "SELECT {$idp}.{$layer}, {$namaprovkabkec}, SUM(" . $nama_kolom . ") FROM " . $idp . " INNER JOIN {$layerdatabase}\nON {$idp}.{$layer}::varchar={$layerdatabase}.{$layer}::varchar " . $wherepulau . "GROUP BY {$idp}.{$layer} ,{$namaprovkabkec} ORDER BY {$idp}.{$layer} "; //$query = "SELECT s00kab.id_prov, s00kab.nama_prov FROM s00kab INNER JOIN $namaTabel //ON $namaTabel.id_kab::varchar=s00kab.id_kab::varchar GROUP BY s00kab.id_prov,s00kab.nama_prov ORDER BY s00kab.nama_prov DESC;"; } else { $query = "SELECT {$idp}.{$layer}, SUM(" . $nama_kolom . "), {$namaprovkabkec} FROM " . $idp . " INNER JOIN {$layerdatabase} ON {$idp}.{$layer}::varchar={$layerdatabase}.{$layer}::varchar " . $where . " GROUP BY {$idp}.{$layer}, " . $namaprovkabkec; } $command = $connection->createCommand($query); $dataReader = $command->query(); $rows = $dataReader->readAll(); $json_provinsi["jumlah2"] = $dataReader->rowCount; foreach ($rows as $myrow) { //echo"hjj"; $json_provinsi["results2"][] = array("nama" => $myrow[$namaprovkabkec], "jumlah" => $myrow["sum"]); $datam[$i][$layer] = $myrow[$layer]; $datam[$i][$nama_kolom] = $myrow["sum"]; $i++; } if ($modelegendcanggih == "tidak") { $nilaimaks = 0; for ($x = 0; $x < $i; $x++) { if ($nilaimaks < $datam[$x][$nama_kolom]) { $nilaimaks = $datam[$x][$nama_kolom]; } } $batasbawah = $nilaimaks / $kelas; $warnalgnd = array(); $warnalgnd = self::_warnaLegenda($pilihwarna); for ($x = 0; $x < $i; $x++) { for ($k = 0; $k < $kelas; $k++) { if ($batasbawah * (1 + $k) >= $datam[$x][$nama_kolom]) { $datam[$x]['R'] = $warnalgnd[$k]["R"]; $datam[$x]['G'] = $warnalgnd[$k]["G"]; $datam[$x]['B'] = $warnalgnd[$k]["B"]; break; //echo"atas Sendiri".$datam[$x][$layer]."".$datam[$x][$nama_kolom]. "knp <br/>"; } } } for ($k = $kelas; $k > 0; $k--) { $json_provinsi["results"][] = array("batas_bawah" => $batasbawah * (x + ($k - 1)) . " - " . $batasbawah * (x + $k), "R" => $warnalgnd[$k - 1]["R"], "G" => $warnalgnd[$k - 1]["G"], "B" => $warnalgnd[$k - 1]["B"]); } } else { if ($modelegendcanggih == "ya") { $datalegendcanggiharray = []; $firstDimension = explode('|', $datalegendcanggih); // Divide by | symbol foreach ($firstDimension as $temp) { // Take each result of division and explode it by , symbol and save to result $datalegendcanggiharray[] = explode(',', $temp); } $warnalgnd = array(); $warnalgnd = self::_warnaLegenda($pilihwarna); for ($x = 0; $x < $i; $x++) { for ($k = 0; $k < $kelas; $k++) { if ($datalegendcanggiharray[$k][0] <= $datam[$x][$nama_kolom] & $datalegendcanggiharray[$k][1] >= $datam[$x][$nama_kolom]) { $datam[$x]['R'] = $warnalgnd[$k]["R"]; $datam[$x]['G'] = $warnalgnd[$k]["G"]; $datam[$x]['B'] = $warnalgnd[$k]["B"]; break; //echo"atas Sendiri".$datam[$x][$layer]."".$datam[$x][$nama_kolom]. "knp <br/>"; } else { if ($datalegendcanggiharray[$kelas - 1][2] != "kosong") { $datam[$x]['R'] = $warnalgnd[$kelas - 1]["R"]; $datam[$x]['G'] = $warnalgnd[$kelas - 1]["G"]; $datam[$x]['B'] = $warnalgnd[$kelas - 1]["B"]; } } } } for ($k = 0; $k < $kelas - 1; $k++) { $json_provinsi["results"][] = array("batas_bawah" => $datalegendcanggiharray[$k][2], "R" => $warnalgnd[$k]["R"], "G" => $warnalgnd[$k]["G"], "B" => $warnalgnd[$k]["B"]); } if ($datalegendcanggiharray[$kelas - 1][2] != "kosong") { $json_provinsi["results"][] = array("batas_bawah" => $datalegendcanggiharray[$kelas - 1][2], "R" => $warnalgnd[$kelas - 1]["R"], "G" => $warnalgnd[$kelas - 1]["G"], "B" => $warnalgnd[$kelas - 1]["B"]); } else { $json_provinsi["jumlah"] = $kelas - 1; } } } echo json_encode($json_provinsi, JSON_PRETTY_PRINT); } if ($tipe_data == "2") { $query = "SELECT {$nama_kolom} FROM " . $idp . " {$wherepulau} GROUP BY " . $nama_kolom; $command = $connection->createCommand($query); $dataReader = $command->query(); $rows = $dataReader->readAll(); $num_rows = $dataReader->rowCount; $json_provinsi = array("status" => "OK", "jumlah" => $num_rows, "jumlah2" => 0, "results" => array(), "results2" => array()); // $query = "SELECT $layer, $nama_kolom FROM ".$idp; // $command=$connection->createCommand($query); // $dataReader=$command->query(); // $rows=$dataReader->readAll(); $i = 0; foreach ($rows as $myrow) { //$datam[$i][$layer] =$myrow[$layer]; $json_provinsi["results"][] = array("batas_bawah" => $myrow[$nama_kolom], "R" => 255 - ($i + 1) * 70, "G" => 141 - ($i + 1) * 20, "B" => 100 - ($i + 1) * 25); $i++; } $sama = 0; $query = "SELECT {$namaprovkabkec},{$idp}.{$layer}, {$nama_kolom} FROM " . $idp . " INNER JOIN {$layerdatabase} ON {$idp}.{$layer}::varchar={$layerdatabase}.{$layer}::varchar {$wherepulau} GROUP BY {$nama_kolom} ,{$namaprovkabkec},{$idp}.{$layer} ORDER BY {$idp}.{$layer}"; $command = $connection->createCommand($query); $dataReader = $command->query(); $rows = $dataReader->readAll(); $json_provinsi["jumlah2"] = $dataReader->rowCount; $i = 0; $w = array(); foreach ($rows as $myrow) { //$datam[$i][$layer] =$myrow[$layer]; $w[$i] = $myrow[$nama_kolom]; $json_provinsi["results2"][] = array("nama" => $myrow[$namaprovkabkec], "jumlah" => $myrow[$nama_kolom]); for ($x = 0; $x < $num_rows; $x++) { if ($w[$i] == $json_provinsi["results"][$x]["batas_bawah"]) { $datam[$i][$layer] = $myrow[$layer]; $datam[$i]['R'] = $json_provinsi["results"][$x]["R"]; $datam[$i]['G'] = $json_provinsi["results"][$x]["G"]; $datam[$i]['B'] = $json_provinsi["results"][$x]["B"]; } } $i++; } echo json_encode($json_provinsi, JSON_PRETTY_PRINT); //$datam[$i]['R']=$json_provinsi["results"][$x]["R"]; // $datam[$i]['G']=$json_provinsi["results"][$x]["G"]; //$datam[$i]['B']=$json_provinsi["results"][$x]["B"]; } $objMap = ms_NewMapObj(""); $objMap->Set("name", "Kab"); $objMap->setSize(384, 204); $objMap->setExtent(92.59, -19.443566666, 142.88, 14.1298); $objMap->Set("units", MS_DD); // derajat $objMap->imagecolor->SetRGB(210, 233, 255); //$objMap->SetSymbolSet ("C:\ms4w\apps\latihan\simbol\simbol.sym"); $objMap->SetFontSet("C:/ms4w/apps/latihan/mapsederhana/font/font.dat"); //$objMap->outputformat->set("transparent",1); // $objMap->outputformat->set("imagemode", MS_GD_ALPHA); $objMap->setProjection("init=epsg:4326"); $projInObj = ms_newprojectionobj("init=epsg:4326"); // objek web di mapfile $objMap->web->set("imagepath", "C:/ms4w/Apache/htdocs/temp/"); $objMap->web->set("imageurl", "/temp/"); $objMap->web->set("template", "C:/ms4w/apps/latihan/html/tmplb.html"); $objMap->setMetaData("ows_title", "Peta wilayah Indonesia"); $objMap->setMetaData("ows_onlineresource", "http://localhost/wms?"); $objMap->setMetaData("wms_srs", "EPSG:4326 EPSG:3857"); $objMap->setMetaData("wms_abstract", "WMS"); $objMap->setMetaData("wms_enable_request", "*"); $objMap->setMetaData("wms_encoding", "utf-8"); $objMap->setMetaData("wfs_getfeature_formatlist", "json"); // // objek layer $objLayerJbr = ms_newLayerObj($objMap); $objLayerJbr->set("name", "provinsi"); $objLayerJbr->setConnectionType(MS_POSTGIS); $dbpgsql = Yii::$app->message->dbpgsql(); $objLayerJbr->set('connection', $dbpgsql); $objLayerJbr->set('data', "geom from (select geom ,gid," . $layer . "," . $namaprovkabkec . " from " . $layerdatabase . " ) as subquery using unique gid using srid=43266"); $objLayerJbr->set("classitem", $layer); $objLayerJbr->set("type", MS_LAYER_POLYGON); $objLayerJbr->set("status", MS_ON); $objLayerJbr->set("opacity", 85); // $objLayerJbr->set ("labelitem",$namaprovkabkec); // label layer //$objLayerJbr->set("labelcache",MS_ON);// field kelas //$objLayerJbr->setprocessing("LABEL_NO_CLIP=on"); // // objek class & style jabar for ($x = 0; $x < $i; $x++) { $objClassJbr[] = ms_newClassObj($objLayerJbr); // echo "<br/>".$datam[$x][$layer]." >>".$datam[$x]['R']." ".$datam[$x]['G']." ".$datam[$x]['B']; $objClassJbr[$x]->SetExpression($datam[$x][$layer]); $objClassJbr[$x]->Set("name", "batas_prov"); // kodeprop=1 $objStyleJbr[] = ms_newStyleObj($objClassJbr[$x]); //echo $datam[$x]['R']." ".$datam[$x]['G']." ".$datam[$x]['B']."<br/>"; $objStyleJbr[$x]->color->setRGB($datam[$x]['R'], $datam[$x]['G'], $datam[$x]['B']); //echo "warna : ".$datam[$x][$layer]." ".$datam[$x]['R']." ".$datam[$x]['G']." ".$datam[$x]['B']."<br/>"; $objStyleJbr[$x]->outlinecolor->SetRGB(0, 0, 0); $objClassJbr[$x]->label->Set("font", "arialbold"); $objClassJbr[$x]->label->Set("type", MS_TRUETYPE); $objClassJbr[$x]->label->Set("encoding", "utf-8"); $objClassJbr[$x]->label->Set("size", 8); $objClassJbr[$x]->label->Set("buffer", 7); $objClassJbr[$x]->label->Set("partials", TRUE); $objClassJbr[$x]->label->Set("align", center); $objClassJbr[$x]->label->Set("position", MS_CC); $objClassJbr[$x]->label->color->SetRGB(3, 3, 3); $objClassJbr[$x]->label->outlinecolor->SetRGB(242, 236, 230); // } $objLayerJbr->setProjection("init=epsg:4326"); // $clonefullpath = Yii::$app->message->clonefullpath(); $objMap->save($clonefullpath); // }
/** * Altera a representacao de um layer mostrando circulos cujo tamanho corresponde a um valor * @param nome do arquivo mapfile em uso * @param nome do layer que sera processado * @param variatamanho|variacor|continuo tipo de processo */ function classes2circulos($map_file, $tema, $tipo) { $nome = basename($map_file) . $tema . $tipo; $mapa = ms_newMapObj($map_file); $teste = $mapa->getlayerbyname($nome); if ($teste != "") { return ""; } $l = $mapa->getlayerbyname($tema); if ($l->getmetadata("METAESTAT_DERIVADO") == "sim") { return ""; } $layer = ms_newLayerObj($mapa, $l); $l->set("status", MS_OFF); $layer->set("status", MS_DEFAULT); $layer->set("opacity", 50); $layer->set("name", $nome); $meta = new Metaestat(); if ($layer->type != MS_LAYER_POINT) { $layer->set("type", 0); $regiao = $meta->listaTipoRegiao($layer->getmetadata("METAESTAT_CODIGO_TIPO_REGIAO")); //repare que existe uma virgula apos o nome da coluna com a geometria, isso e necessario para substituir a string correta if ($regiao["colunacentroide"] != "") { $stringgeo = "g." . $regiao["colunageo"] . ","; $data = str_replace($stringgeo, "g." . $regiao["colunacentroide"] . ",", $layer->data); } else { $stringgeo = 'st_setsrid(g.".' . $regiao["colunageo"] . '.",".' . $regiao["srid"] . '.")'; $data = str_replace($stringgeo, "st_centroid({$stringgeo})", $layer->data); } $layer->set("data", $data); } $numclasses = $layer->numclasses; if ($tipo == "variatamanho" || $tipo == "variacor") { if ($tipo == "variatamanho") { $layer->setmetadata("tema", $layer->getmetadata("tema") . " - circ"); } if ($tipo == "variacor") { $layer->setmetadata("tema", $layer->getmetadata("tema") . " - ponto"); } if ($numclasses > 0) { for ($i = 0; $i < $numclasses; ++$i) { $classe = $layer->getClass($i); $estilo = $classe->getstyle(0); $estilo->set("symbolname", "ponto"); if ($tipo == "variatamanho") { $estilo->set("size", $i * 6); } if ($tipo == "variacor") { $estilo->set("size", 12); } } } } if ($tipo == "continuo") { $nometemp = str_replace(basename($map_file), nomeRandomico(5) . basename($map_file), $map_file); $mapa->save($nometemp); //$mapatemp = ms_newMapObj($nometemp); $medidavariavel = $meta->listaMedidaVariavel("", $layer->getmetadata("METAESTAT_ID_MEDIDA_VARIAVEL")); include_once dirname(__FILE__) . "/../../classesphp/classe_alteraclasse.php"; $m = new Alteraclasse($nometemp, $layer->name, "", ""); $valores = $m->pegaValores($m->mapa, $m->layer, $medidavariavel["colunavalor"], true, 0); $min = min($valores); $max = max($valores); $layer->setmetadata("tema", $layer->getmetadata("tema") . " - cont"); $layer->set("type", MS_LAYER_CHART); $layer->set("opacity", 60); $layer->setprocessing("CHART_TYPE=pie"); $layer->setprocessing("CHART_SIZE_RANGE=" . $medidavariavel["colunavalor"] . " 10 150 " . $min . " " . $max); if ($numclasses > 0) { for ($i = 0; $i < $numclasses; ++$i) { $classe = $layer->getClass($i); $classe->set("status", MS_DELETE); } } $classe = ms_newClassObj($layer); $novoestilo = ms_newStyleObj($classe); //$novoestilo->set("symbolname","ponto"); $novoestilo->set("size", "6"); $ncor = $novoestilo->color; $ncor->setrgb(247, 145, 29); $ncor = $novoestilo->outlinecolor; $ncor->setrgb(255, 255, 255); //$novoestilo->setbinding(MS_STYLE_BINDING_SIZE, $medidavariavel["colunavalor"]); // $classe = ms_newClassObj($layer); $novoestilo = ms_newStyleObj($classe); //$novoestilo->set("symbolname","ponto"); $novoestilo->set("size", "6"); $ncor = $novoestilo->color; $ncor->setrgb(247, 145, 29); $ncor = $novoestilo->outlinecolor; $ncor->setrgb(255, 255, 255); } $layer->setmetadata("METAESTAT_DERIVADO", "sim"); $mapa->save($map_file); return $nome; }
$datal->set("status", MS_ON); $datal->set("type", MS_LAYER_POINT); $datal->setProjection("init=epsg:4326"); $datalc0 = ms_newClassObj($datal); $datalc0->addLabel(new labelObj()); $datalc0->getLabel(0)->color->setrgb(255, 255, 0); $datalc0->getLabel(0)->set("type", MS_TRUETYPE); $datalc0->getLabel(0)->set("font", "liberation"); $datalc0->getLabel(0)->set("size", 12); $datalc0->getLabel(0)->set("force", MS_TRUE); $datalc0->getLabel(0)->set("partials", MS_TRUE); //$datalc0->getLabel(0)->set("antialias", MS_TRUE); $datalc0->getLabel(0)->set("position", MS_UR); $datalc0->getLabel(0)->set("angle", 0); $datalc0->getLabel(0)->set("wrap", 0x57); $datalc0s0 = ms_newStyleObj($datalc0); $datalc0s0->color->setrgb(0, 0, 0); $datalc0s0->set("symbolname", "circle"); $datalc0s0->set("size", 3); $datalc1 = ms_newClassObj($datal, $datalc0); $datalc1->setExpression("([yrs] < 80)"); $datalc1s0 = $datalc1->getStyle(0); $datalc1s0->color->setrgb(255, 0, 0); $img = $map->prepareImage(); $tpos = array("all" => array(-95.40000000000001, 40.2), "ne" => array(-92.90000000000001, 43.7), "se" => array(-92.90000000000001, 40.3), "sw" => array(-96.40000000000001, 40.4), "nw" => array(-96.7, 43.65)); $ts = mktime(0, 0, 0, $month, $day, 2000); $plotDate = strftime('%b %d', $ts); $var = array("max_precip" => "Record Daily Precip [in]", "precip" => "Average Precipitation [in]", "low" => "Average Low Temp [F]", "max_low" => "Record Max Low Temp [F]", "max_high" => "Record Max High Temp [F]", "min_low" => "Record Min Low Temp [F]", "min_high" => "Record Min High Temp [F]", "high" => "Average High Temp [F]"); $dbdate = "2000-" . $month . "-" . $day; if (strcmp($area, 'all') != 0) { $dbarray = array("high" => "round(high::numeric, 0)::int", "low" => "round(low::numeric, 0)::int", "max_low" => "round(max_low::numeric, 0)::int ||'W'|| max_low_yr ", "max_high" => "round(max_high::numeric, 0)::int ||'W'|| max_high_yr ", "min_high" => "round(min_high::numeric, 0)::int ||'W'|| min_high_yr ", "min_low" => "round(min_low::numeric, 0)::int ||'W'|| min_low_yr ", "max_precip" => "to_char(max_precip, '99.99') ||'W'|| max_precip_yr ", "precip" => "round(precip::numeric, 2)");
function generateMapfile($layer_tablename,$hex_colors,$expressions,$classitem,$getfeatureinfocol) { global $FILEPATH; global $db_url; global $ret_file; $layer_type =''; $query = "select layer_type from \"Meta_Layer\" where layer_tablename='".$layer_tablename."'"; $result = db_query($query); if($obj = db_fetch_object($result)){ switch($obj->layer_type){ case 'POLYGON': case 'MULTIPOLYGON': $layer_type = 'polygon'; break; case 'LINESTRING': case 'MULTILINESTRING': $layer_type = 'line'; break; case 'POINT': case 'MULTIPOINT': $layer_type = 'point'; break; } } $mapfilename = session_id().$layer_tablename; $dbpasswd = substr($db_url,$index2,$index2-$index1); $dbuser = preg_replace('/pgsql:\/\/(.*)@[^@]*/','$1',$db_url); $dbname = substr(strrchr($db_url,'/'),1); if(strpos($dbuser,':') >= 0) { list($dbuser,$dbpasswd) = split(":",$dbuser); } else { $dbpasswd = ""; } $name = $FILEPATH.$mapfilename.".map"; /* create a file */ $fh = fopen($name,"w"); fwrite($fh,"map\n"); fwrite($fh,"end"); fclose($fh); /* create new map object and set the parameters */ $map = ms_newMapObj($name); $map->setExtent(60,0,100,40); $map->setSize(725,800); $map->set("units",MS_DD); $map->setProjection("init=epsg:4326"); $map->set("maxsize",4096); $map->selectOutputFormat('PNG'); $map->outputformat->set("transparent", MS_ON); $map->outputformat->set("imagemode", "rgba"); $map->outputformat->setOption("formatoption","INTERLACE=OFF"); //web object $map->setMetaData("wms_srs","epsg:4326 epsg:2805 epsg:24600 epsg:54004 EPSG:900913"); /* set layer specific parameters */ $layer = ms_newLayerObj($map); $layer->set("name",$layer_tablename); switch($layer_type){ case 'polygon': $layer->set("type", MS_LAYER_POLYGON); break; case 'line': $layer->set("type", MS_LAYER_LINE); break; case 'point': $layer->set("type", MS_LAYER_POINT); } $layer->set("status", MS_ON); $layer->set("connectiontype",MS_POSTGIS); if("" == $dbpasswd) { $layer->set("connection","user="******" dbname=".$dbname." host=localhost"); } else { $layer->set("connection","user="******" password="******" dbname=".$dbname." host=localhost"); } $layer->set("data","__mlocate__topology from ".$layer_tablename . " using unique __mlocate__id"); $layer->set("classitem",trim($classitem)); $layer->set("transparency",65); $layer->set("template","template.html"); $layer->setMetaData("wms_feature_info_mime_type","text/html"); $layer->setMetaData("wms_include_items","all"); // loop through the list of values and create the corresponding classes $len = count($expressions); for($i = 0;$i<$len;$i++) { $class = ms_newClassObj($layer); $class->set("status",MS_ON); $class->set("name",urldecode($expressions[$i])); $class->setExpression("$expressions[$i]"); $style = ms_newStyleObj($class); $rgb_color = hex2rgb($hex_colors[$i]); $style->color->setRGB($rgb_color[0],$rgb_color[1],$rgb_color[2]); $style->outlinecolor->setRGB(000,000,000); $style->set("angle",0); } /* set layer specific parameters for select layer*/ $layer_select = ms_newLayerObj($map); $layer_select->set("name",$layer_tablename.'_select'); switch($layer_type){ case 'polygon': $layer_select->set("type", MS_LAYER_POLYGON); break; case 'line': $layer_select->set("type", MS_LAYER_LINE); break; case 'point': $layer_select->set("type", MS_LAYER_POINT); } $layer_select->set("status", MS_ON); //MS_LAYER_POLYGON $layer_select->set("connectiontype",MS_POSTGIS); if("" == $dbpasswd) { $layer_select->set("connection","user="******" dbname=".$dbname." host=localhost"); } else { $layer_select->set("connection","user="******" password="******" dbname=".$dbname." host=localhost"); } $class_select = ms_newClassObj($layer_select); $style_select = ms_newStyleObj($class_select); $style_select->outlinecolor->setRGB(000,000,255); $style_select->set("width",3); $layer_select->setfilter("'__mlocate__id = %pid%'"); $layer_select->set("data","__mlocate__topology from ".$layer_tablename . " using unique __mlocate__id"); /* set layer specific parameters for Search layer*/ $layer_search = ms_newLayerObj($map); $layer_search->set("name",$layer_tablename.'_search'); switch($layer_type){ case 'polygon': $layer_search->set("type", MS_LAYER_POLYGON); break; case 'line': $layer_search->set("type", MS_LAYER_LINE); break; case 'point': $layer_search->set("type", MS_LAYER_POINT); } $layer_search->set("status", MS_ON); $layer_search->set("connectiontype",MS_POSTGIS); if("" == $dbpasswd) { $layer_search->set("connection","user="******" dbname=".$dbname." host=localhost"); } else { $layer_search->set("connection","user="******" password="******" dbname=".$dbname." host=localhost"); } $layer_search->set("transparency",65); $layer_search->set("template","template.html"); $layer_search->setMetaData("wms_feature_info_mime_type","text/html"); $layer_search->setMetaData("wms_include_items","all"); $class_search = ms_newClassObj($layer_search); $style_search = ms_newStyleObj($class_search); $style_search->color->setRGB(228,245,205); $style_search->outlinecolor->setRGB(000,000,000); $style_search->set("width",3); $layer_search->setfilter("'__mlocate__id IN (%pid%)'"); $layer_search->set("data","__mlocate__topology from ".$layer_tablename . " using unique __mlocate__id"); /* set layer specific parameters for Search BBOX layer*/ $layer_searchBB = ms_newLayerObj($map); $layer_searchBB->set("name",$layer_tablename.'_searchBB'); switch($layer_type){ case 'polygon': $layer_searchBB->set("type", MS_LAYER_POLYGON); break; case 'line': $layer_searchBB->set("type", MS_LAYER_LINE); break; case 'point': $layer_searchBB->set("type", MS_LAYER_POINT); } $layer_searchBB->set("status", MS_ON); $layer_searchBB->set("connectiontype",MS_POSTGIS); if("" == $dbpasswd) { $layer_searchBB->set("connection","user="******" dbname=".$dbname." host=localhost"); } else { $layer_searchBB->set("connection","user="******" password="******" dbname=".$dbname." host=localhost"); } $class_searchBB = ms_newClassObj($layer_searchBB); $style_searchBB = ms_newStyleObj($class_searchBB); $style_searchBB->outlinecolor->setRGB(000,000,255); $style_searchBB->set("width",3); $layer_searchBB->setfilter("'__mlocate__id IN (%pid%)'"); $layer_searchBB->set("data","__mlocate__topology from ".$layer_tablename . " using unique __mlocate__id"); $map->save($name); echo $name; /* return file path */ }
function data2layer($oLayer, $dataLayer) { $oLayer->set("name", basename($this->arquivoGvp) . "_" . $oLayer->index); //$this->nomeRandomico()); $this->nomesLayersAdicionados[] = $oLayer->name; $oLayer->set("data", $dataLayer["data"]); if ($dataLayer["connectiontype"] != "") { $oLayer->setConnectionType($dataLayer["connectiontype"]); } if ($dataLayer["connection"] != "") { $oLayer->set("connection", $dataLayer["connection"]); } if ($dataLayer["proj"] != "") { $oLayer->setProjection($dataLayer["proj"]); } $oLayer->set("status", MS_DEFAULT); if ($dataLayer["visible"] == "false") { $oLayer->set("status", MS_OFF); } if (!empty($dataLayer["transparency"])) { $opacidade = $dataLayer["transparency"] * 100 / 255; $oLayer->set("opacity", $opacidade); } if ($dataLayer["minScale"] > 0) { $oLayer->set("minscaledenom", $dataLayer["minScale"]); } if ($dataLayer["maxScale"] > 0) { $oLayer->set("maxscaledenom", $dataLayer["maxScale"]); } $tipo = $dataLayer["legenda"]["classes"][0]["className"]; $oLayer->set("type", 1); if ($tipo == "com.iver.cit.gvsig.fmap.core.symbols.SimpleMarkerSymbol") { $oLayer->set("type", 0); } if ($tipo == "com.iver.cit.gvsig.fmap.core.symbols.SimpleFillSymbol") { $oLayer->set("type", 2); } foreach ($dataLayer["legenda"]["classes"] as $data) { //var_dump($data); $classe = ms_newClassObj($oLayer); $classe->set("name", $data["nome"]); $estilo = ms_newStyleObj($classe); if ($oLayer->type == 0) { $estilo->set("symbolname", "ponto"); } if (!empty($data["color"])) { if ($data["hasFill"] == "true") { $ncor = explode(",", $data["color"]); $cor = $estilo->color; $cor->setrgb($ncor[0], $ncor[1], $ncor[2]); } if ($data["hasOutline"] == "true" && $data["outline"] != "") { $ncor = explode(",", $data["outline"]); $cor = $estilo->outlinecolor; $cor->setrgb($ncor[0], $ncor[1], $ncor[2]); } if ($data["hasFill"] == "" && $data["hasOutline"] == "") { $ncor = explode(",", $data["color"]); $cor = $estilo->color; $cor->setrgb($ncor[0], $ncor[1], $ncor[2]); } } if ($data["size"] != false) { $estilo->set("size", $data["size"]); } if ($data["exp"] != false) { $classe->setExpression($data["exp"]); } } return $oLayer; }
/** * Create all legend icons and group/layer */ public function createLegendList() { $legPath = $_SESSION['PM_BASE_DIR'] . "/images/legend/"; $imgLogFile = $legPath . 'createimg.log'; $this->map->selectOutputFormat($_SESSION["imgFormat"]); $allLayers = $this->map->getAllLayerNames(); // Define background image for legend icons //$icoBGLayer = ms_newLayerObj($this->map); //$icoBGLayer->set("type", 2); // Add class /*$bgClass = ms_newClassObj($icoBGLayer); $bgClStyle = ms_newStyleObj($bgClass); $bgClStyle->color->setRGB(255, 255, 255); $bgClStyle->outlinecolor->setRGB(180, 180, 180);*/ //return false; foreach ($allLayers as $layName) { $qLayer = $this->map->getLayerByName($layName); // All layers but RASTER or ANNOTATION layers $numclasses = $qLayer->numclasses; if ($numclasses > 0) { $clno = 0; for ($cl = 0; $cl < $numclasses; $cl++) { $class = $qLayer->getClass($cl); if (!$class->keyimage) { $clname = $numclasses < 2 ? "" : $class->name; $clStyle = ms_newStyleObj($class); // Set outline for line themes to background color if ($qLayer->type == 1) { #$clStyle->setcolor("outlinecolor", 180, 180, 180); #$clStyle->outlinecolor->setRGB(180, 180, 180); } // set outline to main color if no outline defined (workaround for a bug in the icon creation) if ($qLayer->type == 2) { if ($clStyle->outlinecolor->red == -1 || $clStyle->outlinecolor->green == -1 || $clStyle->outlinecolor->blue == -1) { #$clStyle->setcolor("outlinecolor", $clStyle->color); $clStyle->outlinecolor->setRGB($clStyle->color->red, $clStyle->color->green, $clStyle->color->blue); } } // bad legend icon (due to symbolscaledenom, unit or attribute size/width binding) // if ($qLayer->type == MS_LAYER_POINT) { // find max size for all styles $maxSymbolSize = 0; $maxSymbolWidth = 0; $numStyles = $class->numstyles; for ($iStyle = 0; $iStyle < $numStyles; $iStyle++) { $style = $class->getStyle($iStyle); if ($style->size > $maxSymbolSize) { $maxSymbolSize = $style->size; } if ($style->width > $maxSymbolWidth) { $maxSymbolWidth = $style->width; } } // reduce all symbol size and set minsize and maxsize to the same value than size for ($iStyle = 0; $iStyle < $numStyles; $iStyle++) { $style = $class->getStyle($iStyle); // Size: // attribute binding: $changeSize = false; $newSize = 0; if ($style->size == -1) { // line widthout size --> MS use symbol defined size, but it's not the good way to do... if ($qLayer->type == MS_LAYER_LINE) { $newSize = 1; $changeSize = true; } else { if ($qLayer->type == MS_LAYER_POLYGON) { $newSize = $_SESSION["icoH"] / 0.8 / 4; $changeSize = true; } else { // $newSize = $_SESSION["icoH"] / 0.8; $changeSize = false; } } // reduce size } else { if ($maxSymbolSize > $_SESSION["icoH"]) { $newSize = $style->size * $_SESSION["icoH"] / $maxSymbolSize; $changeSize = true; } } if ($changeSize) { $style->set('size', $newSize); } // set minsize and maxsize to size $style->set('minsize', $style->size); $style->set('maxsize', $style->size); // Width: // attribute binding: $changeWidth = false; $newWidth = 0; // bad width for MS > 6 if ($_SESSION['MS_VERSION'] >= 6) { if ($qLayer->type == MS_LAYER_LINE) { $maxLineWidth = 4; // max width in pixel for legend $widthLimitFactor = $_SESSION["icoH"] / $maxLineWidth; if ($maxSymbolWidth > $widthLimitFactor) { $maxSymbolWidth = $maxSymbolWidth * $widthLimitFactor; } } } if ($style->width == -1) { // $newWidth = $_SESSION["icoH"]; $changeWidth = false; if ($qLayer->type == MS_LAYER_POLYGON) { $newWidth = $_SESSION["icoH"] / $maxSymbolWidth; $changeWidth = true; } // reduce width } else { if ($maxSymbolWidth > $_SESSION["icoH"]) { $newWidth = $style->width * $_SESSION["icoH"] / $maxSymbolWidth; $changeWidth = true; } } if ($changeWidth) { $style->set('width', $newWidth); } // set minwidth and maxwidth to width $style->set('minwidth', $style->width); $style->set('maxwidth', $style->width); } // set size units in pixel : $qLayer->set('sizeunits', MS_PIXELS); // } $icoImg = $class->createLegendIcon($_SESSION["icoW"], $_SESSION["icoH"]); // needed for ms 3.7 $imgFile = $legPath . $layName . '_i' . $clno . '.' . $_SESSION["imgFormatExt"]; //error_log($imgFile); $icoUrl = $icoImg->saveImage($imgFile); PMCommon::freeMsObj($icoImg); // class->keyimage --> generate icon too } else { if (isset($_SESSION['legendKeyimageRewrite']) && $_SESSION['legendKeyimageRewrite'] == '1') { $imgFile = $legPath . $layName . '_i' . $clno . '.' . $_SESSION['imgFormatExt']; $keyimage = dirname($_SESSION['PM_MAP_FILE']) . '/' . $class->keyimage; if (file_exists($keyimage)) { if (extension_loaded('gd')) { // existing image: $imageInfo = getimagesize($keyimage); $imageType = $imageInfo[2]; $imageWidth = $imageInfo[0]; $imageHeight = $imageInfo[1]; if ($imageType == IMAGETYPE_JPEG) { $image = imagecreatefromjpeg($keyimage); } elseif ($imageType == IMAGETYPE_GIF) { $image = imagecreatefromgif($keyimage); } elseif ($imageType == IMAGETYPE_PNG) { $image = imagecreatefrompng($keyimage); } // new size: $wRedFactor = $imageWidth <= $_SESSION['icoW'] ? 1 : $_SESSION['icoW'] / $imageWidth; $hRedFactor = $imageHeight <= $_SESSION['icoH'] ? 1 : $_SESSION['icoH'] / $imageHeight; $redFactor = min(max($wRedFactor, $hRedFactor), 1); $newWidth = $imageWidth * $redFactor; $newHeight = $imageHeight * $redFactor; //new image: $newImage = imagecreatetruecolor($newWidth, $newHeight); imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $imageWidth, $imageHeight); $newFormat = strtolower($_SESSION['imgFormatExt']); switch ($newFormat) { case 'png': imagepng($newImage, $imgFile); break; case 'jpg': case 'jpeg': imagejpeg($newImage, $imgFile); break; case 'gif': imagegif($newImage, $imgFile); break; default: break; } } } } } if ($class->name) { $clno++; } } } else { //error_log("connType: " . $qLayer->connectiontype); if ($qLayer->connectiontype == 7) { //$this->getWmsLegend($qLayer, $layName, $legPath); } } } date_default_timezone_set($_SESSION['defaultTimeZone']); // Required for PHP 5.3 $today = getdate(); $datestr = $today['hours'] . ':' . $today['minutes'] . ':' . $today['seconds'] . '; ' . $today['mday'] . '/' . $today['month'] . '/' . $today['year']; $logStr = "Created legend icons newly on: {$datestr}"; $imgLogFileFH = fopen($imgLogFile, 'w+'); fwrite($imgLogFileFH, $logStr); fclose($imgLogFileFH); }
function autoClasses(&$nlayer, $mapa, $locaplic = null) { $postgis_mapa = ""; $substituicon = "nao"; include dirname(__FILE__) . "/../ms_configura.php"; if ($nlayer->connectiontype == MS_POSTGIS) { if ($nlayer->connection == " ") { $nlayer->set("connection", $postgis_mapa); $substituicon = "sim"; } } // //gera classes automaticamente (temas vetoriais) if ($nlayer->getmetadata("classesitem") != "") { $itemnome = $nlayer->getmetadata("classesnome"); $itemid = $nlayer->getmetadata("classesitem"); $itemcor = $nlayer->getmetadata("classescor"); $itemsimbolo = $nlayer->getmetadata("classesimbolo"); $itemtamanho = $nlayer->getmetadata("classestamanho"); $classeoriginal = $nlayer->getclass(0); // //pega a extensao geografica que devera ser utilizada // $prjMapa = $mapa->getProjection(); $prjTema = $nlayer->getProjection(); $ret = $nlayer->getmetadata("extensao"); if ($ret == "") { $ret = $nlayer->getextent(); //reprojeta o retangulo if ($prjTema != "" && $prjMapa != $prjTema) { $projInObj = ms_newprojectionobj($prjTema); $projOutObj = ms_newprojectionobj($prjMapa); $ret->project($projInObj, $projOutObj); } } else { $temp = explode(" ", $ret); $ret = ms_newRectObj(); $ret->setextent($temp[0], $temp[1], $temp[2], $temp[3]); } // $sopen = $nlayer->open(); if ($sopen == MS_FAILURE) { return "erro"; } $status = $nlayer->whichShapes($ret); $parametrosClasses = array(); if ($status == 0) { while ($shape = $nlayer->nextShape()) { $id = trim($shape->values[$itemid]); if (!$parametrosClasses[$id]) { $nome = ""; if ($itemnome != "") { $nome = trim($shape->values[$itemnome]); } $cor = ""; if ($itemcor != "") { $cor = explode(",", trim($shape->values[$itemcor])); } if (count($cor) != 3) { $cor = explode(" ", trim($shape->values[$itemcor])); } $tamanho = ""; if ($itemtamanho != "") { $tamanho = trim($shape->values[$itemtamanho]); } $simbolo = ""; if ($itemsimbolo != "") { $simbolo = trim($shape->values[$itemsimbolo]); } $parametrosClasses[$id] = array("nome" => $nome, "cor" => $cor, "tamanho" => $tamanho, "simbolo" => $simbolo); } } $fechou = $nlayer->close(); //echo "<pre>";var_dump($parametrosClasses); if (count($parametrosClasses) > 0) { $ids = array_keys($parametrosClasses); for ($i = 0; $i < count($parametrosClasses); ++$i) { $p = $parametrosClasses[$ids[$i]]; //echo "<pre>";var_dump($p); $nclasse = ms_newClassObj($nlayer, $classeoriginal); if ($p["nome"] != "") { $nclasse->set("name", $p["nome"]); } $estilo = $nclasse->getstyle(0); if ($p["cor"] != "") { $cor = $p["cor"]; $ncor = $estilo->color; if ($ncor == "") { $ncor = $estilo->outlinecolor; } $ncor->setrgb($cor[0], $cor[1], $cor[2]); } if ($p["tamanho"] != "") { $estilo->set("size", $p["tamanho"]); } if ($p["simbolo"] != "") { $estilo->set("symbolname", $p["simbolo"]); } $strE = "('[" . $itemid . "]'eq'" . $ids[$i] . "')"; $nclasse->setexpression($strE); } $classeoriginal->set("status", MS_DELETE); } } if ($substituicon == "sim") { $nlayer->set("connection", " "); } } $pf = $nlayer->getmetadata("palletefile"); if ($pf != "") { if (!file_exists($pf)) { return; } $ps = $nlayer->getmetadata("palletesteps"); if ($ps == "") { $ps = 8; } // //pega os valores do arquivo // $rules = array(); $abre = fopen($pf, "r"); $paletteRules = array(); while (!feof($abre)) { $line = trim(fgets($abre)); $pos = strpos($line, "#"); if ($pos === false || $pos > 0) { $paletteEntry = explode(" ", $line); $rules[] = array("v0" => $paletteEntry[0], "v1" => $paletteEntry[1], "r0" => $paletteEntry[2], "g0" => $paletteEntry[3], "b0" => $paletteEntry[4], "r1" => $paletteEntry[5], "g1" => $paletteEntry[6], "b1" => $paletteEntry[7]); } } fclose($abre); foreach ($rules as $rule) { $delta = ceil(($rule["v1"] - $rule["v0"]) / $ps); $legenda = true; for ($value = $rule["v0"]; $value < $rule["v1"]; $value += $delta) { $class = ms_newClassObj($nlayer); $style = ms_newStyleObj($class); if ($legenda) { $class->set(name, round($value, 0)); $legenda = true; } $expression = "([pixel] > " . round($value, 0) . " AND [pixel] <= " . round($value + $delta, 0) . ")"; $class->setExpression($expression); $rgb = getRGBpallete($rule, $value); $style->color->setRGB($rgb[0], $rgb[1], $rgb[2]); } } } return; }
/** * Create class and style object */ private function createMSObj($type, $pObj) { switch ($type) { case "class": return ms_newClassObj($pObj); case "style": return ms_newStyleObj($pObj); } }
$layer->setMetaData("wms_title", $phplayers[$i]['name']); //$layer->setConnectionType(MS_POSTGIS); $layer->set("connectiontype", MS_POSTGIS); $layer->set("connection", "user={$postgis_user} dbname={$postgis_dbname} host={$postgis_host} port={$postgis_port} password={$postgis_pass}"); $layer->set("data", $phplayers[$i]['geometry_name'] . " FROM " . $phplayers[$i]['name']); // If the layer does not have a projection, set the projection to WGS84. if ($phplayers[$i]['PROJ4'] == NULL) { $layer->setProjection("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"); } else { $layer->setProjection($phplayers[$i]['PROJ4']); } // Construct a class object, with style $class = ms_newClassObj($layer); //$class->updateFromString('CLASS NAME className STYLE OUTLINECOLOR 144 50 207 END END'); $class->set("name", $phplayers[$i]['name']); $style = ms_newStyleObj($class); /* Set the graphical representation parameters of the geometry. If the geometry is a * point, render the image associated with the layer (in the layers table, image is * residing in the images folder specified in config-*.inc.php). If the geometry is * a line or a polygon, draw a line using the (R G B) colors specified in the layers * table. */ switch (strtolower($phplayers[$i]['geometry_type'])) { case "multipoint": case "point": $gsymbol = $phplayers[$i]['geometry_symbol']; $layer->set("type", MS_LAYER_POINT); $style->set("symbol", MS_SYMBOL_PIXMAP); $symbol = $map->getSymbolObjectById(ms_newSymbolObj($map, $gsymbol)); $symbol->setImagePath($image_directory . $gsymbol); $style->set("symbolname", $gsymbol);
function generate_map_file() { $map = ms_newMapObj($this->default_map_file); $n_layers = count($this->viewable_layers); // go through and create new // layer objects for those layers // that have their display property set // to true, adding them to the // map object for ($i = 0; $i < $n_layers; $i++) { if ($this->viewable_layers[$i]->display == "true") { $layer = ms_newLayerObj($map); $layer->set("name", $this->viewable_layers[$i]->layer_name); $layer->set("status", MS_OFF); $layer->set("template", "nepas.html"); $this->set_ms_layer_type($layer, $this->viewable_layers[$i]); $layer->set("connectiontype", MS_POSTGIS); $layer->set("connection", $this->dbconn->mapserver_conn_str); $this->set_ms_data_string($layer, $this->viewable_layers[$i]); $layer->setProjection($this->viewable_layers[$i]->layer_proj); // added to allow getfeatureinfo requests on // this layer via WMS $layer->setMetaData("WMS_INCLUDE_ITEMS", "all"); // generate a CLASSITEM directive if ($this->viewable_layers[$i]->layer_ms_classitem != "") { $layer->set("classitem", $this->viewable_layers[$i]->layer_ms_classitem); } // generate classes that this // layer contains $n_classes = count($this->viewable_layers[$i]->layer_classes); for ($j = 0; $j < $n_classes; $j++) { $ms_class_obj = ms_newClassObj($layer); $ms_class_obj->set("name", $this->viewable_layers[$i]->layer_classes[$j]->name); $ms_class_obj->setExpression($this->viewable_layers[$i]->layer_classes[$j]->expression); foreach ($this->viewable_layers[$i]->layer_classes[$j]->styles as $style) { $ms_style_obj = ms_newStyleObj($ms_class_obj); $ms_style_obj->color->setRGB($style->color_r, $style->color_g, $style->color_b); // set bg color $ms_style_obj->backgroundcolor->setRGB($style->bgcolor_r, $style->bgcolor_g, $style->bgcolor_b); // set outline color $ms_style_obj->outlinecolor->setRGB($style->outlinecolor_r, $style->outlinecolor_g, $style->outlinecolor_b); if ($style->symbol_name != "") { $ms_style_obj->set("symbolname", $style->symbol_name); // check for valid size if ($style->symbol_size != "") { $ms_style_obj->set("size", $style->symbol_size); } // check for valid angle if ($style->angle != "") { $ms_style_obj->set("angle", $style->angle); } // check for valid width if ($style->width != "") { $ms_style_obj->set("width", $style->width); } } } } } } if ($map->save($this->output_mapfile) == MS_FAILURE) { echo "mapfile could not be saved"; return NULL; } return $this->output_mapfile; }
function aplicaTodasClasses($parametro, $valor) { if (!$this->layer) { return "erro"; } $numc = $this->layer->numclasses; for ($c = 0; $c < $numc; $c++) { $classe = $this->layer->getclass($c); $estilo = $classe->getstyle(0); switch ($parametro) { case "pattern": if (!empty($pattern)) { $pattern = str_replace(",", " ", $valor); if ($this->v >= 6) { $estilo->updatefromstring("STYLE PATTERN " . $valor . " END"); } } continue; case "symbolname": if ($parametro == "" || $parametro == "0") { $classe->deletestyle($estilo); $estilo = ms_newStyleObj($classe); } else { if (is_numeric($valor)) { $estilo->set("symbol", $valor); } else { $estilo->set("symbolname", $valor); } } continue; case "outlinecolor": $cor = $estilo->outlinecolor; $nc = explode(",", $valor); $cor->setRGB($nc[0], $nc[1], $nc[2]); continue; case "backgroundcolor": $cor = $estilo->backgroundcolor; $nc = explode(",", $valor); $cor->setRGB($nc[0], $nc[1], $nc[2]); continue; case "color": $cor = $estilo->color; $nc = explode(",", $valor); $cor->setRGB($nc[0], $nc[1], $nc[2]); continue; case "size": if (is_numeric($valor)) { $estilo->removebinding(MS_STYLE_BINDING_SIZE); $estilo->set("size", $valor); } else { $estilo->setbinding(MS_STYLE_BINDING_SIZE, $valor); } continue; case "width": $estilo->set("width", $valor); continue; case "offsetx": $estilo->set("offsetx", $valor); continue; case "offsety": $estilo->set("offsety", $valor); continue; case "opacity": $estilo->set("opacity", $valor); continue; case "angle": $estilo->set("angle", $valor); continue; } } $this->layer->setMetaData("cache", ""); return "ok"; }
function updateMapfile($layer_tablename,$hex_colors,$expressions,$classitem) { if (PHP_OS == "WINNT" || PHP_OS == "WIN32") { define( "MODULE", "php_mapscript.dll" ); // load the mapscript module if (!extension_loaded("MapScript")) dl(MODULE); } else { dl("php_mapscript.so"); } $FILEPATH = $_SERVER['SCRIPT_FILENAME']; // remove the file name and append the new directory name if (PHP_OS == "WINNT" || PHP_OS == "WIN32") { $pos1 = strrpos($FILEPATH,'\\'); $FILEPATH= substr($FILEPATH,0,$pos1)."\\choropleth\\"; }else{ $pos1 = strrpos($FILEPATH,'/'); $FILEPATH= substr($FILEPATH,0,$pos1)."/choropleth/"; } $base_path = base_path(); global $user; $ret_file= array(); //global $db_url; $layer_type =''; $query = "select layer_type from \"Meta_Layer\" where layer_tablename='".$layer_tablename."'"; $result = db_query($query); if($obj = db_fetch_object($result)){ switch($obj->layer_type){ case 'POLYGON': case 'MULTIPOLYGON': $layer_type = 'polygon'; break; case 'LINESTRING': case 'MULTILINESTRING': $layer_type = 'line'; break; case 'POINT': case 'MULTIPOINT': $layer_type = 'point'; break; } } $mapfilename = $layer_tablename; // $dbpasswd = substr($db_url,$index2,$index2-$index1); // $dbuser = preg_replace('/pgsql:\/\/(.*)@[^@]*/','$1',$db_url); // $dbname = substr(strrchr($db_url,'/'),1); // if(strpos($dbuser,':') >= 0) { // list($dbuser,$dbpasswd) = split(":",$dbuser); // } else { // $dbpasswd = ""; // } $name = $FILEPATH.$mapfilename.".map"; /* create a file */ $fh = fopen($name,"w"); fwrite($fh,"map\n"); fwrite($fh,"end"); fclose($fh); /* create new map object and set the parameters */ $map = ms_newMapObj($name); $map->setExtent(60,0,100,40); $map->setSize(725,800); $map->set("units",MS_DD); $map->setProjection("init=epsg:4326"); $map->set("maxsize",4096); $map->selectOutputFormat('PNG'); $map->outputformat->set("transparent", MS_ON); $map->outputformat->set("imagemode", "rgba"); $map->outputformat->setOption("formatoption","INTERLACE=OFF"); //web object $map->setMetaData("wms_srs","epsg:4326 epsg:2805 epsg:24600 epsg:54004 EPSG:900913"); /* set layer specific parameters */ $layer = ms_newLayerObj($map); $layer->set("name",$layer_tablename); switch($layer_type){ case 'polygon': $layer->set("type", MS_LAYER_POLYGON); break; case 'line': $layer->set("type", MS_LAYER_LINE); break; case 'point': $layer->set("type", MS_LAYER_POINT); } $layer->set("status", MS_ON); $layer->set("connectiontype",MS_POSTGIS); $layer->set("connection", getDBConnectionString()); /* if("" == $dbpasswd) { $layer->set("connection","user="******" dbname=".$dbname." host=localhost"); } else { $layer->set("connection","user="******" password="******" dbname=".$dbname." host=localhost"); } */ $layer->set("data","__mlocate__topology from ".$layer_tablename . " using unique __mlocate__id"); $layer->set("classitem",trim($classitem)); $layer->set("transparency",65); $layer->set("template","template.html"); $layer->setMetaData("wms_feature_info_mime_type","text/html"); $layer->setMetaData("wms_include_items","all"); // loop through the list of values and create the corresponding classes $len = count($expressions); for($i = 0;$i<$len;$i++) { $class = ms_newClassObj($layer); $class->set("status",MS_ON); $cat = str_replace(' COMMA ',',' ,$expressions[$i] ); $class->set("name",urldecode($cat)); $class->setExpression("$cat"); $style = ms_newStyleObj($class); $rgb_color = hex2rgb($hex_colors[$i]); $style->color->setRGB($rgb_color[0],$rgb_color[1],$rgb_color[2]); $style->outlinecolor->setRGB(000,000,000); $style->set("angle",0); } /* set layer specific parameters for select layer*/ $layer_select = ms_newLayerObj($map); $layer_select->set("name",$layer_tablename.'_select'); switch($layer_type){ case 'polygon': $layer_select->set("type", MS_LAYER_POLYGON); break; case 'line': $layer_select->set("type", MS_LAYER_LINE); break; case 'point': $layer_select->set("type", MS_LAYER_POINT); } $layer_select->set("status", MS_ON); //MS_LAYER_POLYGON $layer_select->set("connectiontype",MS_POSTGIS); $layer->set("connection", getDBConnectionString()); /* if("" == $dbpasswd) { $layer_select->set("connection","user="******" dbname=".$dbname." host=localhost"); } else { $layer_select->set("connection","user="******" password="******" dbname=".$dbname." host=localhost"); } */ $class_select = ms_newClassObj($layer_select); $style_select = ms_newStyleObj($class_select); $style_select->outlinecolor->setRGB(000,000,255); $style_select->set("width",3); $layer_select->setfilter("'__mlocate__id = %pid%'"); $layer_select->set("data","__mlocate__topology from ".$layer_tablename . " using unique __mlocate__id"); /* set layer specific parameters for Search layer*/ $layer_search = ms_newLayerObj($map); $layer_search->set("name",$layer_tablename.'_search'); switch($layer_type){ case 'polygon': $layer_search->set("type", MS_LAYER_POLYGON); break; case 'line': $layer_search->set("type", MS_LAYER_LINE); break; case 'point': $layer_search->set("type", MS_LAYER_POINT); } $layer_search->set("status", MS_ON); $layer_search->set("connectiontype",MS_POSTGIS); $layer->set("connection", getDBConnectionString()); /* if("" == $dbpasswd) { $layer_search->set("connection","user="******" dbname=".$dbname." host=localhost"); } else { $layer_search->set("connection","user="******" password="******" dbname=".$dbname." host=localhost"); } */ $layer_search->set("transparency",65); $layer_search->set("template","template.html"); $layer_search->setMetaData("wms_feature_info_mime_type","text/html"); $layer_search->setMetaData("wms_include_items","all"); $class_search = ms_newClassObj($layer_search); $style_search = ms_newStyleObj($class_search); $style_search->color->setRGB(228,245,205); $style_search->outlinecolor->setRGB(000,000,000); $style_search->set("width",3); $layer_search->setfilter("'__mlocate__id IN (%pid%)'"); $layer_search->set("data","__mlocate__topology from ".$layer_tablename . " using unique __mlocate__id"); /* set layer specific parameters for Search BBOX layer*/ $layer_searchBB = ms_newLayerObj($map); $layer_searchBB->set("name",$layer_tablename.'_searchBB'); switch($layer_type){ case 'polygon': $layer_searchBB->set("type", MS_LAYER_POLYGON); break; case 'line': $layer_searchBB->set("type", MS_LAYER_LINE); break; case 'point': $layer_searchBB->set("type", MS_LAYER_POINT); } $layer_searchBB->set("status", MS_ON); $layer_searchBB->set("connectiontype",MS_POSTGIS); $layer->set("connection", getDBConnectionString()); $class_searchBB = ms_newClassObj($layer_searchBB); $style_searchBB = ms_newStyleObj($class_searchBB); $style_searchBB->outlinecolor->setRGB(000,000,255); $style_searchBB->set("width",3); $layer_searchBB->setfilter("'__mlocate__id IN (%pid%)'"); $layer_searchBB->set("data","__mlocate__topology from ".$layer_tablename . " using unique __mlocate__id"); $map->save($name); }
function inserePoligonosUrl() { global $tamanhosimbolo, $simbolo, $corsimbolo, $poligonos, $nometemapoligonos, $dir_tmp, $imgdir, $tmpfname, $locaplic; include_once "pacotes/phpxbase/api_conversion.php"; if (!isset($nometemapoligonos)) { $nometemapoligonos = "Poligonos"; } if ($nometemapoligonos == "") { $nometemapoligonos = "Poligonos"; } // //cria o shape file // $tipol = MS_SHP_POLYGON; $nomeshp = $dir_tmp . "/" . $imgdir . "/poligonosins"; // cria o dbf $def = array(); $items = array("COORD"); foreach ($items as $ni) { $def[] = array($ni, "C", "254"); } if (!function_exists(dbase_create)) { xbase_create($nomeshp . ".dbf", $def); } else { dbase_create($nomeshp . ".dbf", $def); } $dbname = $nomeshp . ".dbf"; $db = xbase_open($dbname, 2); $novoshpf = ms_newShapefileObj($nomeshp, $tipol); $linhas = explode(",", trim($poligonos)); $pontosLinhas = array(); //guarda os pontos de cada linha em arrays foreach ($linhas as $l) { $tempPTs = explode(" ", trim($l)); $temp = array(); foreach ($tempPTs as $p) { if (is_numeric($p)) { $temp[] = $p; } } $pontosLinhas[] = $temp; } foreach ($pontosLinhas as $ptsl) { $linhas = $ptsl; $shape = ms_newShapeObj($tipol); $linha = ms_newLineObj(); $reg = array(); $reg[] = ""; for ($ci = 0; $ci < count($linhas); $ci = $ci + 2) { $linha->addXY($linhas[$ci], $linhas[$ci + 1]); } $shape->add($linha); $novoshpf->addShape($shape); xbase_add_record($db, $reg); } $novoshpf->free(); xbase_close($db); //adiciona o layer $mapa = ms_newMapObj($tmpfname); $layer = ms_newLayerObj($mapa); $layer->set("name", "linhains"); $layer->set("data", $nomeshp . ".shp"); $layer->setmetadata("DOWNLOAD", "sim"); $layer->setmetadata("temalocal", "sim"); $layer->setmetadata("tema", $nometemapoligonos); $layer->setmetadata("classe", "sim"); $layer->setmetadata("ATLAS", "nao"); $layer->set("type", MS_LAYER_POLYGON); $layer->set("opacity", "50"); $layer->set("status", MS_DEFAULT); $classe = ms_newClassObj($layer); $classe->set("name", " "); $estilo = ms_newStyleObj($classe); $cor = $estilo->color; if (!isset($corsimbolo)) { $corsimbolo = "255,0,0"; } $corsimbolo = str_replace(" ", ",", $corsimbolo); $corsimbolo = explode(",", $corsimbolo); $cor->setRGB($corsimbolo[0], $corsimbolo[1], $corsimbolo[2]); $salvo = $mapa->save($tmpfname); erroCriacao(); }
public function getMapImage(Request $request) { //tutti i parametri in minuscolo $getRequestParams = $request->query->all(); $requestParams = array(); foreach ($getRequestParams as $key => $val) { $requestParams[strtolower($key)] = $val; } //prendo il parametro layers, dove ci sono le linee da visualizzare in formato li_nr:str_li_var $layers = explode(',', $requestParams['layers']); if (count($layers) > 1 || $layers[0] != 'all') { $lines = array(); $whereClauses = array(); foreach ($layers as $layer) { if (!strpos($layer, ':')) { throw new Exception('Invalid layers parameter'); } list($line, $var) = explode(':', $layer); array_push($lines, (int) $line); if (!preg_match('/[0-9a-z]+/i', $var)) { throw new Exception('Invalid var paramter'); } array_push($whereClauses, "(rec_lid.li_nr = " . (int) $line . " and rec_lid.str_li_var = '{$var}')"); } } $sql = "select li_nr, li_r, li_g, li_b from vdv.line_attributes"; if (isset($lines)) { $sql .= " where li_nr in (" . implode(',', $lines) . ")"; } $res = $this->connection->query($sql); $classes = $res->fetchAll(\PDO::FETCH_ASSOC); /* $classes = array( array('li_nr'=>201, 'li_r'=>255, 'li_g'=>0, 'li_b'=>0), array('li_nr'=>211, 'li_r'=>0, 'li_g'=>255, 'li_b'=>0), ); */ $layerData = "the_geom FROM (SELECT rec_lid.li_nr, rec_lid.str_li_var, rec_lid.li_nr || ':' || rec_lid.str_li_var as gc_objid, ST_Collect(ort_edges.the_geom) AS the_geom FROM vdv.rec_lid INNER JOIN vdv.lid_verlauf ON rec_lid.li_nr=lid_verlauf.li_nr AND rec_lid.str_li_var=lid_verlauf.str_li_var INNER JOIN vdv.lid_verlauf next_verlauf ON rec_lid.li_nr=next_verlauf.li_nr AND rec_lid.str_li_var=next_verlauf.str_li_var AND lid_verlauf.li_lfd_nr+1=next_verlauf.li_lfd_nr LEFT JOIN vdv.ort_edges ON lid_verlauf.ort_nr=ort_edges.start_ort_nr AND lid_verlauf.onr_typ_nr=ort_edges.start_onr_typ_nr AND next_verlauf.ort_nr=ort_edges.end_ort_nr AND next_verlauf.onr_typ_nr=ort_edges.end_onr_typ_nr "; // $layerData = "the_geom from (select the_geom, li_nr, li_nr || ':' || str_li_var as gc_objid from vdv.rec_lid "; if (isset($whereClauses)) { $layerData .= "where " . implode(' OR ', $whereClauses); } $layerData .= "GROUP BY rec_lid.li_nr, rec_lid.str_li_var) AS foo USING UNIQUE gc_objid USING SRID=25832"; // echo $layerData; die(); //TODO: pescarlo da resources! $mapfilePath = __DIR__ . '/../../Resources/config/lines_mapfile.map'; $map = ms_newMapobj($mapfilePath); $layer = $map->getLayerByName('g_lines.line'); $layer->set('data', $layerData); foreach ($classes as $n => $classConfig) { $class = ms_newClassObj($layer); $class->set('name', 'dynamic_class_' . $n); $class->setExpression("('[li_nr]' eq '" . $classConfig['li_nr'] . "')"); $style = ms_newStyleObj($class); $style->color->setRGB($classConfig['li_r'], $classConfig['li_g'], $classConfig['li_b']); $style->outlinecolor->setRGB($classConfig['li_r'], $classConfig['li_g'], $classConfig['li_b']); $style->set('size', 3); $style->set('width', 3); //$style->width = 2; //$style->symbol = 'CIRCLE'; } $objRequest = ms_newOwsrequestObj(); $presetParams = array('layers' => 'g_lines.line', 'map' => null); foreach ($requestParams as $key => $value) { if (!is_string($key)) { continue; } if (!empty($presetParams[$key])) { $objRequest->setParameter($key, $presetParams[$key]); } else { $objRequest->setParameter($key, stripslashes($value)); } } ms_ioinstallstdouttobuffer(); $map->save('/tmp/debug.map'); $map->owsdispatch($objRequest); $contentType = ms_iostripstdoutbuffercontenttype(); //accrocchio, ma ms_iogetstdoutbufferstring() non funziona, mi da sempre una immagine vuota! ob_start(); ms_iogetStdoutBufferBytes(); $image = ob_get_contents(); ob_end_clean(); //die($image); ms_ioresethandlers(); return array($contentType, $image); }
$pt = ms_newPointObj(); $pt->setXY(555, 160); //$pt->draw($map, $ia511, $img, 0, ""); } $logokey2 = $map->getlayerbyname("colorkey"); $c1 = $logokey2->getClass(0); $s1 = $c1->getStyle(0); $s1->set("symbolname", "logokey-8bit"); $s1->set("size", 60); $logokey = ms_newLayerObj($map); $logokey->set("type", MS_SHP_POINT); $logokey->set("transform", MS_FALSE); $logokey->set("status", MS_ON); $logokey->set("labelcache", MS_ON); $logokey_c3 = ms_newClassObj($logokey); $logokey_c3s0 = ms_newStyleObj($logokey_c3); //$logokey_c3s0->set("symbolname", "iem"); //$logokey_c3s0->set("size", 45); $l = $logokey_c3->addLabel(new labelObj()); $logokey_c3->getLabel(0)->set("buffer", 10); $logokey_c3->getLabel(0)->set("type", MS_BITMAP); $logokey_c3->getLabel(0)->set("size", MS_MEDIUM); $logokey_c3->getLabel(0)->color->setRGB(0, 0, 0); $bpt = ms_newpointobj(); $bpt->setXY(300, 300); $bpt->draw($map, $logokey, $img, 0, " "); $map->drawLabelCache($img); //$logokey2->draw($img); $layer = $map->getLayerByName("credits"); $c = $layer->getClass(0); $point = ms_newpointobj();
function analiseDistriPt($locaplic, $dir_tmp, $R_path, $numclasses, $tipo, $cori, $corf, $tmpurl, $sigma = "", $limitepontos = "TRUE", $tema2 = "", $extendelimite = 5, $item = "") { set_time_limit(120); // // pega os dados do tema dois para as funções que o utilizam // $dados1 = $this->gravaCoordenadasPt($this->nome, $limitepontos, $extendelimite, $item); $nomearq = $dados1["prefixoarquivo"]; $dimx = $dados1["dimx"]; $dimy = $dados1["dimy"]; $dimz = $dados1["dimz"]; if (isset($tema2) && $tema2 != "") { $dados2 = $this->gravaCoordenadasPt($tema2, $limitepontos, $extendelimite); $nomearq2 = $dados2["prefixoarquivo"]; $dimx2 = $dados2["dimx"]; $dimy2 = $dados2["dimy"]; } switch ($tipo) { // cluster espacial case "cluster": $this->mapaCluster($nomearq, $nomearq2, $dimx, $dimy, $dir_tmp, $R_path, $locaplic); return "ok"; break; // delaunay e voronoi // delaunay e voronoi case "deldir": // error_reporting(0); $this->mapaDeldir($nomearq, $dir_tmp, $R_path, $locaplic); $this->deldirDir2shp($nomearq . "dirsgs", $dir_tmp, $locaplic); $this->deldirDel2shp($nomearq . "delsgs", $dir_tmp, $locaplic); return "ok"; break; case "kernel": $this->mapaKernel($nomearq, $dimx, $dimy, $dir_tmp, $R_path, $locaplic, $sigma); break; case "densidade": $this->mapaDensidade($nomearq, $dimx, $dimy, $dir_tmp, $R_path, $locaplic, $dimz); break; case "distancia": $this->mapaDistancia($nomearq, $dimx, $dimy, $dir_tmp, $R_path, $locaplic); break; case "relatorio": $r = $this->mapaRelatorioAnaliseDist($nomearq, $dimx, $dimy, $dir_tmp, $R_path, $locaplic); return $tmpurl . basename($this->diretorio) . "/" . basename($nomearq) . '.htm'; break; } // cria a imagem $minmax = $this->criaImagemR($nomearq); // cria as cores include_once "class.palette.php"; $cori = RGB2hex(explode(",", $cori)); $corf = RGB2hex(explode(",", $corf)); $myPalette = new palette(array($cori, $corf), $numclasses + 1); // cria os parametros das classes $cls = $this->classesRasterI($minmax[0], $minmax[1], $numclasses, $myPalette->colorRGB); if (count($cls) != $numclasses) { return "erro."; } // adiciona o novo tema if (file_exists($nomearq . ".png")) { $novolayer = criaLayer($this->mapa, MS_LAYER_RASTER, MS_DEFAULT, $tipo . " (" . $this->nome . ")", $metaClasse = "SIM"); $novolayer->set("data", $nomearq . ".png"); $novolayer->set("template", "none.htm"); $novolayer->setmetadata("download", "sim"); // classes $numclassesatual = $novolayer->numclasses; for ($i = 0; $i < $numclassesatual; ++$i) { $classe = $novolayer->getClass($i); $classe->set("status", MS_DELETE); } for ($i = 0; $i < $numclasses; ++$i) { $classe = ms_newClassObj($novolayer); $novoestilo = ms_newStyleObj($classe); $ncor = $novoestilo->color; $cores = $cls[$i]["cores"]; $ncor->setrgb($cores[0], $cores[1], $cores[2]); $classe->setexpression($cls[$i]["expressao"]); $classe->set("name", $cls[$i]["nomeclasse"]); } $of = $this->mapa->outputformat; // $of->set("imagemode",MS_IMAGEMODE_RGB); // // reposiciona o layer // $layer = $this->mapa->getlayerbyname($this->nome); if ($layer != "") { $temp = ms_newLayerObj($this->mapa, $novolayer); $novolayer->set("status", MS_DELETE); $temp = ms_newLayerObj($this->mapa, $layer); $layer->set("status", MS_DELETE); } else { $indicel = $novolayer->index; $numlayers = $this->mapa->numlayers; $nummove = 0; for ($i = $numlayers - 1; $i > 0; $i--) { $layerAbaixo = $this->mapa->getlayer($i); $tipo = $layerAbaixo->type; if ($tipo != 2 && $tipo != 3) { $nummove++; } } if ($nummove > 2) { for ($i = 0; $i <= $nummove - 3; ++$i) { $this->mapa->movelayerup($indicel); } } } } else { return "erro"; } if (file_exists($this->qyfile)) { unlink($this->qyfile); } return $novolayer->name; }
function adicionaTemaGeoJson($servico, $dir_tmp, $locaplic) { $servico = str_replace("|", "?", $servico); $servico = str_replace("#", "&", $servico); $tipos = array("pontos", "linhas", "poligonos"); foreach ($tipos as $tipo) { $novolayer = ms_newLayerObj($this->mapa); $novolayer->set("connection", $servico); if (ms_GetVersionInt() > 50201) { $novolayer->setconnectiontype(MS_OGR); } else { $novolayer->set("connectiontype", MS_OGR); } $nome = nomeRandomico(10) . "geoJson"; $novolayer->set("name", $nome . $tipo); $novolayer->setmetadata("TEMA", "GeoJson " . $nome . " " . $tipo); $novolayer->setmetadata("DOWNLOAD", "SIM"); $novolayer->setmetadata("CLASSE", "SIM"); if ($tipo == "pontos") { $novolayer->set("type", MS_LAYER_POINT); } if ($tipo == "linhas") { $novolayer->set("type", MS_LAYER_LINE); } if ($tipo == "poligonos") { $novolayer->set("type", MS_LAYER_POLYGON); } $novolayer->set("type", $tipo); $novolayer->set("data", "OGRGeoJSON"); $novolayer->setfilter(""); $classe = ms_newClassObj($novolayer); $classe->set("name", ""); $estilo = ms_newStyleObj($classe); if ($tipo == "pontos") { $estilo->set("symbolname", "ponto"); $estilo->set("size", 10); } $estilo->color->setrgb(200, 50, 0); $estilo->outlinecolor->setrgb(0, 0, 0); // le os itens $novolayer->set("status", MS_DEFAULT); $novolayer->set("template", "none.htm"); } return "ok"; }
function valorunico($item, $ignorar, $itemNome = "") { if (!$this->layer) { return "erro"; } if ($itemNome == "" || $ignorar != "") { $itemNome = $item; } // pega valores $vs = $this->pegaValores($this->mapa, $this->layer, $item, false, $ignorar); if ($item == $itemNome) { $ns = $vs; } else { $ns = $this->pegaValores($this->mapa, $this->layer, $itemNome, false, $ignorar); } $lista = array(); for ($i = 0; $i < count($vs); ++$i) { $temp[$vs[$i]] = $ns[$i]; } $valores = array_keys($temp); $nomes = array(); foreach ($temp as $t) { $nomes[] = $t; } $nclassexist = $this->layer->numclasses; if ($nclassexist > count($valores)) { $nclassexist = count($valores); } if ($this->layer->numclasses == 0) { $temp = ms_newClassObj($this->layer); ms_newStyleObj($temp); } // cria classes $classes = array(); $classpadrao = $this->layer->getClass(0); for ($i = 0; $i < $nclassexist; ++$i) { $classes[$i] = $this->layer->getClass($i); } $c = $this->layer->numclasses; for ($i = 0; $i < $c; ++$i) { $cl = $this->layer->getClass($i); $cl->set("status", MS_DELETE); } $c = count($valores); for ($i = 0; $i < $c; ++$i) { $classes[$i] = ms_newClassObj($this->layer); $newstyle = ms_newStyleObj($classes[$i]); } for ($i = 0; $i < $c; ++$i) { $e = "('[" . $item . "]'eq'" . $valores[$i] . "')"; $ca = $classes[$i]; $ca->setexpression($e); $texto = $this->converteTexto($nomes[$i]); $ca->set("name", $texto); $estilo = $classes[$i]->getStyle(0); $ncor = $estilo->color; $ncor->setrgb(mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); $ncor = $estilo->outlinecolor; $ncor->setrgb(255, 255, 255); if ($this->layer->type == 0) { $estilo->set("symbolname", "ponto"); $estilo->set("size", 6); } //$c->set("title",$tema."+".$i); } $this->layer->setMetaData("cache", ""); return "ok"; }