diff --git a/admin/admin.db b/admin/admin.db index 6b76370..874ea64 100644 Binary files a/admin/admin.db and b/admin/admin.db differ diff --git a/admin/js/estat_variavel.js b/admin/js/estat_variavel.js index 126f86f..9d87b18 100755 --- a/admin/js/estat_variavel.js +++ b/admin/js/estat_variavel.js @@ -426,19 +426,21 @@ i3GEOadmin.variaveis = { if(redesenha){tree.draw();} }, classesAuto: function(id_classificacao,id_medida_variavel){ - core_montaEditor("","450px","200px","","Criar classes"); - var ins = "
Utilize um dos métodos abaixo para gerar as classes que serão utilizadas para representar os dados no cartograma
" + - " " + - "Número de intervalos de classes:
" + + " " + + "Utilize um dos métodos abaixo para gerar as classes que serão utilizadas para representar os dados no cartograma
" + + " " + + " " + + " " + + ''; //utilizado pelo seletor de colourramp; $i("editor_bd").innerHTML = ins; new YAHOO.widget.Button( "i3GEOFmetaestatEditorBotao8", {onclick:{fn: function(){ - i3GEO.util.abreColourRamp("","listaColourRampEditor",5); + i3GEO.util.abreColourRamp("","listaColourRampEditor",$i("i3GEOFmetaestatEditorNumInt").value); } }} ); @@ -476,7 +478,36 @@ i3GEOadmin.variaveis = { {onclick:{fn: function(){ var cores = $i("listaColourRampEditor").value, - p = i3GEO.configura.locaplic+"/admin/php/metaestat.php?funcao=calculaClassificacao&tipo=intiguais5&cores="+cores+"&id_classificacao="+id_classificacao+"&id_medida_variavel="+id_medida_variavel, + p = i3GEO.configura.locaplic+"/admin/php/metaestat.php?funcao=calculaClassificacao&tipo=intiguais&cores="+cores+"&id_classificacao="+id_classificacao+"&id_medida_variavel="+id_medida_variavel+"&numintervalos="+$i("i3GEOFmetaestatEditorNumInt").value, + callback; + if(cores == ""){ + alert("Escolha as cores primeiro"); + return; + } + callback = { + success:function(o){ + try { + core_carregando("desativa"); + var no = tree.getNodeByProperty("id_classificacao",id_classificacao); + tree.removeChildren(no) ; + no.expand(); + } + catch(e){core_handleFailure(e,o.responseText);} + }, + failure:core_handleFailure, + argument: { foo:"foo", bar:"bar" } + }; + core_carregando("ativa"); + core_makeRequest(p,callback); + } + }} + ); + new YAHOO.widget.Button( + "i3GEOFmetaestatEditorBotaoQN", + {onclick:{fn: + function(){ + var cores = $i("listaColourRampEditor").value, + p = i3GEO.configura.locaplic+"/admin/php/metaestat.php?funcao=calculaClassificacao&tipo=quebrasnaturais&cores="+cores+"&id_classificacao="+id_classificacao+"&id_medida_variavel="+id_medida_variavel+"&numintervalos="+$i("i3GEOFmetaestatEditorNumInt").value, callback; if(cores == ""){ alert("Escolha as cores primeiro"); diff --git a/admin/php/classe_metaestat.php b/admin/php/classe_metaestat.php index aad08c6..0d03251 100755 --- a/admin/php/classe_metaestat.php +++ b/admin/php/classe_metaestat.php @@ -425,7 +425,10 @@ class Metaestat{ $sqlDadosMedidaVariavel = "SELECT $sqlWMST as dimtempo,".$dados["colunaidgeo"]." AS cod_regiao,".$dados["colunavalor"]." AS valorcalculado FROM ".$dados["esquemadb"].".".$dados["tabela"]; } if(!empty ($filtro)){ - $sqlDadosMedidaVariavel .= " WHERE ".$filtro; + $sqlDadosMedidaVariavel .= " WHERE ".$filtro . "AND ".$dados["colunavalor"]." IS NOT NULL "; + } + else{ + $sqlDadosMedidaVariavel .= " WHERE ".$dados["colunavalor"]." IS NOT NULL "; } if($suportaWMST != true){ $sqlDadosMedidaVariavel .= " /*FA*//*FA*/ /*FAT*//*FAT*/ GROUP BY cod_regiao "; diff --git a/admin/php/metaestat.php b/admin/php/metaestat.php index 65014c2..dad8af1 100644 --- a/admin/php/metaestat.php +++ b/admin/php/metaestat.php @@ -499,6 +499,42 @@ switch (strtoupper($funcao)) if(empty($limite)){ $limite = 10000; } + if($tipo == "quebrasnaturais"){ + $m = new Metaestat(); + $dados = $m->dadosMedidaVariavel($id_medida_variavel,"",0,"",$limite); + $metaVariavel = $m->listaMedidaVariavel("",$id_medida_variavel); + $colunavalor = $metaVariavel["colunavalor"]; + $valores = array(); + + foreach($dados as $d){ + if($d[$colunavalor]){ + $valores[] = $d[$colunavalor]; + } + } + include(dirname(__FILE__)."/../../pacotes/jenks-master/jenks.php"); + $intervalos = getJenksClasses($numintervalos, $valores); + $m->excluirRegistro("i3geoestat_classes","id_classificacao",$id_classificacao); + for ($i=0; $i < $numintervalos; ++$i){ + if ($i == $numintervalos - 1){ + $expressao = "(([".$colunavalor."]>=".$intervalos[$i].")"; + $titulo = ">= ".$intervalos[$i]; + } + else{ + $expressao = "(([".$colunavalor."]>=".$intervalos[$i].")and([".$colunavalor."]<".$intervalos[$i+1]."))"; + $titulo = ">= ".$intervalos[$i]." e < que ".($intervalos[$i+1]); + } + $id_classe = $m->alteraClasseClassificacao($id_classificacao); + if(!empty($cores)){ + $cor = explode(",",$cores[$i]); + $vermelho = $cor[0]; + $verde = $cor[1]; + $azul = $cor[2]; + } + $m->alteraClasseClassificacao("",$id_classe,$titulo,$expressao,$vermelho,$verde,$azul,"","","255","255","255","2"); + } + retornaJSON("ok"); + exit; + } if($tipo == "quartil"){ $m = new Metaestat(); $dados = $m->sumarioMedidaVariavel($id_medida_variavel,"","",$limite); @@ -521,8 +557,14 @@ switch (strtoupper($funcao)) } $m->alteraClasseClassificacao("",$id_classe,$titulo,$expressao,$vermelho,$verde,$azul,"","","255","255","255","2"); } + retornaJSON("ok"); + exit; + } + //para efeitos de compatibilidade com o nome de $tipo + if(empty($numintervalos) || $tipo == "intiguais5"){ + $numintervalos = 5; } - if($tipo == "intiguais5"){ + if($tipo == "intiguais5" || $tipo == "intiguais"){ $m = new Metaestat(); $dados = $m->sumarioMedidaVariavel($id_medida_variavel,"","",$limite); if($dados == false){ @@ -532,12 +574,12 @@ switch (strtoupper($funcao)) $min = $dados["menor"]; $max = $dados["maior"]; $item = $dados["colunavalor"]; - $intervalo = ($max - $min) / 5; + $intervalo = ($max - $min) / $numintervalos; //adiciona as classes novas $intatual = $min; $m->excluirRegistro("i3geoestat_classes","id_classificacao",$id_classificacao); - for ($i=0; $i < 5; ++$i){ - if ($i == 5 - 1){ + for ($i=0; $i < $numintervalos; ++$i){ + if ($i == $numintervalos - 1){ $expressao = "(([".$item."]>=".$intatual.")and([".$item."]<=".($intatual+$intervalo)."))"; } else{ @@ -554,18 +596,24 @@ switch (strtoupper($funcao)) } $m->alteraClasseClassificacao("",$id_classe,$titulo,$expressao,$vermelho,$verde,$azul,"","","255","255","255","2"); } + retornaJSON("ok"); + exit; } //o menor e o maior valor sao enviados como parametro ($min e $max) - if($tipo == "intiguais5mm"){ + //para efeitos de compatibilidade com o nome de $tipo + if(empty($numintervalos) || $tipo == "intiguais5mm"){ + $numintervalos = 5; + } + if($tipo == "intiguais5mm" || $tipo == "intiguaismm"){ $m = new Metaestat(); $metaVariavel = $m->listaMedidaVariavel("",$id_medida_variavel); $item = $metaVariavel["colunavalor"]; - $intervalo = ($max - $min) / 5; + $intervalo = ($max - $min) / $numintervalos; //adiciona as classes novas $intatual = $min; $m->excluirRegistro("i3geoestat_classes","id_classificacao",$id_classificacao); - for ($i=0; $i < 5; ++$i){ - if ($i == 5 - 1){ + for ($i=0; $i < $numintervalos; ++$i){ + if ($i == $numintervalos - 1){ $expressao = "(([".$item."]>=".$intatual.")and([".$item."]<=".($intatual+$intervalo)."))"; } else{ @@ -581,9 +629,11 @@ switch (strtoupper($funcao)) $azul = $cor[2]; } $m->alteraClasseClassificacao("",$id_classe,$titulo,$expressao,$vermelho,$verde,$azul,"","","255","255","255","2"); - } + } + retornaJSON("ok"); + exit; } - retornaJSON("ok"); + retornaJSON("ok"); exit; break; /* diff --git a/classesphp/classe_alteraclasse.php b/classesphp/classe_alteraclasse.php index 13bc89e..b7cf528 100644 --- a/classesphp/classe_alteraclasse.php +++ b/classesphp/classe_alteraclasse.php @@ -97,8 +97,8 @@ function: salva Salva o mapfile atual */ - function salva() - { + function salva() + { if (connection_aborted()){exit();} $this->mapa->save($this->arquivo); } @@ -286,7 +286,7 @@ $ignorar - valor que será ignorado na listagem final {return ("erro. Nenhum valor numerico no item");} } /* - function: quantil + function: quantil Cria classes em um objeto layer com intervalos baseados no calculo de quantil @@ -355,6 +355,69 @@ $ignorar - valor que será ignorado na listagem final return ("erro. Nenhum valor numerico no item"); } } + /* + function: quebrasnaturais + + Cria classes em um objeto layer com intervalos baseados no calculo de quebras naturais + + Parametros: + + $item - item da tabela de atributos + + $nclasses - número de classes + + $ignorar - valor que será ignorado na listagem final + */ + function quebrasnaturais($item,$nclasses,$ignorar) + { + if(!$this->layer){return "erro";} + $valores = $this->pegaValores($this->mapa,$this->layer,$item,true,$ignorar); + if (count($valores) > 0){ + include(dirname(__FILE__)."/../pacotes/jenks-master/jenks.php"); + $classBreaks = getJenksClasses($nclasses, $valores); + //echo "";var_dump($classBreaks);exit; + $numclassesatual = $this->layer->numclasses; + //apaga todas as classes existentes + $classetemp = $this->layer->getClass(0); + $estilotemp = $classetemp->getStyle(0); + for ($i=0; $i < $numclassesatual; ++$i){ + $classe = $this->layer->getClass($i); + $classe->set("status",MS_DELETE); + } + //adiciona as classes novas + for ($i=0; $i < $nclasses; ++$i){ + $expressao = "(([".$item."]>".$classBreaks[$i].")and([".$item."]<=".$classBreaks[$i + 1]."))"; + $nomeclasse = "> ".$classBreaks[$i]." e <= que ".($classBreaks[$i + 1]); + if($i == 0){ + $expressao = "([".$item."]<=".$classBreaks[$i + 1].")"; + $nomeclasse = "<= que ".($classBreaks[$i + 1]); + } + if($i == ($nclasses - 1)){ + $expressao = "([".$item."] >=".$classBreaks[$i].")"; + $nomeclasse = ">= que ".($classBreaks[$i]); + } + $classe = ms_newClassObj($this->layer); + $novoestilo = ms_newStyleObj($classe); + if ($this->layer->type == 0){ + $novoestilo->set("symbolname","ponto"); + $novoestilo->set("size","6"); + } + $ncor = $novoestilo->color; + $ncor->setrgb((mt_rand(0,255)),(mt_rand(0,255)),(mt_rand(0,255))); + $ncor = $novoestilo->outlinecolor; + $ncor->setrgb(255,255,255); + $classe->setexpression($expressao); + $classe->set("name",$nomeclasse); + //$classe->set("title",($this->layer->name)."+".$i); + } + $this->layer->setMetaData("cache",""); + return ("ok"); + } + else{ + return ("erro. Nenhum valor numerico no item"); + } + } + /* function: quartis @@ -378,10 +441,10 @@ Include: $valores = $this->pegaValores($this->mapa,$this->layer,$item,true,$ignorar); if (count($valores) > 0) { - if(file_exists($this->locaplic."/classe_estatistica.php")) - include_once($this->locaplic."/classe_estatistica.php"); - else - include_once("classe_estatistica.php"); + if(file_exists($this->locaplic."/classe_estatistica.php")) + include_once($this->locaplic."/classe_estatistica.php"); + else + include_once("classe_estatistica.php"); $estat = new estatistica(); $estat->calcula($valores); $calc = $estat->resultado; diff --git a/classesphp/mapa_controle.php b/classesphp/mapa_controle.php index 874e959..cfd0558 100644 --- a/classesphp/mapa_controle.php +++ b/classesphp/mapa_controle.php @@ -1114,6 +1114,8 @@ Altera uma classe de um tema, aplicando uma nova classificação ou {$retorno = $m->intervalosiguais($item,$nclasses,$ignorar);} if ($opcao == "quantil") {$retorno = $m->quantil($item,$nclasses,$ignorar);} + if ($opcao == "quebrasnaturais") + {$retorno = $m->quebrasnaturais($item,$nclasses,$ignorar);} if ($opcao == "quartis") { if(!isset($tipoLegenda)) diff --git a/ferramentas/legenda/dicionario.js b/ferramentas/legenda/dicionario.js index 437cfa9..7efa748 100644 --- a/ferramentas/legenda/dicionario.js +++ b/ferramentas/legenda/dicionario.js @@ -563,5 +563,11 @@ i3GEOF.legenda.dicionario = { en:"", es:"", it:"" + }], + 95: [{ + pt:"Quebras naturais", + en:"", + es:"", + it:"" }] }; \ No newline at end of file diff --git a/ferramentas/legenda/index.js b/ferramentas/legenda/index.js index 352ebb5..983dd4e 100644 --- a/ferramentas/legenda/index.js +++ b/ferramentas/legenda/index.js @@ -211,23 +211,30 @@ i3GEOF.legenda = { {onclick:{fn: i3GEOF.legenda.representacao}} ); $i("i3GEOlegendabotao7-button").style.width = "200px"; + new YAHOO.widget.Button( "i3GEOlegendabotao8", {onclick:{fn: i3GEOF.legenda.valorC}} ); - $i("i3GEOlegendabotao8-button").style.width = "200px"; + $i("i3GEOlegendabotao8-button").style.width = "120px"; new YAHOO.widget.Button( "i3GEOlegendabotao9", {onclick:{fn: i3GEOF.legenda.valorQ}} ); - $i("i3GEOlegendabotao9-button").style.width = "200px"; + $i("i3GEOlegendabotao9-button").style.width = "120px"; new YAHOO.widget.Button( "i3GEOlegendabotaoQuantil", {onclick:{fn: i3GEOF.legenda.valorQu}} ); - $i("i3GEOlegendabotaoQuantil-button").style.width = "200px"; + $i("i3GEOlegendabotaoQuantil-button").style.width = "120px"; + + new YAHOO.widget.Button( + "i3GEOlegendabotaoQN", + {onclick:{fn: i3GEOF.legenda.valorQN}} + ); + $i("i3GEOlegendabotaoQN-button").style.width = "120px"; new YAHOO.widget.Button( "i3GEOlegendabotao10", @@ -235,6 +242,7 @@ i3GEOF.legenda = { ); if(navm) {$i("i3GEOlegendabotao10-button").style.width = "0px";} + new YAHOO.widget.Button( "i3GEOlegendabotao17", {onclick:{fn: i3GEOF.legenda.alteraGeometriaTema}} @@ -401,6 +409,7 @@ i3GEOF.legenda = { ''+$trad(40,i3GEOF.legenda.dicionario)+':'+ $inputText("","","i3GEOlegendanclasses","",3,"5") + '
'+ + ' '+ ' '+ '
'+$trad(42,i3GEOF.legenda.dicionario)+'
'+ ''+ @@ -1133,6 +1142,36 @@ i3GEOF.legenda = { catch(e){i3GEO.janela.tempoMsg("Erro: "+ e);i3GEOF.legenda.aguarde.visibility = "hidden";} }, /* + Function: valorQN + + Altera a legenda do tema por meio do calculo de quebras naturais + + Veja: + +
+ */ + valorQN: function(){ + try{ + if(i3GEOF.legenda.aguarde.visibility === "visible") + {return;} + var item = $i("i3GEOlegendaSelItem").value, + nclasses = $i("i3GEOlegendanclasses").value, + p = i3GEO.configura.locaplic+"/classesphp/mapa_controle.php?g_sid="+i3GEO.configura.sid+"&funcao=alteraclasse&nclasses="+nclasses+"&tema="+i3GEOF.legenda.tema+"&item="+item+"&opcao=quebrasnaturais&ignorar="+$i("i3GEOlegendaignorar").value+"&ext="+i3GEO.parametros.mapexten, + cp = new cpaint(), + fim = function(){ + i3GEOF.legenda.aposAlterarLegenda(); + i3GEOF.legenda.aguarde.visibility = "hidden"; + }; + if (item == "") + {i3GEO.janela.tempoMsg($trad(81,i3GEOF.legenda.dicionario));return;} + i3GEOF.legenda.aguarde.visibility = "visible"; + cp.set_response_type("JSON"); + cp.call(p,"alteraclasse",fim); + } + catch(e){i3GEO.janela.tempoMsg("Erro: "+ e);i3GEOF.legenda.aguarde.visibility = "hidden";} + }, + + /* Function: representacao Altera o tipo de representação do tema (linear ou poligonoal) diff --git a/ferramentas/metaestat/index.js b/ferramentas/metaestat/index.js index 16ce920..7cec9bc 100644 --- a/ferramentas/metaestat/index.js +++ b/ferramentas/metaestat/index.js @@ -1825,7 +1825,8 @@ i3GEOF.metaestat = { var id_medida_variavel = $i("i3geoCartoComboMedidaVariavelEditor").value, id_classificacao = $i("i3geoCartoComboClassificacoesEditor").value, cores = $i("listaColourRampEditor").value, - p = i3GEO.configura.locaplic+"/admin/php/metaestat.php?funcao=calculaClassificacao&tipo=intiguais5mm" + + p = i3GEO.configura.locaplic+"/admin/php/metaestat.php?funcao=calculaClassificacao&tipo=intiguaismm" + + "&numintervalos="+$i("i3GEOFmetaestatEditorNumInt").value + "&cores="+cores+"&id_classificacao="+id_classificacao+"&id_medida_variavel="+id_medida_variavel+ "&min="+$i("i3GEOFmetaestatEditorVmin").value + "&max="+$i("i3GEOFmetaestatEditorVmax").value + @@ -1854,7 +1855,7 @@ i3GEOF.metaestat = { var id_medida_variavel = $i("i3geoCartoComboMedidaVariavelEditor").value, id_classificacao = $i("i3geoCartoComboClassificacoesEditor").value, cores = $i("listaColourRampEditor").value, - p = i3GEO.configura.locaplic+"/admin/php/metaestat.php?funcao=calculaClassificacao&tipo=intiguais5&cores="+cores+"&id_classificacao="+id_classificacao+"&id_medida_variavel="+id_medida_variavel+"&g_sid="+i3GEO.configura.sid, + p = i3GEO.configura.locaplic+"/admin/php/metaestat.php?funcao=calculaClassificacao&tipo=intiguais&numintervalos="+$i("i3GEOFmetaestatEditorNumInt").value+"&cores="+cores+"&id_classificacao="+id_classificacao+"&id_medida_variavel="+id_medida_variavel+"&g_sid="+i3GEO.configura.sid, temp = function(retorno){ core_carregando("desativa"); if(retorno == "erro"){ @@ -2116,7 +2117,9 @@ i3GEOF.metaestat = { " " + $trad(10,i3GEOF.metaestat.dicionario1) + "
"; if(soma == 1 || media == 1){ ins += " " + - " "; + " " + + "intervalos:"; + } ins += '' + //utilizado pelo seletor de colourramp; "" + $trad(17,i3GEOF.metaestat.dicionario1) + "
" + @@ -2130,7 +2133,7 @@ i3GEOF.metaestat = { new YAHOO.widget.Button( "i3GEOFmetaestatEditorBotao8", {onclick:{fn: function(){ - i3GEO.util.abreColourRamp("","listaColourRampEditor",5); + i3GEO.util.abreColourRamp("","listaColourRampEditor",$i("i3GEOFmetaestatEditorNumInt").value); }}} ); $i("i3GEOFmetaestatEditorBotao8-button").style.width = (i3GEOF.metaestat.LARGURA / 2) + "px"; diff --git a/pacotes/jenks-master/LICENSE-APACHE b/pacotes/jenks-master/LICENSE-APACHE new file mode 100755 index 0000000..67db858 --- /dev/null +++ b/pacotes/jenks-master/LICENSE-APACHE @@ -0,0 +1,175 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. diff --git a/pacotes/jenks-master/README.md b/pacotes/jenks-master/README.md new file mode 100755 index 0000000..e91dbb0 --- /dev/null +++ b/pacotes/jenks-master/README.md @@ -0,0 +1,70 @@ +jenks +===== + +PHP Implementation of Jenks Natural Breaks Optimization for Choropleth Mapping +----- + +About: +===== +The Jenks natural breaks optimization method allows you to break up data points into the best possible number of groupings, with the best possible contents of each group for choropleth mapping. + + + +http://en.wikipedia.org/wiki/Choropleth_map + +Here's how it works (from [Wikipedia](http://en.wikipedia.org/wiki/Jenks_natural_breaks_optimization)): + +>The method requires an iterative process. That is, calculations must be repeated using different breaks in the dataset to determine which set of breaks has the smallest in-class variance. The process is started by dividing the ordered data into groups. Initial group divisions can be arbitrary. There are four steps that must be repeated: +> +>1. Calculate the sum of squared deviations between classes (SDBC). +>2. Calculate the sum of squared deviations from the array mean (SDAM). +>3. Subtract the SDBC from the SDAM (SDAM-SDBC). This equals the sum of the squared deviations from the class means. +>4. After inspecting each of the SDBC, a decision is made to move one unit from the class with the largest SDBC toward the class with the lowest SDBC. +> +>New class deviations are then calculated, and the process is repeated until the sum of the within class deviations reaches a minimal value. + + + +or + + + +Where... +* A is the set of values that have been ordered from 1 to N. +* 1 ≤ i < j < N +* Mean i..j is the mean of the class bounded by i and j. + +Development: +===== +I studied up on this and wrote it while working [for a startup](http://grupthinkpowered.com/) a few years ago, in 2009. I found that all of the available choroplethic mapping solutions available had inadequate splits of data when asked to create a map. Unfortunately, very few implementations of Jenks exist outside of professional cartography packages. + +When re-writing this, I had chosen to use the Google Charts API for our maps so, you should be able to use this to simply output a map assuming you provide all the necessary parameters. + +This was kind of based on [another script](http://www.forumsig.org/showthread.php?t=22055) that was in French (which I don't speak very well, at all). The original script had many issues and bugs and wasn't as flexible as I wanted it to be. So, I re-wrote it. + +This one works well and is flexible in terms of the datasets. It has been tested pretty thoroughly and, as far as I can tell, is correct. + +To Do: +===== +* Need a chance to go over it again and make improvements and/or more comments. +* Bug test. +* Write example usage. +* See if the Google Maps stuff even works anymore. +* Make a blog post / homepage. + +License: +===== +Open-source and free for use. +>Copyright 2012 David Drake +> +>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at +> +>http://www.apache.org/licenses/LICENSE-2.0 +> +>Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +Author: +===== +David Drake + +[@randomdrake](https://twitter.com/#!/randomdrake) | [http://randomdrake.com](http://randomdrake.com) | [LinkedIn](http://www.linkedin.com/pub/david-drake/52/247/465) diff --git a/pacotes/jenks-master/jenks.php b/pacotes/jenks-master/jenks.php new file mode 100755 index 0000000..eefbff1 --- /dev/null +++ b/pacotes/jenks-master/jenks.php @@ -0,0 +1,626 @@ += $minimum && $valueRank <= $maximum) { + $classNumber = $ii; + } + + $minimum = $minimum + $numberOfElementsPerClassArray[$ii]; + $maximum = $minimum + $numberOfElementsPerClassArray[$ii + 1] - 1; + } + + return $classNumber; +} + +/** + * This function will determine the maximum values for the classes + * + * @param array $values - the values + * @param array $classes - the classes + */ +function getClassMaximums ($values, $classes) { + $numberValues = count($values); + $numberOfClasses = count($classes); + $maximumValues = array(); + + // Make sure our values are sorted + array_multisort($values); + + $valueIndex = 0; + for ($classNumber = 0; $classNumber < $numberOfClasses; $classNumber++) { + $maximumValues[$classNumber] = $values[$valueIndex]; + $valueIndex = $valueIndex + $classes[$classNumber]; + } + + $maximumValues[$numberOfClasses] = $values[$numberValues - 1]; + + return $maximumValues; +} + +/** + * This function will determine the number of values that belong in each class + * + * @param array $values - the values + * @param array $maximumValues - the maximum values of each class + */ +function getNumberOfValuesPerClass ($values, $maximumValues) { + $numberOfClasses = count($maximumValues) - 1; + $numberOfValues = count($values); + $class = array(); + + // Make sure our values are sorted + array_multisort($values); + + $firstValueOfClass = 0; + + for ($classNumber = 1; $classNumber < $numberOfClasses; $classNumber++) { + $crossIndex = 0; + while ($values[$crossIndex] < $maximumValues[$classNumber] && $crossIndex < $numberOfValues) { + $crossIndex++; + } + $lastClassIndex = $crossIndex - 1; + + $class[$classNumber - 1] = $lastClassIndex - $firstValueOfClass + 1; + $firstValueOfClass = $lastClassIndex + 1; + } + + $class[$classNumber - 1] = $numberOfValues - $firstValueOfClass; + + return $class; +} + +/** + * Calculates an average of the values in an array + * + * @param array $values - the array of values you want an average calculated for + */ +function calculateAverage ($values) { + if (!is_array($values) || count($values) == 0) { + return 0; + } + return array_sum($values) / count($values); +} + +/** + * The Jenks Algorithm + * + * This function will determine the optimal natural breaks for a set of values given a number of classes. It will return + * an array of classes with the number of elements for each class. + * + * @param int $numberOfClasses - the number of classes you want + * @param array $values - the values you are working with + */ +function getJenksClasses ($numberOfClasses, $values) { + // Make sure our values are sorted + array_multisort($values); + + // Determine the number of values + $numberOfValues = count($values); + + // If we have the same number of unique values as classes + if (count(array_unique($values)) == $numberOfClasses) { + // Then we can just count up the number of values in each of the classes and we are finished + $classes = array_values(array_count_values($values)); + return getClassMaximums($values, $classes); + } + + // We need a starting point for Jenks. Let's start with a simple quantile split + $classSize = floor($numberOfValues / $numberOfClasses); + for ($ii = 0; $ii < $numberOfClasses; $ii++) { + $classes[] = $classSize; + } + $classes[$ii - 1] = $numberOfValues - ($numberOfClasses - 1) * $classSize; + + /** + * Now that we have our simple quantile split, we'll do our first round of adjustments. It's very likely the quantile split + * caused equal values to be split into two different classes. This will not work for our classes. We will go through each + * class and determine if any of the values in the classes exist in another class. If they do, we will see which class + * would be best for that set of values by creating feaux classes as if all of the values have been moved and determine which + * move would provide the lowest sum of squared differences for that value. We will then move those values into that class. + */ + $valueCounts = array_count_values($values); + $changeOccurred = true; + $firstIterationCounter = 0; + do { + $changeOccurred = false; + if ($numberOfClasses == 6) { + $numsixcounter++; + if ($numsixcounter == 20) { + exit; + } + } + $startingValuesKey = 0; + $currentClassesArray = array(); + foreach ($classes as $numberValuesInClass) { + $currentClassesArray[] = array_slice($values, $startingValuesKey, $numberValuesInClass); + $startingValuesKey += $numberValuesInClass; + } + foreach ($currentClassesArray as $key => $class) { + if ($key == $numberOfClasses - 1) { + break; + } + /** + * Go through each class. If the class only has one number, we are good. Let's move the rest of the numbers + * into this class if they exist elsewhere + */ + if (count(array_unique($class)) == 1) { + $onlyValueInClass = $class[0]; + if ($classes[$key] != $valueCounts[$onlyValueInClass]) { + // Then there are other classes with this value. We've got some moving to do. + $numberOfValuesToMove = $valueCounts[$onlyValueInClass] - $classes[$key]; + $classKeyToTry = $key + 1; + while ($numberOfValuesToMove > 0) { + // We have to start subtracting from classes that are suitable + if ($classes[$classKeyToTry] <= 1) { + do { + $classKeyToTry++; + if ($classKeyToTry > $numberOfClasses - 1) { + $classKeyToTry = 0; + } + } while ($classKeyToTry == $key); + } + $classes[$classKeyToTry]--; + $classes[$key]++; + $numberOfValuesToMove--; + } + $changeOccurred = true; + break; + } + } else { + // There are more than one value in this class + $valuesInThisClass = array_count_values($class); + $value = max($class); + $numberTimesValueInClass = $valuesInThisClass[$value]; + if ($numberTimesValueInClass != $valueCounts[$value]) { + /** + * Then there are more of these in a different class. If the next class is nothing but this value, we + * know we will just move the values to that class. + */ + if (count(array_unique($currentClassesArray[$key + 1])) == 1) { + // The next class up is made up entirely of this class. We will move the numbers to it. + $numberValuesToMove = $numberTimesValueInClass; + for ($ii = 0; $ii < $numberValuesToMove; $ii++) { + $classes[$key]--; + $classes[$key + 1]++; + } + if ($classes[$key + 1] != $valueCounts[$value]) { + // Then we may have moved all the values out of this class into the next, but there are still more + $numberLeftToMove = $valueCounts[$value] - $classes[$key + 1]; + $classKeyToTry = $key + 2; + while ($numberLeftToMove > 0) { + // We have to start subtracting from classes that are suitable + if ($classes[$classKeyToTry] <= 1) { + $classKeyToTry++; + } + $classes[$classKeyToTry]--; + $classes[$key + 1]++; + $numberLeftToMove--; + } + } + } else { + /** + * There are other numbers in the next class besides the one we are working with. Let's create + * the two classes as if we had put all of the values in the class. Then, we'll find out which + * provides the best SSD for our current $value. + */ + $firstComparisonClass = $currentClassesArray[$key]; + $secondComparisonClass = $currentClassesArray[$key + 1]; + $numberValuesForClass = array_count_values($firstComparisonClass); + $numberValuesToAddFirstClass = $valueCounts[$value] - $numberValuesForClass[$value]; + for ($ii = 0; $ii < $numberValuesToAddFirstClass; $ii++) { + $firstComparisonClass[] = $value; + } + $firstClassAverage = calculateAverage($firstComparisonClass); + $numberValuesForClass = array_count_values($secondComparisonClass); + $numberValuesToAddSecondClass = $valueCounts[$value] - $numberValuesForClass[$value]; + for ($ii = 0; $ii < $numberValuesToAddSecondClass; $ii++) { + $secondComparisonClass[] = $value; + } + $secondClassAverage = calculateAverage($secondComparisonClass); + + // Now that we have built our two feaux classes, let's see which provides us with the best SSD for the value + $firstSSD = pow($value - $firstClassAverage, 2); + $secondSSD = pow($value - $secondClassAverage, 2); + if ($firstSSD < $secondSSD) { + $classKeyToAddTo = $key; + $classKeyToSubtractFrom = $key + 1; + $numberValuesToMove = $numberValuesToAddFirstClass; + } else { + $classKeyToAddTo = $key + 1; + $classKeyToSubtractFrom = $key; + $numberValuesToMove = $numberValuesToAddSecondClass; + } + for ($ii = 0; $ii < $numberValuesToMove; $ii++) { + $classes[$classKeyToAddTo]++; + $classes[$classKeyToSubtractFrom]--; + } + } + $changeOccurred = true; + break; + } + } + } + } while ($changeOccurred == true); + + /** + * Now that we are sure our classes have been split in a way that values are not spread amongst different classes, + * we can do work optimizing our classes further. We will look at the highest and lowest values for each class and + * determine if those sets of values would be better suited in the class above, below, or if they are good where + * they are at. We do not need to look at values in the middle of each class because moving a value in the middle + * to a class above or below it would put our classes out of numeric order and does not make sense. We also do not + * look at the largest or smallest values because those should stay in their lowest and highest class respsectively. + */ + $changeOccurred = 1; + $iterationCounter = 0; + $distinctValues = array_keys($valueCounts); + $numberDistinctValues = count($distinctValues); + $currentClassesArray = array(); + $startingValuesKey = 0; + foreach ($classes as $numberValuesInClass) { + $currentClassesArray[] = array_slice($values, $startingValuesKey, $numberValuesInClass); + $startingValuesKey += $numberValuesInClass; + } + + do { + $changeOccurred = 0; + + // We only want to work on the minimums and maximums of the classes + $minimumValue = min($values); + $maximumValue = max($values); + $valuesToWorkWith = array(); + foreach ($currentClassesArray as $class) { + // We don't want to check values that are in classes by themselves because we cannot improve them + if (count(array_unique($class)) != 1) { + $minValueForArray = min($class); + if ($minValueForArray != $minimumValue && $minValueForArray != $maximumValue) { + $valuesToWorkWith[] = $minValueForArray; + } + $maxValueForArray = max($class); + if ($maxValueForArray != $minimumValue && $maxValueForArray != $maximumValue) { + $valuesToWorkWith[] = $maxValueForArray; + } + } + } + + $numberOfValuesToWorkWith = count($valuesToWorkWith); + if ($numberOfValuesToWorkWith > 0) { + for ($ii = 0; $ii < $numberOfValuesToWorkWith; $ii++) { + $iterationCounter++; + $thisValue = $valuesToWorkWith[$ii]; + + /** + * We will need to create feaux classes above and below the current class to see if the squared deviation decreases. + * If it does, we'll move the values into that class. + */ + $currentClassKeyForValue = determineClass(array_search($thisValue, $values), $numberOfClasses, $classes); + + $firstComparisonClassKey = $currentClassKeyForValue - 1; + $secondComparisonClassKey = $currentClassKeyForValue + 1; + $squaredDeviationsArray = array(); + if ($firstComparisonClassKey > 0) { + $firstComparisonClass = $currentClassesArray[$firstComparisonClassKey]; + $numberValuesForClass = array_count_values($firstComparisonClass); + $numberValuesToAddFirstClass = $valueCounts[$thisValue] - $numberValuesForClass[$thisValue]; + for ($jj = 0; $jj < $numberValuesToAddFirstClass; $jj++) { + $firstComparisonClass[] = $thisValue; + } + $firstClassAverage = calculateAverage($firstComparisonClass); + $squaredDeviationsArray[$firstComparisonClassKey] = pow($thisValue - $firstClassAverage, 2); + } + if ($secondComparisonClassKey < $numberOfClasses) { + $secondComparisonClass = $currentClassesArray[$secondComparisonClassKey]; + $numberValuesForClass = array_count_values($secondComparisonClass); + $numberValuesToAddSecondClass = $valueCounts[$thisValue] - $numberValuesForClass[$thisValue]; + for ($jj = 0; $jj < $numberValuesToAddSecondClass; $jj++) { + $secondComparisonClass[] = $thisValue; + } + $secondClassAverage = calculateAverage($secondComparisonClass); + $squaredDeviationsArray[$secondComparisonClassKey] = pow($thisValue - $secondClassAverage, 2); + } + + $currentClassAverage = calculateAverage($currentClassesArray[$currentClassKeyForValue]); + $currentSquaredDeviation = $squaredDeviationsArray[$currentClassKeyForValue] = pow($thisValue - $currentClassAverage, 2); + + $minSquaredDeviation = min($squaredDeviationsArray); + if ($minSquaredDeviation != $currentSquaredDeviation) { + $minSquaredDeviationKey = array_search($minSquaredDeviation, $squaredDeviationsArray); + + // Then we need to move these values from the class they are in to the class they should be in + $numberOfThisValue = $valueCounts[$thisValue]; + $classes[$minSquaredDeviationKey] += $numberOfThisValue; + $classes[$currentClassKeyForValue] -= $numberOfThisValue; + $changeOccurred = 1; + + // Regenerate our classes as they currently are + $startingValuesKey = 0; + $currentClassesArray = array(); + foreach ($classes as $numberValuesInClass) { + $currentClassesArray[] = array_slice($values, $startingValuesKey, $numberValuesInClass); + $startingValuesKey += $numberValuesInClass; + } + } + } + } + } while ($changeOccurred == 1); + + return getClassMaximums($values, $classes); +} + +/** + * This function determines the optimum number of classes for a given set of values by calculating the goodness of variance fit (GVF) + * for class sizes 4 - 7. It will return the maximum values for each class and the number of values for each class in an array for the + * number of classes that best fits the data. + * + * @param array $values - the values you want to determine the optimum deviation for + * @param int $minimumNumberOfClasses - the minimum number of classes you want to try + * @param int $maximumNumberOfClasses - the maximum number of classes you want to try + * @return array - the maximum values for each array and the number of values for each class + */ +function getOptimalClassInformation ($values, $minimumNumberOfClasses = 4, $maximumNumberOfClasses = 7) { + // Make sure our values are sorted + array_multisort($values); + + $numberOfUniqueValues = count(array_unique($values)); + if ($numberOfUniqueValues <= $maximumNumberOfClasses) { + $maximumValues = getJenksClasses ($numberOfUniqueValues, $values); + $numberOfValuesPerClass = getNumberOfValuesPerClass ($values, $maximumValues); + return array ($maximumValues, $numberOfValuesPerClass); + } else { + $valuesAverage = calculateAverage($values); + $SDAM = 0; + foreach ($values as $value) { + $SDAM += pow ($value - $valuesAverage, 2); + } + + for ($classNumber = $minimumNumberOfClasses; $classNumber <= $maximumNumberOfClasses; $classNumber++) { + $maximumValues = getJenksClasses ($classNumber, $values); + $numberOfValuesPerClass = getNumberOfValuesPerClass ($values, $maximumValues); + $arraySliceIndex = 0; + $SDCM = 0; + foreach ($numberOfValuesPerClass as $numberOfValues) { + $thisClass = array_slice($values, $arraySliceIndex, $numberOfValues); + $thisClassAverage = calculateAverage($thisClass); + $deviationsSumForClass = 0; + foreach ($thisClass as $thisValue) { + $deviationsSumForClass += pow ($thisValue - $thisClassAverage, 2); + } + $SDCM += $deviationsSumForClass; + $arraySliceIndex += $numberOfValues; + } + $gvfsArray[$classNumber] = 1 - ($SDCM / $SDAM); + $returnArraysToClassNumbers[$classNumber] = array ($maximumValues, $numberOfValuesPerClass); + } + } + + return $returnArraysToClassNumbers[array_search(max($gvfsArray), $gvfsArray)]; +} + +/** + * Takes an array of values and an array of numbers per class from Jenks to provide us with a nice list of what the ranges are + * + * @param array $values - the original array of values + * @param array $jenksArray - the array of how many values should go in each class from Jenks + */ +function getMapKeys ($values, $jenksArray) { + // Make sure our values are sorted + array_multisort($values); + + if (count($jenksArray) == 2) { + // If the Jenks array just contains a single value and the max, then we can just return that value + return array (0 => $jenksArray[1]); + } + $returnArray = array(); + $startingValue = $jenksArray[0]; + $arrayCount = count($jenksArray); + $rangeString = 1; + $stoppingValue = $jenksArray[$arrayCount - 1]; + for ($ii = 1; $ii < $arrayCount; $ii++) { + $maxValue = $jenksArray[$ii]; + if ($maxValue == $stoppingValue) { + if ($rangeString == $maxValue) { + $rangeString = $maxValue; + } else { + foreach ($values as $value) { + if ($value < $maxValue) { + $max = $value; + } else if ($rangeString == $max) { + break; + } else { + $rangeString .= ' - ' . $max; + break; + } + } + } + } else { + foreach ($values as $value) { + if ($value < $maxValue) { + $max = $value; + } else if ($max == $rangeString) { + break; + } else { + $rangeString .= ' - ' . $max; + break; + } + } + } + + $returnArray[] = $rangeString; + $rangeString = $jenksArray[$ii]; + } + + return $returnArray; +} + +/** + * This function will display a map using the Google Charts API. Information about the API can be found + * here: http://code.google.com/apis/chart/types.html#maps + * + * We are using Jenks Natural Breaks Classification Scheme to create our breaks in our data and our keys + * for our maps. + * + * The output for this will be a URI that looks like this: http://chart.apis.google.com/chart?cht=t + * &chs=440x220&chco=DCDCDC,FDFAD1,FFE9B0,FFBB7D,E5280C,A61900&chtm=usa&chd=t:20,20,20,20,20,20,20,20, + * 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,40,40,40,40,40,40,40,40,40,40,40,40,60,60,60,60,60,60, + * 60,60,60,80,80,80,80,100,100&chld=VTHIDESDWVDCMERIWYARNENHAKNMMSLAOKIDIANVALUTSCCTKYTNINMDWIMNMOOR + * MANCAZVAGAMIOHCOPANJILWAFLTXNYKSCAMT&chf=bg,s,EAF7FE + * + * Due to the limits of the numbers and formats of numbers that can be sent to the charting API, we break + * our classes up into even numbers that have the most distance between them as possible but still remain + * within 100. The rest of the arguments are fully explained in the API documentaiton. + * + * @param array $values - the values of the map you are trying to create + * @param array $locations - either an array of 2-digit state codes or an array of ISO 3166-1-alpha-2 country + * codes. This array should correspond to the $values in the way it is sorted. + * @param string $map_type - the type of map you would like. Should be from this list: + * 'africa', 'asia', 'europe', 'middle_east', 'south_america', 'usa', 'world' + * @param boolean $return_data - if return data is set to true, this function will return the URI and the + * colors and data needed to display the map key + * @return mixed - either nothing or an array containing the return data + */ +function displayGoogleMap($values, $locations, $map_type, $return_data = false) { + // Color of locations with no values + $empty_color = 'DCDCDC'; + + // Color of the water behind the maps + $water_color = 'FAFAFA'; + + // Make sure our values are sorted + array_multisort($values); + + // We will grab the maximum values from each class as determined by the Jenks algorithm + $class_information = getOptimalClassInformation($values); + $jenks_max_values_per_class = $class_information[0]; + $number_values_per_class = $class_information[1]; + $number_of_classes = count($number_values_per_class); + $valid_map_types = array('africa', 'asia', 'europe', 'middle_east', 'south_america', 'usa', 'world'); + $display_map_types = array ('Africa', 'Asia', 'Europe', 'Middle East', 'South America', 'USA', 'World'); + + // With this information, we will get our map keys + $breaks_array = getMapKeys($values, $jenks_max_values_per_class); + + if ($number_of_classes <= 5) { + $map_colors = array ($empty_color, 'FDFAD1', 'FFE9B0', 'FFBB7D', 'E5280C', 'A61900'); + $google_colors = array ($empty_color, 'FEECB6', 'FECC91', 'F4804F', 'D82509', 'A51900'); + + // Google renders the colors for 2 classes in a particular way + if ($number_of_classes == 2) { + $google_colors = array ($empty_color, 'FEECB6', 'FECD91'); + } + + $class_multiplier = 20; + } else if ($number_of_classes > 5) { + $map_colors = array ($empty_color, 'FFFFFF', 'FDFAD1', 'FFE9B0', 'FFBB7D', 'FF7A3D', 'E5280C', 'A61900'); + $google_colors = array ($empty_color, 'FDFAD1', 'FDEDB9', 'FED095', 'FEA265', 'F96933', 'E2270B', 'AD1A01'); + + // Google renders the colors for 6 classes in a particular way + if ($number_of_classes == 6) { + $google_colors = array ($empty_color, 'FDECB8', 'FCD095', 'FDA165', 'F86732', 'E2280B', 'AD1A01'); + } + $map_colors = $google_colors; + $class_multiplier = round(100 / $number_of_classes, 2); + } + + // Let's build our URI + $uri = 'http://chart.apis.google.com/chart?cht=t&chs=440x220&chco='; + foreach ($map_colors as $color) { + $uri .= $color . ','; + } + $uri = substr($uri, 0, -1); + $uri .= '&chtm=' . $map_type; + + // Here we will build the location abbreviations and location values to go in the URI + $max_value = $values[0]; + $key = 0; + foreach ($locations as $location_abbrev => $number_from_location) { + $location_codes .= $location_abbrev; + $class_number = round((determineClass($key, $number_of_classes, $number_values_per_class) + 1) * $class_multiplier); + $location_values .= $class_number . ','; + $key++; + } + $location_values = substr($location_values, 0, -1); + + // Finish off our URI by tacking on the values, codes, and color for the water + $uri .= '&chd=t:' . $location_values . + '&chld=' . $location_codes . + '&chf=bg,s,' . $water_color; + + // We need to check and see if they just wanted data returned or if they wanted the map displayed + if ($return_data) { + // Let's build our array for the map colors and data and return our data + $map_key_array[$empty_color] = 'No Data'; + for ($ii = 1; $ii <= $number_of_classes; $ii++) { + $color = $google_colors[$ii]; + $text = $breaks_array[$ii - 1]; + $map_key_array[$color] = $text; + } + return array ($uri, $map_key_array); + } else { + // Let's display it + $empty_color = $google_colors[0]; + echo << ++
+ +HTML; + for ($ii = 1; $ii <= $number_of_classes; $ii++) { + $color = $google_colors[$ii]; + $text = $breaks_array[$ii - 1]; + echo << ++ + ++ No Data + ++ {$text} + +HTML; + + } + echo << + ++HTML; + } +} +?> -- libgit2 0.21.2