classe_analise.php 80.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738
<?php
/*
Title: classe_analise.php

Gera análises espaciais, como buffer, calculo de centróides, etc.

Licenca:

GPL2


I3Geo Interface Integrada de Ferramentas de Geoprocessamento para Internet

Direitos Autorais Reservados (c) 2006 Ministério do Meio Ambiente Brasil
Desenvolvedor: Edmar Moretti edmar.moretti@mma.gov.br

Este programa é software livre; você pode redistribuí-lo
e/ou modificá-lo sob os termos da Licença Pública Geral
GNU conforme publicada pela Free Software Foundation;

Este programa é distribuído na expectativa de que seja útil,
porém, SEM NENHUMA GARANTIA; nem mesmo a garantia implícita
de COMERCIABILIDADE OU ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA.
Consulte a Licença Pública Geral do GNU para mais detalhes.
Você deve ter recebido uma cópia da Licença Pública Geral do
GNU junto com este programa; se não, escreva para a
Free Software Foundation, Inc., no endereço
59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.

Arquivo:

i3geo/classesphp/classe_analise.php
*/
/*
Classe: Analise

*/
class Analise
{
	/*
	Variavel: $mapa
	
	Objeto mapa
	*/
	public $mapa;
	/*
	Variavel: $arquivo
	
	Arquivo map file
	*/
	protected $arquivo;
	/*
	Variavel: $layer
	
	Objeto layer
	*/
	protected $layer;
	/*
	Variavel: $nome
	
	Nome do layer
	*/
	protected $nome;
	/*
	Variavel: $diretorio
	
	Diretório do arquivo map_file
	*/
	protected $diretorio;
	/*
	Variavel: $qyfile
	
	Nome do arquivo de seleção (.qy)
	*/
	public $qyfile;
	/*
	Variavel: $v
	
	Versão atual do Mapserver (primeiro dígito)
	*/
	public $v;	
	/*
	Variavel: $dbaseExiste
	
	Indica se a biblioteca dbase está carregada
	*/
	protected $dbaseExiste;
/*
Function: __construct

Cria um objeto Analise 

parameters:

$map_file - Endereço do mapfile no servidor.

$tema - Nome do tema que será processado

$ext - Extensão geográfica do mapa
*/  
	function __construct($map_file,$tema="",$locaplic="",$ext="")
	{
  		//error_reporting(E_ALL);
		$this->qyfile = str_replace(".map",".qy",$map_file);
  		if(file_exists($locaplic."/funcoes_gerais.php"))
  		include_once($locaplic."/funcoes_gerais.php");
  		else
  		include_once("funcoes_gerais.php");
		$this->v = versao();
		$this->v = $this->v["principal"];		
		$this->dbaseExiste = false;
		if(function_exists("dbase_create"))
		{$this->dbaseExiste = true;}		
  		$this->locaplic = $locaplic;
  		$this->mapa = ms_newMapObj($map_file);
  		$this->arquivo = $map_file;
  		if($tema != "" && @$this->mapa->getlayerbyname($tema))
 		{$this->layer = $this->mapa->getlayerbyname($tema);}
  		$this->nome = $tema;
  		$this->diretorio = dirname($this->arquivo);
		if($ext && $ext != ""){
			$e = explode(" ",$ext);
			$extatual = $this->mapa->extent;
			$extatual->setextent((min($e[0],$e[2])),(min($e[1],$e[3])),(max($e[0],$e[2])),(max($e[1],$e[3])));
		}
	}
/*
Method: criaDefDb

Cria um array contendo as definições das colunas que serão criadas em uma tabela DBF conforme as exigências de arquivos dbf

parameters:

$itens - array com os nomes originais das colunas

return:
{array}
*/
	function criaDefDb($itens){
		$c = 0;
		$def = array();
		foreach ($itens as $ni){
			$ni = strtoupper($ni);
			$def[] = array(substr($ni, 0, 8).$c,"C","254");
			$c = $c + 1;
		}
		return $def;
	}
/*
Method: truncaS

Trunca o comprimento de uma string em 255 caracteres

parameters:

$s - string

return
{string}
*/	
	function truncaS($s){
		if(strlen($s) > 255){
			$s = substr($s,0,255);
		}
		return $s;
	}
/*
Method: salva

Salva o mapfile atual 
*/	
 	function salva()
 	{
	  	if (connection_aborted()){exit();}
	  	$this->mapa->save($this->arquivo);
	}

/*
function: analiseDistriPt

Gera análise de distribuição de pontos.

Executa script R para gerar a imagem.

parameters:
$locaplic - Localização da aplicação I3Geo

$dir_tmp - Diretório temporário do mapserver

$R_path - Onde fica o R

$numclasses - Número de classes que serão representadas

$tipo - Tipo de análise.

$cori - Cor inicial em rgb.

$corf - Cor final em rgb.

$tmpurl - Url com o nome da imagem final

$sigma - desvio padrão para a opção kernel

$limitepontos - "TRUE"|"FALSE" limita o resultado ao limite geográfico dos pontos se "TRUE" ou ao limite do mapa se "FALSE"

$extendelimite - extende o limite dos pontos em um determinado percentual em relação a área final de abrangência
Include:
<class.palette.php>
*/
	function analiseDistriPt($locaplic,$dir_tmp,$R_path,$numclasses,$tipo,$cori,$corf,$tmpurl,$sigma="",$limitepontos="TRUE",$tema2="",$extendelimite=5)
	{
		set_time_limit(120);
		//
		//pega os dados do tema dois para as funções que o utilizam
		//
		$dados1 = $this->gravaCoordenadasPt($this->nome,$limitepontos,$extendelimite);
		$nomearq = $dados1["prefixoarquivo"];
		$dimx = $dados1["dimx"];
		$dimy = $dados1["dimy"];
		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
			case "deldir":
			$this->mapaDeldir($nomearq,$dir_tmp,$R_path,$locaplic);
			$this->deldirDir2shp($nomearq."dirsgs",$dir_tmp,$locaplic);
			$this->deldirDel2shp($nomearq."delsgs",$dir_tmp,$locaplic);
			if(file_exists($this->qyfile))
			{unlink($this->qyfile);}			
			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);
			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 = 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 = 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
			//
			$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("ok");
	}
/*
function: mapaRelatorioAnaliseDist

Gera um relatório da análise de distribuição de pontos.

Executa script R para gerar relatório .

parameters:

$arqpt - Prefixo dos arquivos em disco com os pontos.

$dimx - Range em x no formato R c(-54,-53).

$dimy - Range em y no formato R c(-25,-23).

$dir_tmp - Diretório temporário do mapserver.

$R_path - Onde fica o R.

$locaplic - Onde fica o I3Geo.
*/
	function mapaRelatorioAnaliseDist($arqpt,$dimx,$dimy,$dir_tmp,$R_path,$locaplic)
	{
		set_time_limit(180);
		$nomedir = dirname($arqpt)."/";
		$rcode[] = 'dadosx<-scan("'.$arqpt.'x")';
		$rcode[] = 'dadosy<-scan("'.$arqpt.'y")';
		$tipoimg = "bitmap";
		if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))
		{
			$lib = '.libPaths("'.$locaplic.'/pacotes/rlib/win")';
			if(file_exists($locaplic.'/pacotes/rlib/win'))
			$rcode[] = $lib;
			$tipoimg = "png";
		}
		else
		{
			if(file_exists($locaplic."/pacotes/rlib/linux"))
			{
				$lib = '.libPaths("'.$locaplic.'/pacotes/rlib/linux")';
				$rcode[] = $lib;
			}
		}		
		$rcode[] = 'library(spatstat)';
		$rcode[] = 'oppp <- ppp(dadosx, dadosy, '.$dimx.','.$dimy.')';
		$rcode[] = 'img<-distmap(oppp)';
		$rcode[] = 'zz <- file("'.$arqpt.'.htm", "w")';
		$rcode[] = 'sink(zz)';
		$rcode[] = 'cat("<br><b>Distância</b>\n", file = zz)';
		$rcode[] = 'sink()';
		$rcode[] = $tipoimg.'(file="'.$nomedir.'distancia.png")';
		$rcode[] = 'plot(img,main="")';
		$rcode[] = 'points(oppp$x,oppp$y,pch="x",col=1)';
		$rcode[] = 'dev.off()';
		$rcode[] = 'sink(zz)';
		$rcode[] = 'cat("<br></pre><img src=distancia.png />\n", file = zz)';
		$rcode[] = 'cat("<br>Resumo<pre>\n", file = zz)';
		$rcode[] = 'summary(img)';
		$rcode[] = 'cat("<br></pre>Quartis<pre>\n", file = zz)';
		$rcode[] = 'quantile.im(img)';
		$rcode[] = 'sink(zz)';
		$rcode[] = 'cat("<br>Histograma\n", file = zz)';
		$rcode[] = 'sink()';
		$rcode[] = $tipoimg.'(file="'.$nomedir.'histdistancia.png")';
		$rcode[] = 'hist.im(img,main="")';
		$rcode[] = 'points(oppp$x,oppp$y,pch="x",col=2)';
		$rcode[] = 'dev.off()';
		$rcode[] = 'sink(zz)';
		$rcode[] = 'cat("<br><img src=histdistancia.png />\n", file = zz)';
		$rcode[] = 'cat("<br></pre>Perspectiva\n", file = zz)';
		$rcode[] = 'sink()';
		$rcode[] = $tipoimg.'(file="'.$nomedir.'perspdistancia.png")';
		$rcode[] = 'p<-persp.im(img,colmap=terrain.colors(128),shade=0.3,theta=30,phi=45,main="")';
		$rcode[] = 'dev.off()';
		$rcode[] = 'sink(zz)';
		$rcode[] = 'cat("<br><img src=perspdistancia.png />\n", file = zz)';
		$rcode[] = 'cat("<br></pre>Contorno\n", file = zz)';
		$rcode[] = 'sink()';
		$rcode[] = $tipoimg.'(file="'.$nomedir.'contordistancia.png")';
		$rcode[] = 'contour.im(img,main="")';
		$rcode[] = 'points(oppp$x,oppp$y,pch="x",col=2)';
		$rcode[] = 'dev.off()';
		$rcode[] = 'sink(zz)';
		$rcode[] = 'cat("<br><img src=contordistancia.png />\n", file = zz)';
		$rcode[] = 'sink()';
		$rcode[] = 'img<-density.ppp(oppp)';
		$rcode[] = 'sink(zz)';
		$rcode[] = 'cat("<br><b>Densidade</b>\n", file = zz)';
		$rcode[] = 'sink()';
		$rcode[] = $tipoimg.'(file="'.$nomedir.'densidade.png")';
		$rcode[] = 'plot(img,main="")';
		$rcode[] = 'points(oppp$x,oppp$y,pch="x",col=2)';
		$rcode[] = 'dev.off()';
		$rcode[] = 'sink(zz)';
		$rcode[] = 'cat("<br></pre><img src=densidade.png />\n", file = zz)';
		$rcode[] = 'cat("<br>Resumo<pre>\n", file = zz)';
		$rcode[] = 'summary(img)';
		$rcode[] = 'cat("<br></pre>Quartis<pre>\n", file = zz)';
		$rcode[] = 'quantile.im(img)';
		$rcode[] = 'sink(zz)';
		$rcode[] = 'cat("<br>Histograma\n", file = zz)';
		$rcode[] = 'sink()';
		$rcode[] = $tipoimg.'(file="'.$nomedir.'histdensidade.png")';
		$rcode[] = 'hist.im(img,main="")';
		$rcode[] = 'dev.off()';
		$rcode[] = 'sink(zz)';
		$rcode[] = 'cat("<br><img src=histdensidade.png />\n", file = zz)';
		$rcode[] = 'cat("<br></pre>Perspectiva\n", file = zz)';
		$rcode[] = 'sink()';
		$rcode[] = $tipoimg.'(file="'.$nomedir.'perspdensidade.png")';
		$rcode[] = 'p<-persp.im(img,colmap=terrain.colors(128),shade=0.3,theta=30,phi=45,main="")';
		$rcode[] = 'dev.off()';
		$rcode[] = 'sink(zz)';
		$rcode[] = 'cat("<br><img src=perspdensidade.png />\n", file = zz)';
		$rcode[] = 'cat("<br></pre>Contorno\n", file = zz)';
		$rcode[] = 'sink()';
		$rcode[] = $tipoimg.'(file="'.$nomedir.'contordensidade.png")#,height =600, width = 600, res = 72)';
		$rcode[] = 'contour.im(img,main="")';
		$rcode[] = 'points(oppp$x,oppp$y,pch="x",col=2)';
		$rcode[] = 'dev.off()';
		$rcode[] = 'sink(zz)';
		$rcode[] = 'cat("<br><img src=contordensidade.png />\n", file = zz)';
		$rcode[] = 'sink()';
		$rcode[] = 'close(zz)';
		$r = executaR($rcode,$dir_tmp,$R_path);
	}
/*
function: mapaCluster

Gera um mapa de cluster.

Executa script R para gerar os dados.

parameters:
$arqpt - Prefixo dos arquivos em disco com os pontos.

$dimx - Range em x no formato R c(-54,-53).

$dimy - Range em y no formato R c(-25,-23).

$dir_tmp - Diretório temporário do mapserver.

$R_path - Onde fica o R.

$locaplic - Onde fica o I3Geo.

$sigma - Bandwidth for kernel smoother in "smooth" option.
*/
	function mapaCluster($arqpt,$arqpt2,$dimx,$dimy,$dir_tmp,$R_path,$locaplic)
	{
		$gfile_name = nomeRandomico(20);
		$rcode[] = 'dadosx<-scan("'.$arqpt.'x")';
		$rcode[] = 'dadosy<-scan("'.$arqpt.'y")';
		$rcode[] = 'dadosx2<-scan("'.$arqpt2.'x")';
		$rcode[] = 'dadosy2<-scan("'.$arqpt2.'y")';
		$rcode[] = 'd1<-data.frame(cbind(dadosx,dadosy))';
		$rcode[] = 'names(d1)<-(c("x","y"))';
		$rcode[] = 'd2<-data.frame(cbind(dadosx2,dadosy2))';
		$rcode[] = 'names(d2)<-(c("col1","col2"))';
		$rcode[] = 'd2<-as.matrix.data.frame(d2)';
		if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))
		{
			$lib = '.libPaths("'.$locaplic.'/pacotes/rlib/win")';
			if(file_exists($locaplic.'/pacotes/rlib/win'))
			$rcode[] = $lib;
		}
		else
		{
			if(file_exists($locaplic."/pacotes/rlib/linux"))
			{
				$lib = '.libPaths("'.$locaplic.'/pacotes/rlib/linux")';
				$rcode[] = $lib;
			}
		}		
		$rcode[] = 'library(spatclus)';
		$rcode[] = 'RES <- clus(d1,d2,limx='.$dimx.',limy='.$dimy.',eps=0.2)';
		//var_dump($rcode);
		$r = executaR($rcode,$dir_tmp,$R_path,$gfile_name);
		return "ok";
	}

/*
function: mapaKernel

Gera um mapa de kernel.

Executa script R para gerar a imagem.

parameters:
$arqpt - Prefixo dos arquivos em disco com os pontos.

$dimx - Range em x no formato R c(-54,-53).

$dimy - Range em y no formato R c(-25,-23).

$dir_tmp - Diretório temporário do mapserver.

$R_path - Onde fica o R.

$locaplic - Onde fica o I3Geo.

$sigma - Bandwidth for kernel smoother in "smooth" option.
*/
	function mapaKernel($arqpt,$dimx,$dimy,$dir_tmp,$R_path,$locaplic,$sigma="")
	{
		$gfile_name = nomeRandomico(20);
		$graf = "png";
		$rcode[] = 'dadosx<-scan("'.$arqpt.'x")';
		$rcode[] = 'dadosy<-scan("'.$arqpt.'y")';
		if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))
		{
			$lib = '.libPaths("'.$locaplic.'/pacotes/rlib/win")';
			if(file_exists($locaplic.'/pacotes/rlib/win'))
			$rcode[] = $lib;
			$tipoimg = "png";
		}
		else
		{
			if(file_exists($locaplic."/pacotes/rlib/linux"))
			{
				$lib = '.libPaths("'.$locaplic.'/pacotes/rlib/linux")';
				$rcode[] = $lib;
			}
		}		
		$rcode[] = 'library(spatstat)';
		$rcode[] = 'pt <- ppp(dadosx, dadosy, '.$dimx.','.$dimy.')';
		$rcode[] = 'img <- ksmooth.ppp(pt';
		if (is_numeric($sigma))
		{$rcode[] = ',sigma='.$sigma.')';}
		else
		{$rcode[] = ')';}
		$rcode[] = 'cat(img$v,file="'.$arqpt.'img",fill=FALSE)';
		$rcode[] = 'cat(img$xstep,file="'.$arqpt.'h",fill=TRUE)';
		$rcode[] = 'cat(img$ystep,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
		$rcode[] = 'cat(img$xrange,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
		$rcode[] = 'cat(img$yrange,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
		$rcode[] = 'cat(img$dim,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
		//var_dump($rcode);
		$r = executaR($rcode,$dir_tmp,$R_path,$gfile_name);
		return "ok";
	}
/*
function: mapaDensidade

Gera um mapa de densidade de pontos.

Executa script R para gerar a imagem.

parameters:
$arqpt - Prefixo dos arquivos em disco com os pontos.

$dimx - Range em x no formato R c(-54,-53).

$dimy - Range em y no formato R c(-25,-23).

$dir_tmp - Diretório temporário do mapserver.

$R_path - Onde fica o R.

$locaplic - Onde fica o I3Geo.
*/
	function mapaDensidade($arqpt,$dimx,$dimy,$dir_tmp,$R_path,$locaplic)
	{
		$gfile_name = nomeRandomico(20);
		$graf = "png";
		$rcode[] = 'dadosx<-scan("'.$arqpt.'x")';
		$rcode[] = 'dadosy<-scan("'.$arqpt.'y")';
		if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))
		{
			$lib = '.libPaths("'.$locaplic.'/pacotes/rlib/win")';
			if(file_exists($locaplic.'/pacotes/rlib/win'))
			$rcode[] = $lib;
			$tipoimg = "png";
		}
		else
		{
			if(file_exists($locaplic."/pacotes/rlib/linux"))
			{
				$lib = '.libPaths("'.$locaplic.'/pacotes/rlib/linux")';
				$rcode[] = $lib;
			}
		}		
		$rcode[] = 'library(spatstat)';
		$rcode[] = 'pt <- ppp(dadosx, dadosy, '.$dimx.','.$dimy.')';
		$rcode[] = 'img <- density.ppp(pt)';
		$rcode[] = 'cat(img$v,file="'.$arqpt.'img",fill=FALSE)';
		$rcode[] = 'cat(img$xstep,file="'.$arqpt.'h",fill=TRUE)';
		$rcode[] = 'cat(img$ystep,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
		$rcode[] = 'cat(img$xrange,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
		$rcode[] = 'cat(img$yrange,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
		$rcode[] = 'cat(img$dim,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
		$r = executaR($rcode,$dir_tmp,$R_path,$gfile_name);
		return "ok";
	}
/*
function: mapaDistancia

Gera um mapa de distancia de pontos.

Executa script R para gerar a imagem.

parameters:

$arqpt - Prefixo dos arquivos em disco com os pontos.

$dimx - Range em x no formato R c(-54,-53).

$dimy - Range em y no formato R c(-25,-23).

$dir_tmp - Diretório temporário do mapserver.

$R_path - Onde fica o R.

$locaplic - Onde fica o I3Geo.
*/
	function mapaDistancia($arqpt,$dimx,$dimy,$dir_tmp,$R_path,$locaplic)
	{
		$gfile_name = nomeRandomico(20);
		$graf = "png";
		$rcode[] = 'dadosx<-scan("'.$arqpt.'x")';
		$rcode[] = 'dadosy<-scan("'.$arqpt.'y")';
		if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))
		{
			$lib = '.libPaths("'.$locaplic.'/pacotes/rlib/win")';
			if(file_exists($locaplic.'/pacotes/rlib/win'))
			$rcode[] = $lib;
			$tipoimg = "png";
		}
		else
		{
			if(file_exists($locaplic."/pacotes/rlib/linux"))
			{
				$lib = '.libPaths("'.$locaplic.'/pacotes/rlib/linux")';
				$rcode[] = $lib;
			}
		}		
		$rcode[] = 'library(spatstat)';
		$rcode[] = 'pt <- ppp(dadosx, dadosy, '.$dimx.','.$dimy.')';
		$rcode[] = 'img <- distmap(pt)';
		$rcode[] = 'cat(img$v,file="'.$arqpt.'img",fill=FALSE)';
		$rcode[] = 'cat(img$xstep,file="'.$arqpt.'h",fill=TRUE)';
		$rcode[] = 'cat(img$ystep,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
		$rcode[] = 'cat(img$xrange,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
		$rcode[] = 'cat(img$yrange,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
		$rcode[] = 'cat(img$dim,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
		$r = executaR($rcode,$dir_tmp,$R_path,$gfile_name);
		return "ok";
	}
/*
function: mapaDeldir

Calcula a triangulação de Delaunay e diagrama de Voronoi.

Para funcionar, é necessário a instalação da biblioteca deldir do R.

http://cran.r-project.org/web/packages/deldir

parameters:

$arqpt - Prefixo dos arquivos em disco com os pontos.

$dir_tmp - Diretório temporário do mapserver.

$R_path - Onde fica o R.

$locaplic - Onde fica o I3Geo.
*/
	function mapaDeldir($arqpt,$dir_tmp,$R_path,$locaplic)
	{
		$gfile_name = nomeRandomico(20);
		$rcode[] = 'dadosx<-scan("'.$arqpt.'x")';
		$rcode[] = 'dadosy<-scan("'.$arqpt.'y")';
		if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))
		{
			$lib = '.libPaths("'.$locaplic.'/pacotes/rlib/win")';
			if(file_exists($locaplic.'/pacotes/rlib/win'))
			$rcode[] = $lib;
		}
		else
		{
			if(file_exists($locaplic."/pacotes/rlib/linux"))
			{
				$lib = '.libPaths("'.$locaplic.'/pacotes/rlib/linux")';
				$rcode[] = $lib;
			}
		}		
		$rcode[] = 'library(deldir)';
		$rcode[] = 'pt <- deldir(dadosx, dadosy)';
		$rcode[] = 'write.csv(pt$delsgs,file="'.$arqpt.'delsgs")';
		$rcode[] = 'write.csv(pt$dirsgs,file="'.$arqpt.'dirsgs")';
		$r = executaR($rcode,$dir_tmp,$R_path,$gfile_name);
		return "ok";
	}
/*
function deldirDel2shp

Lê um arquivo CSV gerado pelo software R com os dados referentes à triangulação de Delaunay.

O arquivo CSV é lido e convertido em um shape file que é então adicionado ao mapa.

Parametros:

$nomearq - nome do arquivo CSV

$dir_tmp - diretório temporário do Mapserver

$locaplic - diretório da aplicação i3geo
*/
	function deldirDel2shp($nomearq,$dir_tmp,$locaplic)
	{
		if (file_exists($nomearq))
		{
  			if($this->dbaseExiste == false){
				if(file_exists($this->locaplic."/pacotes/phpxbase/api_conversion.php"))
				include_once($this->locaplic."/pacotes/phpxbase/api_conversion.php");
				else	
				include_once "../pacotes/phpxbase/api_conversion.php";
			}
			//define o nome do novo shapefile que será criado
			$nomefinal = nomeRandomico();
			$nomeshp = $this->diretorio."/".$nomefinal;
			//cria o shape file
			$novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_ARC);
			// cria o dbf
			$def[] = array("x1","N","12","5");
			$def[] = array("y1","N","12","5");
			$def[] = array("x2","N","12","5");
			$def[] = array("y2","N","12","5");
			$def[] = array("ind1","N","5","0");
			$def[] = array("ind2","N","5","0");
			if($this->dbaseExiste == false)
			{$db = xbase_create($nomeshp.".dbf", $def);}
			else
			{$db = dbase_create($nomeshp.".dbf", $def);}				
			$dbname = $nomeshp.".dbf";
			//le o arquivo linha a linha, pulando a primeira
			//acrescenta os pontos no shape file formando as linhas
			$abre = fopen($nomearq, "r");
			$buffer = fgets($abre);
			$poligonos = array();
			while (!feof($abre))
			{
				$buffer = fgets($abre);
				$i = explode(",",$buffer);
				if(is_array($i))
				{
					$i1 = floatval($i[1]);
					$i2 = floatval($i[2]);
					$i3 = floatval($i[3]);
					$i4 = floatval($i[4]);
					$i5 = floatval($i[5]);
					$i6 = floatval($i[6]);
					$poPoint1 = ms_newpointobj();
					$poPoint1->setXY($i1,$i2);
					$poPoint2 = ms_newpointobj();
					$poPoint2->setXY($i3, $i4);			
					$linha = ms_newLineObj();
					$linha->add($poPoint1);
					$linha->add($poPoint2);
					$ShapeObj = ms_newShapeObj(MS_SHAPE_LINE);
					$ShapeObj->add($linha);	
					$novoshpf->addShape($ShapeObj);
					$registro = array($i1,$i2,$i3,$i4,$i5,$i6);
					if($this->dbaseExiste == false)
					xbase_add_record($db,$registro);
					else
					dbase_add_record($db,$registro);
					$linha->free();
					$ShapeObj->free();
				}
			}
			$novoshpf->free();
			if($this->dbaseExiste == false)
			xbase_close($db);
			else
			dbase_close($db);
			fclose($abre);		
			//adiciona no mapa atual o novo tema
			$novolayer = criaLayer($this->mapa,MS_LAYER_LINE,MS_DEFAULT,("Delaunay (".$nomefinal.")"),$metaClasse="SIM");
			$novolayer->set("data",$nomeshp.".shp");
			$novolayer->setmetadata("DOWNLOAD","SIM");
			$novolayer->set("template","none.htm");
			$classe = $novolayer->getclass(0);
			$estilo = $classe->getstyle(0);
			$estilo->set("symbolname","linha");
			$estilo->set("size",2);
			$cor = $estilo->color;
			$cor->setrgb(255,50,0);
		}
	}
/*
function deldirDir2shp

Lê um arquivo CSV gerado pelo software R com os dados referentes ao diagrama de Voronoi.

O arquivo CSV é lido e convertido em um shape file que é então adicionado ao mapa.

Parametros:

$nomearq - nome do arquivo CSV

$dir_tmp - diretório temporário do Mapserver

$locaplic - diretório da aplicação i3geo
*/	
	function deldirDir2shp($nomearq,$dir_tmp,$locaplic)
	{
		if (file_exists($nomearq))
		{
  			if($this->dbaseExiste == false){
				if(file_exists($this->locaplic."/pacotes/phpxbase/api_conversion.php"))
				include_once($this->locaplic."/pacotes/phpxbase/api_conversion.php");
				else	
				include_once "../pacotes/phpxbase/api_conversion.php";
			}
			//
			//define os nomes dos novos shapefiles que serão criados
			//
			$nomeLinhas = nomeRandomico();
			$nomePoligonos = nomeRandomico();
			$nomeshpLinhas = $this->diretorio."/".$nomeLinhas;
			$nomeshpPoligonos = $this->diretorio."/".$nomePoligonos;
			//cria o shape file
			$novoshpLinhas = ms_newShapefileObj($nomeshpLinhas, MS_SHP_ARC);
			$novoshpPoligonos = ms_newShapefileObj($nomeshpPoligonos, MS_SHP_POLYGON);
			//
			// cria o dbf para o shapefile linear
			//
			$def[] = array("x1","N","12","5");
			$def[] = array("y1","N","12","5");
			$def[] = array("x2","N","12","5");
			$def[] = array("y2","N","12","5");
			$def[] = array("ind1","N","5","0");
			$def[] = array("ind2","N","5","0");
			$def[] = array("b1","C","6");
			$def[] = array("b2","C","6");
			if($this->dbaseExiste == false)
			{$dbLinhas = xbase_create($nomeshpLinhas.".dbf", $def);}
			else
			{$dbLinhas = dbase_create($nomeshpLinhas.".dbf", $def);}				
			$dbnameLinhas = $nomeshpLinhas.".dbf";
			//
			// cria o dbf para o shapefile poligonal
			//
			$def = array();
			$def[] = array("area","N","12","5");
			if($this->dbaseExiste == false)
			{$dbPoligonos = xbase_create($nomeshpPoligonos.".dbf", $def);}
			else
			{$dbPoligonos = dbase_create($nomeshpPoligonos.".dbf", $def);}				
			$dbnamePoligonos = $nomeshpPoligonos.".dbf";
			//
			//constrói as linhas do diagrama
			//			
			//le o arquivo linha a linha, pulando a primeira
			//acrescenta os pontos no shape file formando as linhas
			//cria o array para criar os polígonos
			//
			$abre = fopen($nomearq, "r");
			$buffer = fgets($abre);
			$borda = array();//guarda os pontos que ficam na borda
			$poligonos = array();
			while (!feof($abre))
			{
				$buffer = fgets($abre);
				$i = explode(",",$buffer);
				if(is_array($i))
				{
					$i1 = floatval($i[1]);
					$i2 = floatval($i[2]);
					$i3 = floatval($i[3]);
					$i4 = floatval($i[4]);
					$i5 = floatval($i[5]);
					$i6 = floatval($i[6]);
					$poPoint1 = ms_newpointobj();
					$poPoint1->setXY($i1,$i2);
					$poPoint2 = ms_newpointobj();
					$poPoint2->setXY($i3, $i4);
					if(trim($i[7]) == "TRUE")
					{$borda[] = $poPoint1;}
					if(trim($i[8]) == "TRUE")
					{$borda[] = $poPoint2;}	
					$linha = ms_newLineObj();
					$linha->add($poPoint1);
					$linha->add($poPoint2);
					if($poligonos[$i[5]])
					$poligonos[$i[5]] = array_merge(array($linha),$poligonos[$i[5]]);
					else
					$poligonos[$i[5]] = array($linha);
					if($poligonos[$i[6]])
					$poligonos[$i[6]] = array_merge(array($linha),$poligonos[$i[6]]);
					else
					$poligonos[$i[6]] = array($linha);
					$ShapeObj = ms_newShapeObj(MS_SHAPE_LINE);
					$ShapeObj->add($linha);
					$novoshpLinhas->addShape($ShapeObj);
					$registro = array($i1,$i2,$i3,$i4,$i5,$i6,$i[7],$i[8]);
					if($this->dbaseExiste == false)
					xbase_add_record($dbLinhas,$registro);
					else
					dbase_add_record($dbLinhas,$registro);
					$ShapeObj->free();
				}
			}
			//
			//adiciona os poligonos
			//
			foreach ($poligonos as $p)
			{
				$ShapeObjp = ms_newShapeObj(MS_SHAPE_LINE);
				foreach ($p as $o)
				{$ShapeObjp->add($o);}
				$ns = $ShapeObjp->convexhull();
				$novoshpPoligonos->addShape($ns);
				$registro = array($ns->getArea());
				if($this->dbaseExiste == false)
				xbase_add_record($dbPoligonos,$registro);
				else
				dbase_add_record($dbPoligonos,$registro);
				$ShapeObjp->free();	
			}
			$novoshpPoligonos->free();
			if($this->dbaseExiste == false)
			xbase_close($dbPoligonos);
			else
			dbase_close($dbPoligonos);
			//
			//adiciona o layer com os polígonos no mapa
			//
			$novolayerp = criaLayer($this->mapa,MS_LAYER_POLYGON,MS_DEFAULT,("Voronoi - poligonos (".$nomePoligonos.")"),$metaClasse="SIM");
			$novolayerp->set("data",$nomeshpPoligonos.".shp");
			$novolayerp->setmetadata("DOWNLOAD","SIM");
			$novolayerp->set("template","none.htm");
			$classe = $novolayerp->getclass(0);
			$estilo = $classe->getstyle(0);
			$cor = $estilo->color;
			$cor->setrgb(240,240,240);
			//
			//adiciona no mapa atual o novo tema com as linhas do diagrama
			//
			if (count($borda > 2))
			{
				$linha = ms_newLineObj();
				foreach ($borda as $ponto)
				{
					$linha->add($ponto);
				}
				$ShapeObj = ms_newShapeObj(MS_SHAPE_LINE);
				$ShapeObj->add($linha);
				$novoshpLinhas->addShape($ShapeObj->convexhull());
				$registro = array(0,0,0,0,0,0,0,0);
				if($this->dbaseExiste == false)
				xbase_add_record($dbLinhas,$registro);
				else
				dbase_add_record($dbLinhas,$registro);
				$linha->free();
				$ShapeObj->free();				
			}
			$novoshpLinhas->free();
			if($this->dbaseExiste == false)
			xbase_close($dbLinhas);
			else
			dbase_close($dbLinhas);
			fclose($abre);			
			$novolayer = criaLayer($this->mapa,MS_LAYER_LINE,MS_DEFAULT,("Voronoi (".$nomeLinhas.")"),$metaClasse="SIM");
			$novolayer->set("data",$nomeshpLinhas.".shp");
			$novolayer->setmetadata("DOWNLOAD","SIM");
			$novolayer->set("template","none.htm");
			$classe = $novolayer->getclass(0);
			$estilo = $classe->getstyle(0);
			$estilo->set("symbolname","linha");
			$estilo->set("size",4);
			$cor = $estilo->color;
			$cor->setrgb(255,210,0);
		}
	}
/*
function: pontoEmPoligono

Cruza um tema pontual com temas poligonais ou raster.

Salva o mapa acrescentando um novo layer com o resultado.

parameters:

$temaPt - Tema de pontos que será utilizado.

$temaPo - Temas poligonais separados por virgula.

$locaplic - Localização do I3geo.
*/
	function pontoEmPoligono($temaPt,$temasPo,$locaplic)
	{
		set_time_limit(3000);
		if($this->dbaseExiste == false){
			if(file_exists($this->locaplic."/pacotes/phpxbase/api_conversion.php"))
			{include_once($this->locaplic."/pacotes/phpxbase/api_conversion.php");}
			else	
			{include_once "../pacotes/phpxbase/api_conversion.php";}
		}
		$layerPt = $this->mapa->getlayerbyname($temaPt);
		$layerPt->set("template","none.htm");
		$layerPt->set("tolerance",0);
		//define o nome do novo shapefile que será criado
		$nomefinal = nomeRandomico();
		$nomeshp = $this->diretorio."/".$nomefinal;
		//
		$spts = retornaShapesSelecionados($layerPt,$this->arquivo,$this->mapa);
		if(count($spts) == 0){
			$spts = retornaShapesMapext($layerPt,$this->mapa);
		}
		//
		$itemspt = pegaItens($layerPt);
		//gera o novo arquivo shape file
		// cria o dbf
		$def = $this->criaDefDb($itemspt);
		//pega os itens dos temas poligonais
		$layersPol = array();
		$temas = explode(",",$temasPo);
		$layers = array();
		$nomesitens = array(); //guarda os nomes dos temas e seus itens
		$conta = 0;
		$listaItens = array();
		foreach ($temas as $tema)
		{
			$layer = $this->mapa->getlayerbyname($tema);
			$layer->set("template","none.htm");
			$layer->set("status",MS_DEFAULT);
			$items = pegaItens($layer);
			if($layer->type == MS_LAYER_RASTER)
			{
				$lineo = $spts[0]->line(0);
				$pt = $lineo->point(0);
				$layer->queryByPoint($pt, 0, 0);
			}
			$layers[] = $layer;
			
			if(!$items)
			{return "erro ao obter a lista de itens do tema $layer->name";}
			$listaItens[$layer->name] = $items;
			foreach ($items as $ni)
			{
				$def[] = array("I".$conta,"C","254");
				$nomesitens[] = "Tema: ".$layer->name.", Item: ".$ni." Novo: I".$conta."<br>";
				$conta = $conta + 1;
			}
		}
		if($this->dbaseExiste == false)
		{$db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);}
		else
		{$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);}
		//acrescenta os pontos no novo shapefile
		$dbname = $nomeshp.".dbf";
		if($this->dbaseExiste == false)
		$db=xbase_open($dbname,2);
		else
		$db=dbase_open($dbname,2);
		// cria o shapefile
		$novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POINT);
		foreach($spts as $spt)
		{
			foreach ($itemspt as $ni)
			{$reg[] = $this->truncaS($spt->values[$ni]);}
			$novoshpf->addShape($spt);
			$lineo = $spt->line(0);
			$pt = $lineo->point(0);
			//faz a pesquisa
			error_reporting(E_ALL);
			foreach ($layers as $layer)
			{
				$layer->set("template","none.htm");
				$layer->set("toleranceunits",MS_PIXELS);
				$layer->set("tolerance",1);
				$ident = @$layer->queryByPoint($pt, 0, 0);
				if($ident == "MS_SUCCESS"){
					$itens = $listaItens[$layer->name];
					$sopen = $layer->open();
					if($sopen == MS_FAILURE){return "erro";}
					if ($layer->getResult(0) !== FALSE)
					{
						if($this->v == 6)
						{$shape = $layer->getShape($layer->getResult(0));}
						else{
							$result = $layer->getResult(0);
							$shp_index  = $result->shapeindex;					
							$shape = $layer->getfeature($shp_index,-1);						
						}
						foreach ($itens as $item)
						{$reg[] = $this->truncaS($shape->values[$item]);}
					}
					else
					{
						foreach ($itens as $item)
						{$reg[] = "???";}
					}
				}
				$layer->close();
			}
			if($this->dbaseExiste == false)
			xbase_add_record($db,$reg);
			else
			dbase_add_record($db,$reg);
			$reg = array();
		}
		$novoshpf->free();
		if($this->dbaseExiste == false)
		xbase_close($db);
		else
		dbase_close($db);	
		$novolayer = ms_newLayerObj($this->mapa, $layerPt);
		$novolayer->set("data",$nomeshp.".shp");
		$novolayer->set("name",$nomefinal);
		$novolayer->setmetadata("TEMA","Cruzamento (".$nomefinal.")");
		$novolayer->setmetadata("TEMALOCAL","SIM");
		$novolayer->setmetadata("DOWNLOAD","SIM");
		$novolayer->setmetadata("ITENS","");
		$novolayer->setmetadata("ITENSDESC","");				
		if(ms_GetVersionInt() > 50201)
		{$novolayer->setconnectiontype(MS_SHAPEFILE);}
		else
		{$novolayer->set("connectiontype",MS_SHAPEFILE);}
		if (file_exists($this->qyfile))
		{unlink ($this->qyfile);}
		return(implode(" ",$nomesitens));
	}
/*
function: distanciaptpt

Calcula a distancia entre um ponto de origem e os pontos em um tema.

São considerados apenas os pontos dentro de um tema de overlay.

parameters:

temaorigem - nome do layer com o ponto de origem

temadestino - nome do tema com os pontos de destino

temaoverlay - tema que será utilizado para selecionar o tema de destino

locapli - endereço da aplicação i3geo

itemorigem - nome do item na tabela de atributos do tema de origem que será acrescentado ao tema que será criado

itemdestino - nome do item na tabela de atributos do tema de origem que será acrescentado ao tema que será criado

*/
function distanciaptpt($temaorigem,$temadestino,$temaoverlay,$locaplic,$itemorigem="",$itemdestino="")
{
	error_reporting(E_ALL);
	set_time_limit(180);
	//para manipular dbf
	if($this->dbaseExiste == false){
		if(file_exists($this->locaplic."/pacotes/phpxbase/api_conversion.php"))
		include_once($this->locaplic."/pacotes/phpxbase/api_conversion.php");
		else	
		include_once "../pacotes/phpxbase/api_conversion.php";
	}
	//define o nome do novo shapefile que será criado
	$nomefinal = nomeRandomico();
	$nomeshp = $this->diretorio."/".$nomefinal;

	$existesel = carregaquery2($this->arquivo,$this->layer,$this->mapa);
	if ($existesel == "nao")
	{return "errox";}

	$layerorigem = $this->mapa->getlayerbyname($temaorigem);
	$layerdestino = $this->mapa->getlayerbyname($temadestino);
	$layeroverlay = $this->mapa->getlayerbyname($temaoverlay);

	$shapesorigem = retornaShapesSelecionados($layerorigem,$this->arquivo,$this->mapa);
	if(count($shapesorigem) == 0){
		return "erro";
	}
	$layeroverlay->set("tolerance",0);
	$layerdestino->set("tolerance",0);
	$layeroverlay->queryByrect($this->mapa->extent);
	$layerdestino->queryByFeatures($layeroverlay->index);
	
	$sopen = $layerdestino->open();
	if($sopen == MS_FAILURE){return "erro";}
	$res_count = $layerdestino->getNumresults();

	for ($i = 0; $i < $res_count; ++$i)
	{
		if($this->v == 6)
		{$shapesdestino[] = $layerdestino->getShape($layerdestino->getResult($i));}
		else{
			$result = $layerdestino->getResult($i);
			$shp_index  = $result->shapeindex;
			$shapesdestino[] = $layerdestino->getshape(-1, $shp_index);		
		}
	}
	$layerdestino->close();
	$rect = $this->mapa->extent;
	$projInObj = $layerorigem->getProjection();
	if ($projInObj == "")
	{$projInObj = ms_newprojectionobj("proj=latlong");}
	$projOutObj = ms_newprojectionobj("proj=poly,ellps=GRS67,lat_0=".$rect->miny.",lon_0=".$rect->minx.",x_0=5000000,y_0=10000000");
	$origemdestino = array();
	if (count($shapesorigem)==0){return "erro";}
	if (count($shapesdestino)==0){return "erro";}
	$novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_ARC);
	// cria o dbf
	$def[] = array("dist_m","N","10","2");
	$def[] = array("origem","C","255");
	$def[] = array("destino","C","255");
	if($this->dbaseExiste == false)
	{$db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);}
	else
	{$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);}
	//acrescenta os pontos no novo shapefile
	$dbname = $nomeshp.".dbf";
	if($this->dbaseExiste == false)
	$db=xbase_open($dbname,2);
	else
	$db=dbase_open($dbname,2);
	foreach ($shapesorigem as $sorigem)
	{
		if($itemorigem != "")
		{$valororigem = $sorigem->values[$itemorigem];}
		else
		{$valororigem = "";}
		foreach ($shapesdestino as $sdestino)
		{
			$linha = ms_newLineObj();
			$linha->add($sorigem->getCentroid());
			$linha->add($sdestino->getCentroid());
			if($itemdestino != "")
			{$valordestino = $sdestino->values[$itemdestino];}
			else
			{$valordestino = "";}
			$ShapeObj = ms_newShapeObj(MS_SHAPE_LINE);
			$ShapeObj->add($linha);
			$novoshpf->addShape($ShapeObj);
			$ShapeObj->project($projInObj, $projOutObj);
			$distancia = $ShapeObj->getLength();
			$registro = array($distancia,$valororigem,$valordestino);
			if($this->dbaseExiste == false)
			xbase_add_record($db,$registro);
			else
			dbase_add_record($db,$registro);
		}
	}
	$novoshpf->free();
	if($this->dbaseExiste == false)
	xbase_close($db);
	else
	dbase_close($db);
	//adiciona no mapa atual o novo tema
	$novolayer = criaLayer($this->mapa,MS_LAYER_LINE,MS_DEFAULT,("Distancias (".$nomefinal.")"),$metaClasse="SIM");
	$novolayer->set("data",$nomeshp.".shp");
	$novolayer->setmetadata("DOWNLOAD","SIM");
	$novolayer->set("template","none.htm");
	$classe = $novolayer->getclass(0);
	$estilo = $classe->getstyle(0);
	$estilo->set("symbolname","linha");
	$estilo->set("size",4);
	$cor = $estilo->color;
	$cor->setrgb(255,210,0);
	//limpa selecao
	if (file_exists($this->qyfile))
	{unlink ($this->qyfile);}
	return($nomeshp.".shp");	
}
/*
Function: criaBuffer

Gera entorno (buffer) nos elementos selecionados de um tema.

Salva o mapa acrescentando um novo layer com o buffer.

Parametros:

$distancia - Distância em metros.

$locaplic - Localização do I3geo.

$unir - sim|nao indica se os elementos selecionados deverão ser unidos em um só antes do buffer ser criado

$wkt - (opcional) elemento no formato wkt para o qual o buffer será gerado. Só de ve ser definido se $this->nome for vazio, ou seja
se o parâmetro "tema" não tiver sido fornecido ao construtor da classe

return:

nome do layer criado com o buffer.
*/
	function criaBuffer($distancia,$locaplic,$unir="nao",$wkt="")
	{
		set_time_limit(180);
		$items = pegaItens($this->layer);
		//error_reporting(E_ALL);
		//para manipular dbf
		if($this->dbaseExiste == false){
			if(file_exists($this->locaplic."/pacotes/phpxbase/api_conversion.php"))
			include_once($this->locaplic."/pacotes/phpxbase/api_conversion.php");
			else	
			include_once "../pacotes/phpxbase/api_conversion.php";
		}
		$nomebuffer = nomeRandomico();
		$nomeshp = $this->diretorio."/".$nomebuffer;

		$listaShapes = array();
		if($this->nome != ""){
			$listaShapes = retornaShapesSelecionados($this->layer,$this->arquivo,$this->mapa);
		}
		else{
			$s = ms_shapeObjFromWkt($wkt);
			$s->values["ID"] = 0;
			$items[] = "ID";
			$listaShapes[] = $s;
		}
		foreach($listaShapes as $shape){
			//calcula a extensão geografica
			$rect = $shape->bounds;
			$projInObj = ms_newprojectionobj("proj=latlong");
			$projOutObj = ms_newprojectionobj("proj=poly,ellps=GRS67,lat_0=".$rect->miny.",lon_0=".$rect->minx.",x_0=5000000,y_0=10000000");
			$poPoint = ms_newpointobj();
			$poPoint->setXY($rect->minx, $rect->miny);
			$dd1 = ms_newpointobj();
			$dd1->setXY($rect->minx, $rect->miny);
			$poPoint->project($projInObj, $projOutObj);
			$dd2 = ms_newpointobj();
			$dd2->setXY(($poPoint->x + $distancia), $poPoint->y);
			$dd2->project($projOutObj,$projInObj);
			$d = $dd1->distanceToPoint($dd2);
			if ($distancia < 0){$d = $d * -1;}
			//calcula a distancia 29100
			//gera o buffer
			$buffers[] = $shape->buffer($d);
			$shapes[] = $shape;
		}
		//faz a união dos elementos se necessário
		if($unir == "sim")
		{
			$ns = $buffers[0];
			for($s=1;$s < count($buffers);$s++)
			{$ns = $ns->union($buffers[$s]);}
			$buffers = array($ns);
			$shapes = array($shapes[0]);
		}		
		//gera o novo arquivo shape file
		// cria o shapefile
		$novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POLYGON);
		// cria o dbf
		$def = $this->criaDefDb($items);
		$def[] = array("i3geo","C","254");
		if($this->dbaseExiste == false)
		{$db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);}
		else
		{$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);}
		//acrescenta os pontos no novo shapefile
		$dbname = $nomeshp.".dbf";
		if($this->dbaseExiste == false)
		$db=xbase_open($dbname,2);
		else
		$db=dbase_open($dbname,2);
		for($i = 0;$i < count($buffers);++$i)
		{
			foreach ($items as $ni)
			{$reg[] = $this->truncaS($shapes[$i]->values[$ni]);}
			$reg[] = $i;
			$novoshpf->addShape($buffers[$i]);
			if($this->dbaseExiste == false)
			xbase_add_record($db,$reg);
			else
			dbase_add_record($db,$reg);
			$reg = array();
		}
		$novoshpf->free();
		if($this->dbaseExiste == false)
		xbase_close($db);
		else
		dbase_close($db);
		//adiciona no mapa atual o novo tema
		$novolayer = criaLayer($this->mapa,MS_LAYER_POLYGON,MS_DEFAULT,("Buffer (".$nomebuffer.")"),$metaClasse="SIM",false);
		$novolayer->set("data",$nomeshp.".shp");
		$novolayer->setmetadata("DOWNLOAD","SIM");
		$novolayer->set("template","none.htm");
		$classe = $novolayer->getclass(0);
		$estilo = $classe->getstyle(0);
		$estilo->set("symbolname","p4");
		$estilo->set("size",5);		
		$cor = $estilo->color;
		$cor->setrgb(255,0,0);
		$coro = $estilo->outlinecolor;
		$coro->setrgb(255,0,0);
		return($novolayer->name);
	}
/*
function: centroMassa

Calcula o centro médio.

Se "item" for diferente de vazio, calcula o centro médio ponderado baseado no item

Parametros:

$item {string} - (opcional) Item q será utilizado para ponderar os valores.
*/
	function centroMassa($item="")
	{
		if(!$this->layer){return "erro";}
		set_time_limit(180);
		//para manipular dbf
		if($this->dbaseExiste == false){
			if(file_exists($this->locaplic."/pacotes/phpxbase/api_conversion.php"))
			include_once($this->locaplic."/pacotes/phpxbase/api_conversion.php");
			else	
			include_once "../pacotes/phpxbase/api_conversion.php";
		}
		error_reporting(E_ALL);
		$nomeCentro = nomeRandomico();
		$nomeshp = $this->diretorio."/".$nomeCentro;
		//pega os shapes selecionados
		$lshapes = retornaShapesSelecionados($this->layer,$this->arquivo,$this->mapa);
		if(count($lshapes) == 0){
			$lshapes = retornaShapesMapext($this->layer,$this->mapa);
		}
		$pondera = 1;
		$xs = 0;
		$ys = 0;
		foreach($lshapes as $shape){
			if($item != "")
			{$pondera = $shape->values[$item];}
			$pt = $shape->line(0)->point(0);
			$xs += ($pt->x * $pondera);
			$ys += ($pt->y * $pondera);
		
		}
		//gera o novo arquivo shape file
		// cria o shapefile
		$novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POINT);
		// cria o dbf
		$def[] = array("id","C","254");
		if($this->dbaseExiste == false)
		{$db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);}
		else
		{$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);}
		//acrescenta os pontos no novo shapefile
		$dbname = $nomeshp.".dbf";
		if($this->dbaseExiste == false)
		$db=xbase_open($dbname,2);
		else
		$db=dbase_open($dbname,2);
		$reg[] = "";
		
		$shp = ms_newShapeObj(MS_SHP_POINT);
		$linha = ms_newLineObj();
		$linha->addXY(($xs / $res_count),($ys / $res_count));
		$shp->add($linha);
		$novoshpf->addShape($shp);
		if($this->dbaseExiste == false)
		xbase_add_record($db,$reg);
		else
		dbase_add_record($db,$reg);
		$novoshpf->free();
		if($this->dbaseExiste == false)
		xbase_close($db);
		else
		dbase_close($db);
		//adiciona no mapa atual o novo tema
		$novolayer = criaLayer($this->mapa,MS_LAYER_POINT,MS_DEFAULT,("Centróide (".$nomeCentro.")"),$metaClasse="SIM");
		$novolayer->set("data",$nomeshp.".shp");
		$novolayer->setmetadata("DOWNLOAD","SIM");
		$novolayer->set("template","none.htm");
		$novolayer->setmetadata("TEMALOCAL","SIM");
		$classe = $novolayer->getclass(0);
		$estilo = $classe->getstyle(0);
		$estilo->set("size","12");
		//limpa selecao
		if (file_exists($this->qyfile))
		{unlink ($this->qyfile);}
		return("ok");
	}
/*
function: criaCentroide

Gera centroide dos elementos selecionados de um tema.

Salva o mapa acrescentando um novo layer com os pontos.

Parametros:

$locaplic - Localização do I3geo.
*/
	function criaCentroide($locaplic)
	{
		if(!$this->layer){return "erro";}
		$items = pegaItens($this->layer);
		set_time_limit(180);
		//para manipular dbf
		if($this->dbaseExiste == false){
			if(file_exists($this->locaplic."/pacotes/phpxbase/api_conversion.php"))
			include_once($this->locaplic."/pacotes/phpxbase/api_conversion.php");
			else	
			include_once "../pacotes/phpxbase/api_conversion.php";
		}
		$nomeCentroides = nomeRandomico();
		$nomeshp = $this->diretorio."/".$nomeCentroides;
		$shapes = retornaShapesSelecionados($this->layer,$this->arquivo,$this->mapa);
		foreach($shapes as $shape){
			$LineObj = ms_newLineObj();
			$LineObj->add($shape->getCentroid());
			$ShapeObj = ms_newShapeObj(MS_SHAPE_POINT);
			$ShapeObj->add($LineObj);
			$centroides[] = $ShapeObj;	
		}
		//gera o novo arquivo shape file
		// cria o shapefile
		$novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POINT);
		// cria o dbf
		$def = $this->criaDefDb($items);
		if($this->dbaseExiste == false)
		{$db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);}
		else
		{$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);}
		//acrescenta os pontos no novo shapefile
		$dbname = $nomeshp.".dbf";
		if($this->dbaseExiste == false)
		$db=xbase_open($dbname,2);
		else
		$db=dbase_open($dbname,2);
		for($i = 0;$i < count($centroides);++$i)
		{
			foreach ($items as $ni)
			{$reg[] = $this->truncaS($shapes[$i]->values[$ni]);}
			$novoshpf->addShape($centroides[$i]);
			if($this->dbaseExiste == false)
			xbase_add_record($db,$reg);
			else
			dbase_add_record($db,$reg);
			$reg = array();
		}
		$novoshpf->free();
		if($this->dbaseExiste == false)
		xbase_close($db);
		else
		dbase_close($db);
		//adiciona no mapa atual o novo tema
		$novolayer = criaLayer($this->mapa,MS_LAYER_POINT,MS_DEFAULT,("Centróide (".$nomeCentroides.")"),$metaClasse="SIM");
		$novolayer->set("data",$nomeshp.".shp");
		$novolayer->setmetadata("DOWNLOAD","SIM");
		$novolayer->set("template","none.htm");
		$novolayer->setmetadata("TEMALOCAL","SIM");
		//limpa selecao
		if (file_exists($this->qyfile))
		{unlink ($this->qyfile);}
		return("ok");
	}
	
/*
function: gradeDePontos

Gera uma grade de pontos com espaçamento regular definido em décimos de grau.

Salva o mapa acrescentando um novo layer com a grade de coordenadas.

$ddx - Espaçamento em x.

$ddy - Espaçamento em y.

$px - X do primeiro ponto (superior esquerdo)

$py - Y do primeiro ponto.

$locaplic - Endereço da aplicação.

$nptx - Número de pontos em X (opcional)

$npty - Número de pontos em Y (opcional)
*/
	function gradeDePontos($xdd,$ydd,$px,$py,$locaplic,$nptx,$npty)
	{
		set_time_limit(180);
		//para manipular dbf
		if($this->dbaseExiste == false){
			if(file_exists($this->locaplic."/pacotes/phpxbase/api_conversion.php"))
			include_once($this->locaplic."/pacotes/phpxbase/api_conversion.php");
			else	
			include_once "../pacotes/phpxbase/api_conversion.php";
		}
		$nomegrade = nomeRandomico();
		$nomeshp = $this->diretorio."/".$nomegrade;
		$this->mapa->preparequery();
		$ext = $this->mapa->extent;
		$fx = $ext->maxx;
		$fy = $ext->miny;
		//calcula a distância entre os pontos em dd
		$distx = $fx - $px;
		$disty = $fy - $py;
		if ($distx < 0){$distx = $distx * -1;}
		if ($disty < 0){$disty = $disty * -1;}
		if ($nptx == "")
		{$nptx = round(($distx / $xdd),0);}
		if ($npty == "")
		{$npty = round(($disty / $ydd),0);}
		// cria o shapefile
		$novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POINT);
		$def = array();
		$def[] = array("x","C","20");
		$def[] = array("y","C","20");
		if($this->dbaseExiste == false)
		{$db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);}
		else
		{$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);}
		//acrescenta os pontos no novo shapefile
		$dbname = $nomeshp.".dbf";
		if($this->dbaseExiste == false)
		$db=xbase_open($dbname,2);
		else
		$db=dbase_open($dbname,2);
		$reg = array();
		$w = $this->mapa->width;
		$h = $this->mapa->height;
		if ($h > $w)
		{
			$valorlinha = $py;
			for ($linha = 0; $linha < $npty; $linha++)
			{
				$y = $valorlinha;
				$valorcoluna = $px;
				for ($coluna = 0; $coluna < $nptx; $coluna++)
				{
					$x = $valorcoluna;
					$valorcoluna = $valorcoluna + $xdd;
					$poPoint = ms_newpointobj();
					$poPoint->setXY($x,$y);
					$novoshpf->addpoint($poPoint);
					$reg[] = $x;
					$reg[] = $y;
					if($this->dbaseExiste == false)
					xbase_add_record($db,$reg);
					else
					dbase_add_record($db,$reg);
					$reg = array();
				}
				$valorlinha = $valorlinha - $ydd;
			}
		}
		else
		{
			$valorcoluna = $px;
			for ($coluna = 0; $coluna < $nptx; $coluna++)
			{
				$x = $valorcoluna;
				$valorlinha = $py;
				for ($linha = 0; $linha < $npty; $linha++)
				{
					$y = $valorlinha;
					$valorlinha = $valorlinha - $ydd;
					$poPoint = ms_newpointobj();
					$poPoint->setXY($x,$y);
					$novoshpf->addpoint($poPoint);
					$reg[] = $x;
					$reg[] = $y;
					if($this->dbaseExiste == false)
					xbase_add_record($db,$reg);
					else
					dbase_add_record($db,$reg);
					$reg = array();
				}
				$valorcoluna = $valorcoluna + $xdd;
			}
		}
		$novoshpf->free();
		if($this->dbaseExiste == false)
		xbase_close($db);
		else
		dbase_close($db);
		//adiciona o novo tema no mapa
		$novolayer = criaLayer($this->mapa,MS_LAYER_POINT,MS_DEFAULT,("Grade (".$nomegrade.")"),$metaClasse="SIM");
		$novolayer->set("data",$nomeshp.".shp");
		$novolayer->setmetadata("DOWNLOAD","SIM");
		$novolayer->setmetadata("TEMALOCAL","SIM");
		if (file_exists($this->qyfile))
		{unlink ($this->qyfile);}
		return("ok");
	}
/*
function: gradeDePol

Gera uma grade de polígonos com espaçamento regular definido em décimos de grau.

Salva o mapa acrescentando um novo layer com a grade.

parameters:

$xdd - Espaçamento em x.

$ydd - Espaçamento em y.

$x - X do primeiro ponto (superior esquerdo)

$y - Y do primeiro ponto.

$locaplic - Endereço da aplicação.

$nptx - Número de pontos em X (opcional)

$npty - Número de pontos em Y (opcional)
*/
	function gradeDePol($xdd,$ydd,$px,$py,$locaplic,$nptx,$npty)
	{
		set_time_limit(180);
		//para manipular dbf
		if($this->dbaseExiste == false){
			if(file_exists($this->locaplic."/pacotes/phpxbase/api_conversion.php"))
			include_once($this->locaplic."/pacotes/phpxbase/api_conversion.php");
			else	
			include_once "../pacotes/phpxbase/api_conversion.php";
		}
		$nomegrade = nomeRandomico();
		$nomeshp = $this->diretorio."/".$nomegrade;
		//pega a extensão geográfica do mapa
		$this->mapa->preparequery();
		$ext = $this->mapa->extent;
		$fx = $ext->maxx;
		$fy = $ext->miny;
		//calcula a distância entre os pontos em dd
		$distx = $fx - $px;
		$disty = $fy - $py;
		if ($distx < 0){$distx = $distx * -1;}
		if ($disty < 0){$disty = $disty * -1;}
		if ($nptx == "")
		{$nptx = round(($distx / $xdd),0);}
		if ($npty == "")
		{$npty = round(($disty / $ydd),0);}
		// cria o shapefile
		$novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POLYGON);
		$def = array();
		$def[] = array("id","C","20");
		if($this->dbaseExiste == false)
		{$db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);}
		else
		{$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);}
		//acrescenta os pontos no novo shapefile
		$dbname = $nomeshp.".dbf";
		if($this->dbaseExiste == false)
		$db=xbase_open($dbname,2);
		else
		$db=dbase_open($dbname,2);
		$reg = array();
		$w = $this->mapa->width;
		$h = $this->mapa->height;
		if ($h > $w)
		{
			$valorlinha = $py;
			for ($linha = 0; $linha < $npty; $linha++)
			{
				$y = $valorlinha;
				$valorcoluna = $px;
				for ($coluna = 0; $coluna < $nptx; $coluna++)
				{
					$x = $valorcoluna;
					$valorcoluna = $valorcoluna + $xdd;
					$poPoint1 = ms_newpointobj();
					$poPoint2 = ms_newpointobj();
					$poPoint3 = ms_newpointobj();
					$poPoint4 = ms_newpointobj();
					$poPoint1->setXY($x,$y);
					$poPoint2->setXY(($x + $xdd),$y);
					$poPoint3->setXY(($x + $xdd),($y - $ydd));
					$poPoint4->setXY($x,($y - $ydd));
					$linhas = ms_newLineObj();
					$linhas->add($poPoint1);
					$linhas->add($poPoint2);
					$linhas->add($poPoint3);
					$linhas->add($poPoint4);
					$linhas->add($poPoint1);
					$shapen = ms_newShapeObj(MS_SHP_POLYGON);
					$shapen->add($linhas);
					$novoshpf->addShape($shapen);
					$reg[] = $linha."-".$coluna;
					if($this->dbaseExiste == false)
					xbase_add_record($db,$reg);
					else
					dbase_add_record($db,$reg);
					$reg = array();
				}
				$valorlinha = $valorlinha - $ydd;
			}
		}
		else
		{
			$valorcoluna = $px;
			for ($coluna = 0; $coluna < $nptx; $coluna++)
			{
				$x = $valorcoluna;
				$valorlinha = $py;
				for ($linha = 0; $linha < $npty; $linha++)
				{
					$y = $valorlinha;
					$valorlinha = $valorlinha - $ydd;
					$poPoint1 = ms_newpointobj();
					$poPoint2 = ms_newpointobj();
					$poPoint3 = ms_newpointobj();
					$poPoint4 = ms_newpointobj();
					$poPoint1->setXY($x,$y);
					$poPoint2->setXY(($x + $xdd),$y);
					$poPoint3->setXY(($x + $xdd),($y - $ydd));
					$poPoint4->setXY($x,($y - $ydd));
					$linhas = ms_newLineObj();
					$linhas->add($poPoint1);
					$linhas->add($poPoint2);
					$linhas->add($poPoint3);
					$linhas->add($poPoint4);
					$linhas->add($poPoint1);
					$shapen = ms_newShapeObj(MS_SHP_POLYGON);
					$shapen->add($linhas);
					$novoshpf->addShape($shapen);
					$reg[] = $linha."-".$coluna;
					if($this->dbaseExiste == false)
					xbase_add_record($db,$reg);
					else
					dbase_add_record($db,$reg);
					$reg = array();
				}
			$valorcoluna = $valorcoluna + $xdd;
			}
		}
		$novoshpf->free();
		if($this->dbaseExiste == false)
		xbase_close($db);
		else
		dbase_close($db);
		//adiciona o novo tema no mapa
		$novolayer = criaLayer($this->mapa,MS_LAYER_POLYGON,MS_DEFAULT,("Grade (".$nomegrade.")"),$metaClasse="SIM");
		$novolayer->set("data",$nomeshp.".shp");
		$novolayer->setmetadata("DOWNLOAD","SIM");
		$novolayer->setmetadata("TEMALOCAL","SIM");
		$novolayer->set("opacity","50");
		if (file_exists($this->qyfile))
		{unlink ($this->qyfile);}
		return("ok");
	}
/*
function: gradeDeHex

Gera uma grade de polígonos hexagonais definido em décimos de grau.

Salva o mapa acrescentando um novo layer com a grade.

parameters:
$xdd - Espaçamento em x.

$ydd - Espaçamento em y.

$px - X do primeiro ponto (superior esquerdo)

$py - Y do primeiro ponto.

$locaplic - Endereço da aplicação.

$nptx - Número de pontos em X (opcional)

$npty - Número de pontos em Y (opcional)
*/
	function gradeDeHex($xdd,$ydd,$px,$py,$locaplic,$nptx,$npty)
	{
		set_time_limit(180);
		//para manipular dbf
		if($this->dbaseExiste == false){
			if(file_exists($this->locaplic."/pacotes/phpxbase/api_conversion.php"))
			include_once($this->locaplic."/pacotes/phpxbase/api_conversion.php");
			else	
			include_once "../pacotes/phpxbase/api_conversion.php";
		}
		$nomegrade = nomeRandomico();
		$nomeshp = $this->diretorio."/".$nomegrade;
		//pega a extensão geográfica do mapa
		$this->mapa->preparequery();
		$ext = $this->mapa->extent;
		$fx = $ext->maxx;
		$fy = $ext->miny;
		//calcula a distância entre os pontos em dd
		$distx = $fx - $px;
		$disty = $fy - $py;
		if ($distx < 0){$distx = $distx * -1;}
		if ($disty < 0){$disty = $disty * -1;}
		if ($nptx == "")
		{$nptx = round(($distx / $xdd),0);}
		if ($npty == "")
		{$npty = round(($disty / $ydd),0);}
		// cria o shapefile
		$novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POLYGON);
		$def = array();
		$def[] = array("id","C","20");
		if($this->dbaseExiste == false)
		{$db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);}
		else
		{$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);}
		//acrescenta os pontos no novo shapefile
		$dbname = $nomeshp.".dbf";
		if($this->dbaseExiste == false)
		$db=xbase_open($dbname,2);
		else
		$db=dbase_open($dbname,2);
		$reg = array();
		$w = $this->mapa->width;
		$h = $this->mapa->height;
		if ($h > $w)
		{
			$valorlinha = $py;
			for ($linha = 0; $linha < $npty; $linha++)
			{
				$y = $valorlinha;
				$valorcoluna = $px;
				for ($coluna = 0; $coluna < $nptx; $coluna++)
				{
					$x = $valorcoluna;
					$valorcoluna = $valorcoluna + $xdd;
					$poPoint1 = ms_newpointobj();
					$poPoint2 = ms_newpointobj();
					$poPoint3 = ms_newpointobj();
					$poPoint4 = ms_newpointobj();
					$poPoint1->setXY($x,$y);
					$poPoint2->setXY(($x + $xdd),$y);
					$poPoint3->setXY(($x + $xdd),($y - $ydd));
					$poPoint4->setXY($x,($y - $ydd));
					$linhas = ms_newLineObj();
					$linhas->add($poPoint1);
					$linhas->add($poPoint2);
					$linhas->add($poPoint3);
					$linhas->add($poPoint4);
					$linhas->add($poPoint1);
					$shapen = ms_newShapeObj(MS_SHP_POLYGON);
					$shapen->add($linhas);
					$novoshpf->addShape($shapen);
					$reg[] = $linha."-".$coluna;
					if($this->dbaseExiste == false)
					xbase_add_record($db,$reg);
					else
					dbase_add_record($db,$reg);
					$reg = array();
				}
				$valorlinha = $valorlinha - $ydd;
			}
		}
		else
		{
			$valorcoluna = $px;
			for ($coluna = 0; $coluna < $nptx; $coluna++)
			{
				$x = $valorcoluna;
				$valorlinha = $py;
				$par = true;
				for ($linha = 0; $linha < $npty; $linha++)
				{
					$y = $valorlinha;
					$valorlinha = $valorlinha - $ydd - ($ydd/2);
					$poPoint1 = ms_newpointobj();
					$poPoint2 = ms_newpointobj();
					$poPoint3 = ms_newpointobj();
					$poPoint4 = ms_newpointobj();
					$poPoint5 = ms_newpointobj();
					$poPoint6 = ms_newpointobj();
					$poPoint1->setXY($x,$y);
					$poPoint2->setXY(($x + ($xdd/2)),$y+($ydd/2));
					$poPoint3->setXY($x + $xdd,$y);
					$poPoint4->setXY($x + $xdd,$y - $ydd);
					$poPoint5->setXY(($x + ($xdd/2)),$y - $ydd - ($ydd/2));
					$poPoint6->setXY($x,$y - $ydd);
					$linhas = ms_newLineObj();
					$linhas->add($poPoint1);
					$linhas->add($poPoint2);
					$linhas->add($poPoint3);
					$linhas->add($poPoint4);
					$linhas->add($poPoint5);
					$linhas->add($poPoint6);
					$linhas->add($poPoint1);
					$shapen = ms_newShapeObj(MS_SHP_POLYGON);
					$shapen->add($linhas);
					$novoshpf->addShape($shapen);
					$reg[] = $linha."-".$coluna;
					if($this->dbaseExiste == false)
					xbase_add_record($db,$reg);
					else
					dbase_add_record($db,$reg);
					$reg = array();
					if ($par)
					{$x=$x+($xdd/2);$par=false;}
					else
					{$x=$x-($xdd/2);$par=true;}
				}
				$valorcoluna = $valorcoluna + $xdd;
			}
		}
		$novoshpf->free();
		if($this->dbaseExiste == false)
		xbase_close($db);
		else
		dbase_close($db);
		//adiciona o novo tema no mapa
		$novolayer = criaLayer($this->mapa,MS_LAYER_POLYGON,MS_DEFAULT,("Grade (".$nomegrade.")"),$metaClasse="SIM");
		$novolayer->set("data",$nomeshp.".shp");
		$novolayer->setmetadata("DOWNLOAD","SIM");
		$novolayer->setmetadata("TEMALOCAL","SIM");
		$novolayer->set("opacity","50");
		if (file_exists($this->qyfile))
		{unlink ($this->qyfile);}
		return("ok");
	}
/*
function: nptPol

Conta o número de pontos em polígono cruzando dois temas.

Salva o mapa acrescentando um novo layer com o resultado.

parameters:
$temaPt - Tema de pontos.

$temaPo - Tema poligonal.

$locaplic - Localização do I3geo
*/
	function nptPol($temaPt,$temaPo,$locaplic)
	{
		//error_reporting(E_ALL);
		set_time_limit(180);
		//para manipular dbf
		if($this->dbaseExiste == false){
			if(file_exists($this->locaplic."/pacotes/phpxbase/api_conversion.php"))
			include_once($this->locaplic."/pacotes/phpxbase/api_conversion.php");
			else	
			include_once "../pacotes/phpxbase/api_conversion.php";
		}
		$layerPt = $this->mapa->getlayerbyname($temaPt);
		$layerPt->set("template","none.htm");
		$layerPt->set("tolerance",0);
		$layerPo = $this->mapa->getlayerbyname($temaPo);
		$layerPo->set("template","none.htm");
		//define o nome do novo shapefile que será criado
		$nomefinal = nomeRandomico();
		$nomeshp = $this->diretorio."/".$nomefinal;
		$itenspo = pegaItens($layerPo);
		$novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POLYGON);
		// cria o dbf
		$def = array();
		foreach ($itenspo as $ni)
		{$def[] = array(substr($ni, 0, 10),"C","254");}
		$def[] = array("npontos","N","10","0");
		if($this->dbaseExiste == false)
		{$db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);}
		else
		{$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);}
		//acrescenta os pontos no novo shapefile
		$dbname = $nomeshp.".dbf";
		if($this->dbaseExiste == false)
		$db=xbase_open($dbname,2);
		else
		$db=dbase_open($dbname,2);	
		$shapes = retornaShapesMapext($layerPo,$this->mapa);
		foreach($shapes as $shape)
		{
			$novoreg = array();
			foreach($itenspo as $ipo)
			{$novoreg[] = $shape->values[$ipo];}
			$layerPt->querybyshape($shape);
			$novoreg[] = $layerPt->getNumresults();
			$novoshpf->addShape($shape);
			if($this->dbaseExiste == false)
			xbase_add_record($db,$novoreg);
			else
			dbase_add_record($db,$novoreg);
		}
		$novoshpf->free();
		if($this->dbaseExiste == false)
		xbase_close($db);
		else
		dbase_close($db);
		//adiciona o novo tema no mapa
		$novolayer = criaLayer($this->mapa,MS_LAYER_POLYGON,MS_DEFAULT,"N pontos",$metaClasse="SIM",false);
		$novolayer->set("data",$nomeshp.".shp");
		$novolayer->setmetadata("DOWNLOAD","SIM");
		$novolayer->setmetadata("TEMALOCAL","SIM");
		$novolayer->set("opacity","80");
		if (file_exists($this->qyfile))
		{unlink ($this->qyfile);}
		return("ok");
	}
/*
Function: agrupaElementos

Agrupa elementos em um polígono.

Salva o mapa acrescentando um novo layer com o resultado.
*/
	function agrupaElementos($item,$locaplic)
	{
		if(!$this->layer){return "erro";}
		set_time_limit(180);
		//para manipular dbf
		if(!isset($item)){$item="";}
		if($this->dbaseExiste == false){
			if(file_exists($this->locaplic."/pacotes/phpxbase/api_conversion.php"))
			include_once($this->locaplic."/pacotes/phpxbase/api_conversion.php");
			else	
			include_once "../pacotes/phpxbase/api_conversion.php";
		}
		$shapes =retornaShapesSelecionados($this->layer,$this->arquivo,$this->mapa);
		$indices = array();
		foreach($shapes as $shape){
			if($item != "")
			{$valor = $shape->values[$item];}
			else
			{$valor = "nenhum";}
			if(!isset($indices[$valor])){
				$indices[$valor] = array($shape);
			}
			else
			$indices[$valor] = array_merge($indices[$valor],array($shape));
		}
		$dissolve=array();
		foreach($indices as $shapes)
		{
			foreach($shapes as $shape){
				if($item != "")
				$valor = $shape->values[$item];
				else
				$valor = "nenhum";
				if (!isset($dissolve[$valor]))
				{$dissolve[$valor] = $shape;}
				else
				{
					$tipo = $shape->type;
					if($tipo==2)
					{
						for($l=0;$l<($shape->numlines);$l++)
						{
							$shape1 = $dissolve[$valor];
							$linha = $shape->line($l);
							$shape1->add($linha);
						}
						$dissolve[$valor] = $shape1;
					}
					else
					{
						$dissolve[$valor] = $shape->union($dissolve[$valor]);
					}
				}
			}
		}
		//
		//cria o novo shapefile
		//
		$nomefinal = nomeRandomico();
		$nomeshp = $this->diretorio."/".$nomefinal;
		$novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POLYGON);
		// cria o dbf
		$def = array();
		if($item==""){$item="nenhum";}
		$def[] = array($item,"C","254");
		if($this->dbaseExiste == false)
		{$db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);}
		else
		{$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);}
		//acrescenta os pontos no novo shapefile
		$dbname = $nomeshp.".dbf";
		if($this->dbaseExiste == false)
		$db=xbase_open($dbname,2);
		else
		$db=dbase_open($dbname,2);
		$classes = array_keys($dissolve);
		foreach ($classes as $classe)
		{
			$novoshpf->addShape($dissolve[$classe]->convexhull());
			if($this->dbaseExiste == false)
			xbase_add_record($db,array($classe));
			else
			dbase_add_record($db,array($classe));
		}
		$novoshpf->free();
		if($this->dbaseExiste == false)
		xbase_close($db);
		else
		dbase_close($db);
		//
		//adiciona o novo layer no mapa
		//	
		$n = pegaNome($this->layer);	
		$novolayer = criaLayer($this->mapa,MS_LAYER_POLYGON,MS_DEFAULT,("Agrupamento de ".$n),$metaClasse="SIM",false);
		$novolayer->set("data",$nomeshp.".shp");
		$novolayer->setmetadata("DOWNLOAD","SIM");
		$novolayer->setmetadata("TEMALOCAL","SIM");
		return("ok");
	}
	
/*
function: dissolvePoligono

Dissolve as bordas entre polígonos com o mesmo atributo.

Salva o mapa acrescentando um novo layer com o resultado.

$item - item utilizado para agregar os polígonos

$locaplic - Localização do I3geo
*/
	function dissolvePoligono($item,$locaplic)
	{
		if(!$this->layer){return "erro";}
		set_time_limit(180);
		//para manipular dbf
		if(!isset($item)){$item="";}
		if($this->dbaseExiste == false){
			if(file_exists($this->locaplic."/pacotes/phpxbase/api_conversion.php"))
			include_once($this->locaplic."/pacotes/phpxbase/api_conversion.php");
			else	
			include_once "../pacotes/phpxbase/api_conversion.php";
		}
		$shapes = retornaShapesSelecionados($this->layer,$this->arquivo,$this->mapa);
		$indices = array();
		foreach($shapes as $shape){
			if($item != "")
			{$valor = $shape->values[$item];}
			else
			{$valor = "nenhum";}
			if(!isset($indices[$valor])){
				$indices[$valor] = array($shape);
			}
			else
			$indices[$valor] = array_merge($indices[$valor],array($shape));
		}
		$dissolve=array();
		foreach($indices as $shapes)
		{
			foreach($shapes as $shape){
				if($item != "")
				$valor = $shape->values[$item];
				else
				$valor = "nenhum";
				if (!isset($dissolve[$valor]))
				{$dissolve[$valor] = $shape;}
				else
				{
					if($shape->type != MS_SHAPE_POLYGON)
					{
						for($l=0;$l<($shape->numlines);$l++)
						{
							$shape1 = $dissolve[$valor];
							$linha = $shape->line($l);
							$shape1->add($linha);
						}
						$dissolve[$valor] = $shape1;
					}
					else
					{
						$dissolve[$valor] = $shape->union($dissolve[$valor]);
					}
				}
			}
		}
		//
		//cria o novo shapefile
		//
		$nomefinal = nomeRandomico();
		$nomeshp = $this->diretorio."/".$nomefinal;
		$novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POLYGON);
		// cria o dbf
		$def = array();
		if($item==""){$item="nenhum";}
		$def[] = array($item,"C","254");
		if($this->dbaseExiste == false)
		{$db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);}
		else
		{$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);}
		//acrescenta os pontos no novo shapefile
		$dbname = $nomeshp.".dbf";
		if($this->dbaseExiste == false)
		$db=xbase_open($dbname,2);
		else
		$db=dbase_open($dbname,2);
		$classes = array_keys($dissolve);
		foreach ($classes as $classe)
		{
			$novoshpf->addShape($dissolve[$classe]);
			if($this->dbaseExiste == false)
			xbase_add_record($db,array($classe));
			else
			dbase_add_record($db,array($classe));
		}
		$novoshpf->free();
		if($this->dbaseExiste == false)
		xbase_close($db);
		else
		dbase_close($db);
		//
		//adiciona o novo layer no mapa
		//	
		$n = pegaNome($this->layer);	
		$novolayer = criaLayer($this->mapa,MS_LAYER_POLYGON,MS_DEFAULT,("Dissolve de ".$n),$metaClasse="SIM");
		$novolayer->set("data",$nomeshp.".shp");
		$novolayer->setmetadata("DOWNLOAD","SIM");
		$novolayer->setmetadata("TEMALOCAL","SIM");
		if (file_exists($this->qyfile))
		{unlink ($this->qyfile);}

		return("ok");
	}
	/*
	Function aplicaFuncaoListaWKT
	
	Aplica uma função do Mapserver à uma lista de geometrias no formato WKT
	
	Parametros:
	
	$geometrias {Array} - lista de WKT
	
	$operacao {String} - operação suportada pelo Mapserver, por exemplo, union, intersects, etc. converteSHP irá converter as geometrias em um tema e adicioná-lo ao mapa

	$dir_tmp - Diretório temporário do mapserver. Utilizado apenas se $operacao = "converteSHP"

	$imgdir - Diretório das imagens do mapa atual. Utilizado apenas se $operacao = "converteSHP"
	
	Return:
	
	{string wkt}
	*/
	function aplicaFuncaoListaWKT($geometrias,$operacao,$dir_tmp="",$imgdir=""){
		if($operacao === "converteSHP"){
			$this->incmapageometrias($dir_tmp,$imgdir,$geometrias,$tipoLista="arraywkt");
			return "ok";
		}
		$geos = array();
		foreach ($geometrias as $geo){
			$geos[] = ms_shapeObjFromWkt($geo);
		}
		$n = count($geos);
		if ($n == 1)
		{
			eval("\$nShape = \$geos[0]->".$operacao."();");
			return $nShape->toWkt();
		}		
		if ($n == 2)
		{
			eval("\$nShape = \$geos[0]->".$operacao."(\$geos[1]);");
			return $nShape->toWkt();
		}
		if ($n > 2)
		{
			$geoc = $geos[0];
			for($i=1;$i<$n;++$i)
			{
				eval("\$geoc = \$geoc->".$operacao."(\$geos[\$i]);");
			}
			return $geoc->toWkt();
		}
	}
/*
function: funcoesGeometrias

Funções de análise de geometrias da ferramenta Geometrias.

parameters:
$dir_tmp - Diretório temporário do mapserver

$imgdir - Diretório das imagens do mapa atual

$lista - String com a lista de nomes dos arquivos serializados que contém as geometrias

$operacao - Tipo de análise.
*/
	function funcoesGeometrias($dir_tmp,$imgdir,$lista,$operacao)
	{
		$lista = explode(",",$lista);
		$dir = $dir_tmp."/".$imgdir."/";
		$geometrias = array();
		$valoresoriginais = array();
		$calculo = array();
		foreach ($lista as $l)
		{
			$geos = $this->unserializeGeo($dir.$l);
			foreach ($geos["dados"] as $geo)
			{
				$geometrias[] = $geo["wkt"];
				$valoresoriginais = array_merge($valoresoriginais,$geo["valores"]);
			}
		}	
		$calculo[]["gwkt"] = $this->aplicaFuncaoListaWKT($geometrias,$operacao);
		$nomegeo = "";
		if (count($calculo)>0)
		{
			$final["layer"] = $operacao." ".(implode(" ",$lista));
			$final["dados"][] = array("id"=>"0","wkt"=>($calculo[0]["gwkt"]),"valores"=>$valoresoriginais,"imagem"=>"");
			$nomegeo = $dir.(nomerandomico(10))."keo";
			$this->serializeGeo($nomegeo,$final);
			$ext = $this->mapa->extent;
			$minx = $ext->minx;
			$miny = $ext->miny;
			$maxx = $ext->maxx;
			$maxy = $ext->maxy;
			$h = $this->mapa->height;
			$w = $this->mapa->width;
			$nomelayer = $this->incmapageometrias($dir_tmp,$imgdir,basename($nomegeo));
			if ($nomelayer != "erro")
			{
				
				$nlayer = $this->mapa->getlayerbyname($nomelayer);
				$bounds = $nlayer->getExtent();
				$this->mapa->setsize(30,30);
				$sb = $this->mapa->scalebar;
				$statusoriginal = $sb->status;
				$sb->set("status",MS_OFF);
				$ext->setextent(($bounds->minx),($bounds->miny),($bounds->maxx),($bounds->maxy));
	 			$imagem = gravaImagemMapa($this->mapa);
				$this->mapa->setsize($w,$h);
				$ext->setextent($minx,$miny,$maxx,$maxy);			
				$nlayer->set("status",MS_DELETE);
				$sb->set("status",$statusoriginal);
				$this->salva();
				$final = array();
				$final["layer"] = $operacao." ".(implode(" ",$lista));
				$final["dados"][] = array("id"=>"0","wkt"=>($calculo[0]["gwkt"]),"valores"=>$valoresoriginais,"imagem"=>($imagem["url"]));
				$this->serializeGeo($nomegeo,$final);
			}
		}
		return($nomegeo);	
	}
	
/*
function: calculaGeometrias

Funções de cálculo de geometrias da ferramenta Geometrias.

parameters:

$dir_tmp - Diretório temporário do mapserver

$imgdir - Diretório das imagens do mapa atual

$lista - Arquivos com as geometrias

$operacao - Tipo de análise.
*/
	function calculaGeometrias($dir_tmp,$imgdir,$lista,$operacao)
	{
		//error_reporting(E_ALL);
		$lista = explode(",",$lista);
		$dir = $dir_tmp."/".$imgdir."/";
		foreach ($lista as $l)
		{
			$geos = $this->unserializeGeo($dir.$l);
			//
			//verifica a versão do mapserver
			//se for anterior a 5, utiliza a conexão com o postgis para fazer o processamento dos daods
			//
            $v = versao();
			if (($v["principal"] != 5))
			{return ("erro. E necessario uma versão maior que 5.0 do Mapserver.");}
			foreach ($geos["dados"] as &$geo)
			{
				$g = $geo["wkt"];
				switch ($operacao)
				{
					case "perimetro":
						$shape = ms_shapeObjFromWkt($g);
						$rect = $shape->bounds;
						$projInObj = ms_newprojectionobj("proj=latlong");
						$projOutObj = ms_newprojectionobj("proj=poly,ellps=GRS67,lat_0=".$rect->miny.",lon_0=".$rect->minx.",x_0=5000000,y_0=10000000,units=m");
						$shape->project($projInObj, $projOutObj);
						$s = $shape->towkt();
						$shape = ms_shapeObjFromWkt($s);
						$area = $shape->getLength();
						$geo["valores"][] = array("item"=>"P_perim_metros","valor"=>$area);
					break;
					case "area":
						$shape = ms_shapeObjFromWkt($g);
						$rect = $shape->bounds;
						$projInObj = ms_newprojectionobj("proj=latlong");
						$projOutObj = ms_newprojectionobj("proj=laea,lat_0=".$rect->miny.",lon_0=".$rect->minx.",x_0=500000,y_0=10000000,ellps=GRS67,units=m,no_defs");					
						$shape->project($projInObj, $projOutObj);
						$s = $shape->towkt();
						$shape = ms_shapeObjFromWkt($s);
						$area = $shape->getArea();
						$geo["valores"][] = array("item"=>"P_area_metros","valor"=>$area);
					break;
					case "comprimento":
					break;
				}
			}
			$this->serializeGeo($dir.$l,$geos);
		}
		return("ok");	
	}
/*
Function: incmapageometrias

Insere geometrias como tema no mapa.

parameters:

$dir_tmp - Diretório temporário do mapserver

$imgdir - Diretório das imagens do mapa atual

$lista - Nomes, sem o caminho, dos arquivos com as geometrias, separados por vírgula.

$tipoLista - tipo de valores que são passados em $lista stringArquivos|arraywkt. O default é stringArquivos
*/
	function incmapageometrias($dir_tmp,$imgdir,$lista,$tipoLista="stringArquivos")
	{
		$dir = $dir_tmp."/".$imgdir."/";
		if($tipoLista == "stringArquivos"){
			$lista = explode(",",$lista);
			$shapes = array();
			$valoresoriginais = array();
			foreach ($lista as $l)
			{
				$geos = $this->unserializeGeo($dir.$l);
				//pega todas as geometrias
				foreach ($geos["dados"] as $geo)
				{
					//echo $geo["wkt"]."<br>";
					$shapes[] = ms_shapeObjFromWkt(str_replace("'","",$geo["wkt"]));
					foreach ($geo["valores"] as $v)
					{$valorestemp[] = $v["item"]."=".$v["valor"];}
					$valoresoriginais[] = implode(" ",$valorestemp);
				}
			}
		}
		if($tipoLista == "arraywkt"){
			$shapes = array();
			$valoresoriginais = array();
			foreach ($lista as $l){
				$shapes[] = ms_shapeObjFromWkt($l);
			}			
		}
		//verifica o tipo
		if (count($shapes) == 0){return("erro.");}
		$tiposhape = $shapes[0]->type;
		$tiposhapefile = MS_SHP_POLYGON;
		if ($tiposhape == 0){$tiposhapefile = MS_SHP_MULTIPOINT;}
		if ($tiposhape == 1){$tiposhapefile = MS_SHP_ARC;}
		//cria o shapefile
		if($this->dbaseExiste == false){
			if(file_exists($this->locaplic."/pacotes/phpxbase/api_conversion.php"))
			include_once($this->locaplic."/pacotes/phpxbase/api_conversion.php");
			else	
			include_once "../pacotes/phpxbase/api_conversion.php";
		}
		$diretorio = dirname($this->arquivo);
		$novonomelayer = nomeRandomico();
		$nomeshp = $diretorio."/".$novonomelayer;
		$l = criaLayer($this->mapa,$tiposhape,MS_DEFAULT,"Ins","SIM");
		$novoshpf = ms_newShapefileObj($nomeshp, $tiposhapefile);
		$def[] = array("ID","C","250");
		if($this->dbaseExiste == false)
		{$db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);}
		else
		{$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);}
		//acrescenta os pontos no novo shapefile
		$dbname = $nomeshp.".dbf";
		if($this->dbaseExiste == false)
		$db=xbase_open($dbname,2);
		else
		$db=dbase_open($dbname,2);
		$conta = 0;
		foreach ($shapes as $s)
		{
			$reg = array();
			$reg[] = $valoresoriginais[$conta];
			if($this->dbaseExiste == false)
			xbase_add_record($db,$reg);
			else
			dbase_add_record($db,$reg);
			$novoshpf->addshape($s);
			$conta = $conta + 1;
		}
		if($this->dbaseExiste == false)
		xbase_close($db);
		else
		dbase_close($db);
		$novoshpf->free();
		$l->setmetadata("tema",$novonomelayer." geometria");
		$l->setmetadata("TEMALOCAL","SIM");
		$l->setmetadata("DOWNLOAD","sim");
		$l->set("data",$nomeshp);
		$l->set("name",$novonomelayer);
		$classe = $l->getclass(0);
		$estilo = $classe->getstyle(0);
		if ($tiposhape == 0)
		{
			$estilo->set("symbolname","ponto");
			$estilo->set("size",6);
		}
		$cor = $estilo->color;
		$cor->setrgb(255,210,0);
		$cor = $estilo->outlinecolor;
		$cor->setrgb(255,0,0);
		$this->salva();
		return($novonomelayer);
	}
/*
function: gravaCoordenadasPt

Lê as coordenadas de um tema pontual e grava em arquivos.

Essa função é utilizada nas opções que utilizam o R para cálculos e necessitam ler as coordenadas dos pontos.

Parametros:

tema - nome do tema com os pontos

limitepontos - FALSE para considerar a extensão geográfica do mapa atual e TRUE para considerar como limite as ocorrências pontuais do tema

extendelimite - percentual utilizado para extender o limite da área resultante

return:

array com as dimensões em x e y e nome dos arquivos com x e y gerados.
*/
function gravaCoordenadasPt($tema,$limitepontos="TRUE",$extendelimite)
{
		$prjMapa = $this->mapa->getProjection();
		$layerPt = $this->mapa->getlayerbyname($tema);
		$prjTema = $layerPt->getProjection();
		$layerPt->set("tolerance",0);
		$layerPt->set("template","none.htm");
		$nomefinal = nomeRandomico();
		$nomearq = $this->diretorio."/".$nomefinal;
		$itemspt = pegaItens($layerPt);
		$shapes = retornaShapesSelecionados($layerPt,$this->arquivo,$this->mapa);
		if(count($shapes) == 0){
			$shapes = retornaShapesMapext($layerPt,$this->mapa);
		}
		$pontos = array();
		if (($prjTema != "") && ($prjMapa != $prjTema))
		{
			$projInObj = ms_newprojectionobj($prjTema);
			$projOutObj = ms_newprojectionobj($prjMapa);		
		}
		foreach($shapes as $shape)
		{
			$pt = $shape->getCentroid();
			if (($prjTema != "") && ($prjMapa != $prjTema))
			{
				$pt->project($projInObj, $projOutObj);
			}		
			$pontos[] = $pt->x."  ".$pt->y."\n";
			$pontosx[] = $pt->x;
			$pontosy[] = $pt->y;
		}
		$layerPt->close();
		//grava o arquivo com os pontos em x
		$f = fopen($nomearq."x","w");
		foreach ($pontosx as $pt)
		{fwrite($f,$pt."\n");}
		fclose($f);
		//grava o arquivo com os pontos em y
		$f = fopen($nomearq."y","w");
		foreach ($pontosy as $pt)
		{fwrite($f,$pt."\n");}
		fclose($f);
		if ($limitepontos == "TRUE")
		{
			$xi = (min($pontosx));
			$xf = (max($pontosx));
			$yi = (min($pontosy));
			$yf = (max($pontosy));
		}
		else
		{
			$ext = $this->mapa->extent;
			$xi = $ext->minx;
			$xf = $ext->maxx;
			$yi = $ext->miny;
			$yf = $ext->maxy;
		}
		if($extendelimite > 0)
		{
			$dx = $xf - $xi;
			$dy = $yf - $yi;
			$maisx = ($dx * $extendelimite) / 100;
			$maisy = ($dy * $extendelimite) / 100;
			$xi = $xi - $maisx;
			$xf = $xf + $maisx;
			$yi = $yi - $maisy;
			$yf = $yf + $maisy;
		}
		$dimx = "c(".$xi.",".$xf.")";
		$dimy = "c(".$yi.",".$yf.")";
		return array("dimx"=>$dimx,"dimy"=>$dimy,"arqx"=>($nomearq."x"),"arqy"=>($nomearq."y"),"prefixoarquivo"=>$nomearq);
}
/*
function unserializeGeo

Deserializa um arquivo de geometrias.

Parametros:
$arquivo - arquivo que será processado
*/ 	 	
	public function unserializeGeo($arq)
	{
		$handle = fopen ($arq, "r");
		$conteudo = fread ($handle, filesize ($arq));
		fclose ($handle);
		return(unserialize($conteudo));
	}
/*
function serializeGeo

Deserializa um arquivo de geometrias.

Parametros:
$arquivo - arquivo que será processado

$geos - array com os dados
*/ 	 	
	public function serializeGeo($arq,$geos)
	{
		if (file_exists($arq))
		{unlink($arq);}
		$fp = fopen($arq,"w");
		$r = serialize($geos);
		fwrite($fp,$r);
		fclose($fp);
	}
}
?>