From d4b1d361a94b9bc330f098348cedb3bc8343d505 Mon Sep 17 00:00:00 2001 From: Edmar Moretti Date: Wed, 25 Jun 2014 17:59:57 +0000 Subject: [PATCH] Inclusao do calculo de heatmap na interface googlemaps --- classesjs/classe_interface.js | 347 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- classesjs/classe_plugini3geo.js | 260 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------------------------------------------- classesphp/classe_atributos.php | 12 ++++++------ ferramentas/heatmap/openlayers_js.php | 3 ++- pacotes/heatmap/src/heatmap-gmaps.js | 79 +++++++++++++++++++++++++++++++++++++++++++++---------------------------------- pacotes/heatmap/src/heatmap.js | 66 +++++++++++++++++++++++++++++++++--------------------------------- 6 files changed, 414 insertions(+), 353 deletions(-) diff --git a/classesjs/classe_interface.js b/classesjs/classe_interface.js index 4046f43..0eecbc9 100644 --- a/classesjs/classe_interface.js +++ b/classesjs/classe_interface.js @@ -47,152 +47,152 @@ if (typeof (i3GEO) === 'undefined') { i3GEO.Interface = { /* * Propriedade: TABLET - * + * * Quando true, são aplicadas configurações especiais * para uso em tablets. - * + * * Altera o posicionamento da barra de botões e comportamento das * guias. Veja o exemplo interface/openlayers_t.htm. - * + * * Type: {boolean} - * + * * Default: {false} */ TABLET : false, /* * Propriedade: ALTTABLET - * + * * Nome do arquivo HTML com a interface alternativa utilizada quando o i3Geo * detecta o uso de um dispositivo móvel - * + * * A detecção é aplicada automaticamente quando essa * variável for definida - * + * * Para não aplicar a detecção, use * i3GEO.Interface.ALTTABLET = "" - * + * * Type: {string} - * + * * Default: {""} */ ALTTABLET : "", /* * Formato de geração da imagem. - * + * * Os formatos devem estar definidos no mapfile geral1windows.map e * geral1.map. A definição dessa variável não * afeta a interface padrão, que utiliza a definição * que estiver ativa nos mapfiles de inicialização. - * + * * Tipo: {MAPSERVER OUTPUTFORMAT} - * + * * Default: {"AGG_Q"} */ OUTPUTFORMAT : "AGG_Q", /* * Propriedade: BARRABOTOESTOP - * + * * Distancia da barra de botões em relação ao topo do * mapa. - * + * * Tipo: {number} - * + * * Default: {12} */ BARRABOTOESTOP : 12, /* * Propriedade: BARRABOTOESLEFT - * + * * Distancia da barra de botões em relação ao lado * esquerdo do mapa. - * + * * Tipo: {number} - * + * * Default: {3} */ BARRABOTOESLEFT : 3, /* * Propriedade: BARRADEZOOMTOP - * + * * Distancia da barra de zoom em relação ao topo do mapa. - * + * * Tipo: {number} - * + * * Default: {12} */ BARRADEZOOMTOP : 20, /* * Propriedade: BARRADEZOOMLEFT - * + * * Distancia da barra de zoom em relação ao lado esquerdo do * mapa. - * + * * Tipo: {number} - * + * * Default: {3} */ BARRADEZOOMLEFT : 10, /* * Propriedade: ATUAL - * + * * Interface utilizada na criação e controle do mapa. - * + * * Veja como usar nos arquivos de apresentação do mapa * existentes no diretório i3geo/interface - * + * * O i3Geo, além da interface própria, permite o uso de outras * APIs para a construção do mapa, como Google Maps ou * Openlayers. Essa propriedade define qual interface será usada. * Não confundir com o nome do HTML que é utilizado para * mostrar o mapa. - * + * * Para definir a interface, utilize - * + * * i3GEO.Interface.ATUAL = "" - * + * * Tipo: {string} - * + * * Valores: {openlayers|googlemaps|googleearth} - * + * * Default: {"openlayers"} */ ATUAL : "openlayers", /* * Propriedade: IDCORPO - * + * * ID do elemento HTML que receberá o corpo do mapa - * + * * Tipo: {string} - * + * * Default: {"corpoMapa"} */ IDCORPO : "corpoMapa", /* * Indica se o menu de contexto deve ser ativado - * + * * Tipo: {Boolean} - * + * * Default: {true} */ ATIVAMENUCONTEXTO : false, /* * Variavel: IDMAPA - * + * * ID do elemento HTML criado para conter o mapa - * + * * Esse elemento normalmente é criado dentro de IDCORPO dependendo da * interface */ IDMAPA : "", /* * Indica o status atual do mapa. - * + * * É utilizado para verificar o status do mapa e bloquear ou * não determinadas funções. - * + * * Por exemplo, na interface OpenLayers, identifica se as camadas * estão sendo atualizadas - * + * * STATUS = { atualizando: new Array(), //guarda os códigos dos * layers que estão sendo redesenhados trocando: false //indica se o * mapa está na fase de troca de interface } @@ -282,7 +282,7 @@ i3GEO.Interface = { }, /* * Function: redesenha - * + * * Aplica o método redesenha da interface atual. Em alguns casos, a * função de redesenho aplica os mesmos processos da * função de atualizar o mapa. Isso ocorre pq em alguns casos @@ -296,13 +296,13 @@ i3GEO.Interface = { }, /* * Function: aplicaOpacidade - * + * * Aplica um fator de opacidade a todos os layers do mapa - * + * * Parametro: - * + * * opacidade {numerico} - 0 a 1 - * + * * layer {string} - (opcional) se for vazio aplica ao mapa todo */ aplicaOpacidade : function(opacidade, layer) { @@ -313,7 +313,7 @@ i3GEO.Interface = { }, /* * Function: atualizaMapa - * + * * Aplica o método atualizaMapa da interface atual. Em alguns casos, * a função de redesenho aplica os mesmos processos da * função de atualizar o mapa. Isso ocorre pq em alguns casos @@ -333,16 +333,16 @@ i3GEO.Interface = { }, /* * Function: atualizaTema - * + * * Aplica o método atualizaTema da interface atual - * + * * Parametros: - * + * * retorno {JSON} - objeto JSON com os par�metros obtidos da * função PHP de redesenho do mapa. Quando igual a "", * é feita apenas a atualização da camada, sem que a * árvore de camadas seja atualizada. - * + * * tema {string} - código do tema */ atualizaTema : function(retorno, tema) { @@ -352,11 +352,11 @@ i3GEO.Interface = { }, /* * Function: ligaDesliga - * + * * Liga/desliga um tema - * + * * Parametros: - * + * * {object} objeto do tipo checkbox que foi acionado na arvore de camadas */ ligaDesliga : function(obj) { @@ -364,7 +364,7 @@ i3GEO.Interface = { }, /* * Function: adicionaKml - * + * * Aplica o método de adição de kml ao mapa conforme a * interface atual */ @@ -383,14 +383,14 @@ i3GEO.Interface = { }, /* * Cria ou altera os elementos HTML necessários para a interface - * + * * Essa função é executada na * inicialização do i3geo - * + * * Parametros: - * + * * w {Integer} - largura do corpo do mapa em pixels - * + * * h {Integer} - altura do corpo do mapa em pixels */ cria : function(w, h) { @@ -442,7 +442,7 @@ i3GEO.Interface = { }, /* * Function: alteraLayers - * + * * Altera todos os layers do mapa modificando um determinado par�metro */ alteraParametroLayers : function(parametro, valor) { @@ -469,27 +469,27 @@ i3GEO.Interface = { }, /* * Classe: i3GEO.Interface.openlayers - * + * * Interface com motor de navegação baseado na API OpenLayers - * + * * Utilizado quando - * + * * i3GEO.Interface.ATUAL = "openlayers" - * + * * Cria o objeto i3geoOL que pode receber os métodos da API do * OpenLayers - * + * * Para detalhes sobre a configuração da interface, veja * i3geo/aplicmap/openlayers.htm */ openlayers : { /* * Propriedade: parametrosMap - * + * * Permite incluir parametros da API do OpenLayers nao previstos no * i3Geo. Veja em * http://dev.openlayers.org/releases/OpenLayers-2.12/doc/apidocs/files/OpenLayers/Map-js.html - * + * * Exemplo i3GEO.Interface.openlayers.parametrosMap.scales = [50000000, * 30000000, 10000000, 5000000]; */ @@ -505,46 +505,46 @@ i3GEO.Interface = { }, /* * Propriedade: FUNDOTEMA - * + * * Estilo "background" do nome do tema na árvore de camadas * enquanto o mesmo está sendo carregado. - * + * * Permite destacar o nome do tema que está em processo de * carregamento - * + * * Tipo: {background style} - * + * * Default: {yellow} */ FUNDOTEMA : "yellow", /* * Propriedade: TILES - * + * * Indica se será utilizado o modo de navegação em * tiles - * + * * Tipo: {boolean} - * + * * Default: {false} */ TILES : true, /* * Número de TILES na área não visível do * mapa - * + * * Tipo: {integer} - * + * * Default: {0} */ BUFFER : 0, /* * Propriedade: GADGETS - * + * * Lista dos controles específicos da API do OpenLayers que * serão inseridos ou não no mapa - * + * * Tipo: {object} - * + * * Default: * {PanZoomBar:true,LayerSwitcher:true,ScaleLine:true,OverviewMap:true} */ @@ -557,37 +557,37 @@ i3GEO.Interface = { }, /* * Propriedade: MINEXTENT - * + * * Menor extensão geográfica que pode ser mostrada no mapa - * + * * Tipo: {array} - * + * * Default: {-0.0003, -0.0003, 0.0003, 0.0003]} */ MINEXTENT : [ -0.0003, -0.0003, 0.0003, 0.0003 ], /* * Propriedade: MAXEXTENT - * + * * Maior extensão geográfica que pode ser mostrada no mapa - * + * * Tipo: {array} - * + * * Default: {[-180, -90, 180, 90]} */ MAXEXTENT : [ -180, -90, 180, 90 ], /* * Propriedades: LAYERSADICIONAIS - * + * * Array com objetos do tipo LAYER que serão adicionados * após a crioação de todos os layers default. - * + * * Tipo: {array} - * + * */ LAYERSADICIONAIS : [], /* * Propriedade: LAYERFUNDO - * + * * Nome do layer do tipo baselayer que sera ativado */ LAYERFUNDO : "", @@ -1628,13 +1628,13 @@ i3GEO.Interface = { }, /* * Classe: i3GEO.Interface.googlemaps - * + * * Interface com motor de navegação baseado na API Google Maps - * + * * Utilizado quando - * + * * i3GEO.Interface.ATUAL = "googlemaps" - * + * * Cria o objeto i3GeoMap que pode receber os métodos da API. Cria * também o objeto i3GeoMapOverlay do tipo Overlay, utilizado para * cálculos ou para receber elementos gráficos. @@ -1642,14 +1642,14 @@ i3GEO.Interface = { googlemaps : { /* * Propriedade: ESTILOS - * + * * Estilos que podem ser utilizados com o mapa - * - * + * + * * Para novos estilos, acrescente seu codigo nesse objeto - * + * * Fonte http://maps-api-tt.appspot.com/apilite/styled/styled.html - * + * * Tipo: {objeto estilo do Google Maps} */ ESTILOS : { @@ -1791,30 +1791,30 @@ i3GEO.Interface = { }, /* * Propriedade: ESTILOPADRAO - * + * * Nome do estilo definido em ESTILOS que sera usado como padrao para o * mapa. Se for "" sera usado o estilo normal do Google - * + * * Estilos pre-definidos Red, Countries, Night, Blue, Greyscale, No * roads, Mixed, Chilled - * + * * Tipo: {string} - * + * * Default: "" */ ESTILOPADRAO : "", /* * Propriedade: MAPOPTIONS - * + * * Objeto contendo opções que serão utilizadas no * construtor do mapa conforme a API do GoogleMaps - * + * * Exemplo de uso - * + * * i3GEO.Interface.googlemaps.MAPOPTIONS = {maxZoom:5}; - * + * * https://developers.google.com/maps/documentation/javascript/reference#MapOptions - * + * * Tipo: {MapOptions} */ MAPOPTIONS : { @@ -1822,36 +1822,36 @@ i3GEO.Interface = { }, /* * Propriedade: OPACIDADE - * + * * Valor da opacidade das camadas i3geo do mapa - * + * * Varia de 0 a 1 - * + * * Default: 0.8 - * + * * Tipo: {Numeric} */ OPACIDADE : 0.8, /* * Propriedade: TIPOMAPA - * + * * Tipo de mapa que será usado como default, conforme constantes * definidas na API do Google Maps. - * + * * Default: "roadmap" - * + * * Tipo: {string - Google API constante * "satellite"|"roadmap"|"hybrid"|"terrain"} */ TIPOMAPA : "terrain", /* * Variable: ZOOMSCALE - * + * * Array com a lista de escalas em cada nivel de zoom utilizado pelo * Google - * + * * Tipo: {array} - * + * */ ZOOMSCALE : [ 591657550, 295828775, 147914387, 73957193, 36978596, 18489298, 9244649, 4622324, 2311162, 1155581, 577790, 288895, @@ -1859,14 +1859,14 @@ i3GEO.Interface = { /* * Par�metros adicionais que são inseridos na URL que define cada * layer - * + * * Tipo: {string} */ PARAMETROSLAYER : "&TIPOIMAGEM=" + i3GEO.configura.tipoimagem, /* * String acrescentada � url de cada tile para garantir a * remoção do cache local - * + * * Type: {string} */ posfixo : 0, @@ -2060,8 +2060,15 @@ i3GEO.Interface = { if (!indice) { // nao utilize !== aqui if (camada.status != 0) { + // verifica se a camada contem um plugin do i3geo + // caso tenha, direciona para a classe_i3geoplugin + if (camada.plugini3geo != "") { + i3GEO.pluginI3geo.inicia(camada); + continue; + } else { i3GEO.Interface.googlemaps.insereLayer(camada.name, 0, camada.cache); + } } } } @@ -2172,7 +2179,7 @@ i3GEO.Interface = { var i = false; try { i3GeoMap.overlayMapTypes.forEach(function(elemento, number) { - // alert(nomeLayer+" "+elemento.name) + //alert(nomeLayer+" "+elemento.name) if (elemento.name === nomeLayer) { i = number; } @@ -2353,27 +2360,27 @@ i3GEO.Interface = { }, /* * Function: adicionaKml - * + * * Insere no mapa uma camada KML com base na API do Google Maps - * + * * As camadas adicionadas são acrescentadas na árvore de * camadas - * + * * A lista de nomes dos objetos geoXml criados é mantida em * i3GEO.mapas.GEOXML - * + * * Parametros: - * + * * pan {Boolean} - define se o mapa será deslocado para encaixar * o KML - * + * * url {String} - URL do arquivo KML. Se não for definido, a URL * será obtida do INPUT com id = i3geo_urlkml (veja * i3GEO.gadgets.mostraInserirKml) - * + * * titulo {string} - titulo que aparecerá na árvore. Se * não for definido, será calculado aleatoriamente. - * + * * ativo {boolean} - indica se a camada estará ativa ou * não. Se não for definido, será considerado como * true @@ -2424,24 +2431,24 @@ i3GEO.Interface = { }, /* * Function: adicionaNoArvoreGoogle - * + * * Acrescenta na árvore de camadas um novo tema no nó que * mostra os arquivos KML inseridos no mapa - * + * * Os temas são incluídos em um nó chamado "Google * Maps". - * + * * Para obter esse nó utilize var node = * i3GEO.arvoreDeCamadas.ARVORE.getNodeByProperty("idkml","raiz"); - * + * * Parametros: - * + * * url {string} - url do arquivo KML - * + * * nomeOverlay {string} - título do tema - * + * * ativo {boolean} - indica o estado do checkbox - * + * * id {string} - nome do objeto GGeoXml */ adicionaNoArvoreGoogle : function(url, nomeOverlay, ativo, id) { @@ -2524,13 +2531,13 @@ i3GEO.Interface = { }, /* * Function: ativaDesativaCamadaKml - * + * * Ativa ou desativa uma camada do nó de layers KML - * + * * Parametro: - * + * * obj {object} - objeto do tipo checkbox que foi ativado/desativado - * + * * url {string} - url do KML */ ativaDesativaCamadaKml : function(obj, url) { @@ -2553,42 +2560,42 @@ i3GEO.Interface = { }, /* * Classe: i3GEO.Interface.googleearth - * + * * Interface com motor de navegação baseado na API Google * Earth - * + * * Utilizado quando - * + * * i3GEO.Interface.ATUAL = "googleearth" - * + * * Cria o objeto i3GeoMap que pode receber os métodos da API do * google Earth */ googleearth : { /* * Variable: PARAMETROSLAYER - * + * * Par�metros adicionais que são inseridos na URL que define cada * layer - * + * * Tipo: {string} */ PARAMETROSLAYER : "&TIPOIMAGEM=" + i3GEO.configura.tipoimagem, /* * String acrescentada � url de cada tile para garantir a * remoção do cache local - * + * * Type: {string} */ posfixo : "", /* * Propriedade: GADGETS - * + * * Lista dos controles específicos da API do Google Earth que * serão inseridos ou não no mapa - * + * * Tipo: {object} - * + * * Default: {} */ GADGETS : { @@ -3060,27 +3067,27 @@ i3GEO.Interface = { }, /* * Function: adicionaKml - * + * * Insere no mapa uma camada KML com base na API do Google Earth - * + * * As camadas adicionadas são crescentadas na árvore de * camadas - * + * * A lista de nomes dos objetos geoXml criados é mantida em * i3GEO.mapas.GEOXML - * + * * Parametros: - * + * * pan {Boolean} - define se o mapa será deslocado para encaixar * o KML - * + * * url {String} - URL do arquivo KML. Se não for definido, a URL * será obtida do INPUT com id = i3geo_urlkml (veja * i3GEO.gadgets.mostraInserirKml) - * + * * titulo {string} - titulo que aparecerá na árvore. Se * não for definido, será calculado aleatoriamente. - * + * * ativo {boolean} - indica se a camada estará ativa ou * não. Se não for definido, será considerado como * true @@ -3141,24 +3148,24 @@ i3GEO.Interface = { }, /* * Function: adicionaNoArvoreGoogle - * + * * Acrescenta na árvore de camadas um novo tema no nó que * mostra os arquivos KML inseridos no mapa - * + * * Os temas são incluídos em um nó chamado "Google * Earth". - * + * * Para obter esse nó utilize var node = * i3GEO.arvoreDeCamadas.ARVORE.getNodeByProperty("idkml","raiz"); - * + * * Parametros: - * + * * url {string} - url do arquivo KML - * + * * nomeOverlay {string} - título do tema - * + * * ativo {boolean} - indica o estado do checkbox - * + * * id {string} - nome do objeto GGeoXml */ adicionaNoArvoreGoogle : function(url, nomeOverlay, ativo, id) { @@ -3254,11 +3261,11 @@ i3GEO.Interface = { }, /* * Function: ativaDesativaCamadaKml - * + * * Ativa ou desativa uma camada do nó de layers KML - * + * * Parametro: - * + * * obj {object} - objeto do tipo checkbox que foi ativado/desativado */ ativaDesativaCamadaKml : function(obj) { diff --git a/classesjs/classe_plugini3geo.js b/classesjs/classe_plugini3geo.js index 9712319..045518b 100644 --- a/classesjs/classe_plugini3geo.js +++ b/classesjs/classe_plugini3geo.js @@ -1,28 +1,28 @@ /** * Title: pluginI3geo - * + * * i3GEO.pluginI3geo - * + * * Implementam os plugins do i3Geo que adicionam camadas especiais ao mapa, * normalmente dados vetoriais. - * + * * Arquivo: - * + * * i3geo/classesjs/classe_plugini3geo.js - * + * * Licença: - * + * * 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@gmail.com - * + * * 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 ADEQUACÃO A UMA FINALIDADE @@ -37,108 +37,150 @@ if (typeof (i3GEO) === 'undefined') { var i3GEO = {}; } i3GEO.pluginI3geo = { - /** - * Inicia a execucao de um plugin - * - * Camada e um objeto gerado pelo i3Geo quando uma camada e adicionada ao - * mapa O objeto i3GEO.arvoreDeCamadas.CAMADAS guarda todas as camadas - * adicionadas ao mapa Ao adicionar uma camada pelo catalogo, o i3Geo - * verifica se a camada possui plugin e direciona para ca Os plugins sao - * definidos como metadados em cada mapfile de cada tema - * - * Veja em i3geo/classesphp/classe_mapa.php funcao parametrostemas - */ - inicia : function(camada) { - i3GEO.janela.AGUARDEMODAL = true; - i3GEO.janela.abreAguarde("aguardePlugin","Calculando..."); - i3GEO.janela.AGUARDEMODAL = false; - // chama a funcao conforme o tipo de plugin e a interface atual - // para cada plugin deve haver um objeto com as funcoes especificas para - // cada interface - i3GEO.pluginI3geo[camada.plugini3geo.plugin][i3GEO.Interface.ATUAL] - .call(null, camada); - }, - /** - * Function: heatmap - * - * Mapa de calor - * - * Gera um layer do tipo mapa de calor e adiciona ao mapa - * - * As dependências em javascript sao carregadas via script tag por - * meio de ferramentas/heatmap/openlayers_js.php - * - * Esse programa também obtém os dados necessários ao - * plugin - * - * O layer existente no mapfile deve conter um metadata chamado PLUGINI3GEO - * - * Esse matadado deve conter uma string que será transformada em um - * objeto javascript para uso no plugin - * - * Exemplo: - * - * "PLUGINI3GEO" '{"plugin":"heatmap","parametros":{"coluna":"teste"}}' - * - * Coluna é a que contém os dados numéricos que definem - * a quantidade de uma medida em cada ponto e é usada para gerar a - * representação. Se for vazia, considera-se o valor como 1 - * - * As cores das classes existentes no LAYER serão utilizadas para - * calcular as cores do mapa de calor. Se não existirem classes, - * será usado o default. - * - */ - heatmap : { - openlayers : function(camada) { - var p = i3GEO.configura.locaplic - + "/ferramentas/heatmap/openlayers_js.php", carregaJs = "nao", crialayer; - criaLayer = function() { - var heatmap, g, datalen = heatmap_dados.length, features = []; - if (i3GEO.Interface.openlayers.googleLike === true) { - var sphericalMercatorProj = new OpenLayers.Projection( - 'EPSG:900913'), geographicProj = new OpenLayers.Projection( - 'EPSG:4326'); + /** + * Inicia a execucao de um plugin + * + * Camada e um objeto gerado pelo i3Geo quando uma camada e adicionada + * ao mapa O objeto i3GEO.arvoreDeCamadas.CAMADAS guarda todas as + * camadas adicionadas ao mapa Ao adicionar uma camada pelo catalogo, o + * i3Geo verifica se a camada possui plugin e direciona para ca Os + * plugins sao definidos como metadados em cada mapfile de cada tema + * + * Veja em i3geo/classesphp/classe_mapa.php funcao parametrostemas + */ + inicia : function(camada) { + i3GEO.janela.AGUARDEMODAL = true; + i3GEO.janela.abreAguarde("aguardePlugin","Calculando..."); + i3GEO.janela.AGUARDEMODAL = false; + // chama a funcao conforme o tipo de plugin e a interface atual + // para cada plugin deve haver um objeto com as funcoes especificas + // para + // cada interface + i3GEO.pluginI3geo[camada.plugini3geo.plugin][i3GEO.Interface.ATUAL] + .call(null, camada); + }, + /** + * Function: heatmap + * + * Mapa de calor + * + * Gera um layer do tipo mapa de calor e adiciona ao mapa + * + * As dependências em javascript sao carregadas via script tag por + * meio de ferramentas/heatmap/openlayers_js.php + * + * Esse programa também obtém os dados necessários + * ao plugin + * + * O layer existente no mapfile deve conter um metadata chamado + * PLUGINI3GEO + * + * Esse matadado deve conter uma string que será transformada em + * um objeto javascript para uso no plugin + * + * Exemplo: + * + * "PLUGINI3GEO" '{"plugin":"heatmap","parametros":{"coluna":"teste"}}' + * + * Coluna é a que contém os dados numéricos que + * definem a quantidade de uma medida em cada ponto e é usada + * para gerar a representação. Se for vazia, considera-se + * o valor como 1 + * + * As cores das classes existentes no LAYER serão utilizadas para + * calcular as cores do mapa de calor. Se não existirem classes, + * será usado o default. + * + */ + heatmap : { + googlemaps: function(camada){ + var p = i3GEO.configura.locaplic + + "/ferramentas/heatmap/googlemaps_js.php", carregaJs = "nao", crialayer; + criaLayer = function() { + var heatmap,pontos; + heatmap = new HeatmapOverlay(i3GeoMap, { + "radius":15, + "visible":true, + "opacity":60, + "gradient": { 0.45: "rgb(0,0,255)", 0.55: "rgb(0,255,255)", 0.65: "rgb(0,255,0)", 0.95: "yellow", 1.0: "rgb(255,0,0)" }, + "legend": { + "title": camada.tema, + "position": "bl", + "offset": [5,50] + } + }); + pontos={ + max: 10, + data: heatmap_dados + }; + i3GEO.janela.fechaAguarde("aguardePlugin"); + heatmap.setDataSet(pontos); + heatmap_dados = null; + //i3GeoMap.setZoom(i3GeoMap.getZoom()); + }; + if (typeof (HeatmapOverlay) === 'undefined') { + carregaJs = "sim"; } - while (datalen--) { - g = new OpenLayers.Geometry.Point(parseInt( - heatmap_dados[datalen].lng, 10), parseInt( - heatmap_dados[datalen].lat, 10)); - if(geographicProj){ - g.transform(geographicProj, sphericalMercatorProj); + p += "?carregajs=" + carregaJs + "&layer=" + camada.name + + "&coluna=" + camada.plugini3geo.parametros.coluna + + "&g_sid=" + i3GEO.configura.sid + + "&nomevariavel=heatmap_dados"; + i3GEO.util.scriptTag(p, criaLayer, + "i3GEO.pluginI3geo.heatmap_script"); + }, + openlayers : function(camada) { + var p = i3GEO.configura.locaplic + + "/ferramentas/heatmap/openlayers_js.php", carregaJs = "nao", crialayer; + criaLayer = function() { + var heatmap, transformedTestData = { max: 10 , data: [] }, + data = heatmap_dados, + datalen = heatmap_dados.length, + nudata = []; + // in order to use the OpenLayers Heatmap Layer we have to transform our data into + // { max: , data: [{lonlat: , count: },...]} + while(datalen--){ + nudata.push({ + lonlat: new OpenLayers.LonLat(data[datalen].lng, heatmap_dados[datalen].lat), + count: heatmap_dados[datalen].count + }); } - features.push(new OpenLayers.Feature.Vector(g, { - count : parseInt(heatmap_dados[datalen].count, 10) - })); - } + transformedTestData.data = nudata; + // create our heatmap layer + heatmap = new OpenLayers.Layer.Heatmap( + camada.name, + i3geoOL, + i3geoOL.baseLayer, + { + visible: true, + radius:10, + "gradient": { 0.45: "rgb(0,0,255)", 0.55: "rgb(0,255,255)", 0.65: "rgb(0,255,0)", 0.95: "yellow", 1.0: "rgb(255,0,0)" }, + "legend": { + "title": camada.tema, + "position": "bl", + "offset": [5,50] + } + }, + { + isBaseLayer: false, + opacity: 0.3, + projection: new OpenLayers.Projection("EPSG:4326") + } + ); + i3geoOL.addLayer(heatmap); + heatmap.setDataSet(transformedTestData); - // create our vectorial layer using heatmap renderer - heatmap = new OpenLayers.Layer.Vector(camada.name, { - opacity : 0.3, - renderers : [ 'Heatmap' ], - rendererOptions : { - weight : 'count', - heatmapConfig : { - radius : 10 - } - } - }); - heatmap.addFeatures(features); - i3geoOL.addLayer(heatmap); - heatmap_dados = null; - i3GEO.janela.fechaAguarde("aguardePlugin"); - }; - if (typeof (HeatmapOverlay) === 'undefined') { - carregaJs = "sim"; + heatmap_dados = null; + i3GEO.janela.fechaAguarde("aguardePlugin"); + }; + if (typeof (HeatmapOverlay) === 'undefined') { + carregaJs = "sim"; + } + p += "?carregajs=" + carregaJs + "&layer=" + camada.name + + "&coluna=" + camada.plugini3geo.parametros.coluna + + "&g_sid=" + i3GEO.configura.sid + + "&nomevariavel=heatmap_dados"; + i3GEO.util.scriptTag(p, criaLayer, + "i3GEO.pluginI3geo.heatmap_script"); } - p += "?carregajs=" + carregaJs + "&layer=" + camada.name - + "&coluna=" + camada.plugini3geo.parametros.coluna - + "&g_sid=" + i3GEO.configura.sid - + "&nomevariavel=heatmap_dados"; - - i3GEO.util.scriptTag(p, criaLayer, - "i3GEO.pluginI3geo.heatmap_script"); - } - } } \ No newline at end of file diff --git a/classesphp/classe_atributos.php b/classesphp/classe_atributos.php index 21d7939..ea08c46 100644 --- a/classesphp/classe_atributos.php +++ b/classesphp/classe_atributos.php @@ -564,17 +564,17 @@ class Atributos } /* function: listaRegistrosXY - + Pega o XY de cada registro e valores de itens especificos - + parameters: - + $items - lista de itens separado por "," - + $tipo - Tipo de abrangência espacial (brasil ou mapa). - + $tipolista - Indica se serão mostrados todos os registros ou apenas os selecionados (tudo|selecionados) - + */ function listaRegistrosXY($items,$tipo,$tipolista) { diff --git a/ferramentas/heatmap/openlayers_js.php b/ferramentas/heatmap/openlayers_js.php index 7df3549..1440d6b 100644 --- a/ferramentas/heatmap/openlayers_js.php +++ b/ferramentas/heatmap/openlayers_js.php @@ -47,7 +47,8 @@ if (!connection_aborted()){ echo $nomevariavel.' = ['.implode(",",$resultado).'];'; if($carregajs === "sim"){ include_once($dir."/../../pacotes/heatmap/src/heatmap.js"); - include_once($dir."/../../pacotes/heatmap/src/heatmap-openlayers-renderer.js"); + //include_once($dir."/../../pacotes/heatmap/src/heatmap-openlayers-renderer.js"); + include_once($dir."/../../pacotes/heatmap/src/heatmap-openlayers.js"); } ?> \ No newline at end of file diff --git a/pacotes/heatmap/src/heatmap-gmaps.js b/pacotes/heatmap/src/heatmap-gmaps.js index 41befe5..30ca720 100755 --- a/pacotes/heatmap/src/heatmap-gmaps.js +++ b/pacotes/heatmap/src/heatmap-gmaps.js @@ -1,11 +1,21 @@ -/* +/* * heatmap.js GMaps overlay * * Copyright (c) 2011, Patrick Wied (http://www.patrick-wied.at) * Dual-licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and the Beerware (http://en.wikipedia.org/wiki/Beerware) license. - */ - + */ + +//cria um layer idiota para poder calcular a projecao +//http://stackoverflow.com/questions/1538681/how-to-call-fromlatlngtodivpixel-in-google-maps-api-v3 +heatmapFooOverlay.prototype = new google.maps.OverlayView(); +heatmapFooOverlay.prototype.onAdd = function() { } +heatmapFooOverlay.prototype.onRemove = function() { } +heatmapFooOverlay.prototype.draw = function() { } +function heatmapFooOverlay() { this.setMap(i3GeoMap); } +var heatmapBarOverlay = new heatmapFooOverlay(); + + function HeatmapOverlay(map, cfg){ var me = this; @@ -14,21 +24,20 @@ function HeatmapOverlay(map, cfg){ me.latlngs = []; me.bounds = null; me.setMap(map); - - google.maps.event.addListener(map, 'dragend', function() { me.draw() }); + google.maps.event.addListener(map, 'bounds_changed', function() { me.draw() }); } HeatmapOverlay.prototype = new google.maps.OverlayView(); HeatmapOverlay.prototype.onAdd = function(){ - + var panes = this.getPanes(), w = this.getMap().getDiv().clientWidth, - h = this.getMap().getDiv().clientHeight, + h = this.getMap().getDiv().clientHeight, el = document.createElement("div"); - + el.style.cssText = "position:absolute;top:0;left:0;width:"+w+"px;height:"+h+"px;"; - + this.conf.element = el; panes.overlayLayer.appendChild(el); @@ -40,16 +49,16 @@ HeatmapOverlay.prototype.onRemove = function(){ } HeatmapOverlay.prototype.draw = function(){ - + var me = this, - overlayProjection = me.getProjection(), + overlayProjection = heatmapBarOverlay.getProjection(), //me.getProjection(), currentBounds = me.map.getBounds(); - + if (currentBounds.equals(me.bounds)) { return; } me.bounds = currentBounds; - + var ne = overlayProjection.fromLatLngToDivPixel(currentBounds.getNorthEast()), sw = overlayProjection.fromLatLngToDivPixel(currentBounds.getSouthWest()), topY = ne.y, @@ -62,12 +71,12 @@ HeatmapOverlay.prototype.draw = function(){ me.conf.element.style.width = w + 'px'; me.conf.element.style.height = h + 'px'; me.heatmap.store.get("heatmap").resize(); - + if(this.latlngs.length > 0){ this.heatmap.clear(); - + var len = this.latlngs.length, - projection = this.getProjection(); + projection = heatmapBarOverlay.getProjection(); //this.getProjection(); d = { max: this.heatmap.store.max, data: [] @@ -76,7 +85,7 @@ HeatmapOverlay.prototype.draw = function(){ while(len--){ var latlng = this.latlngs[len].latlng; if(!currentBounds.contains(latlng)) { continue; } - + // DivPixel is pixel in overlay pixel coordinates... we need // to transform to screen coordinates so it'll match the canvas // which is continually repositioned to follow the screen. @@ -84,8 +93,8 @@ HeatmapOverlay.prototype.draw = function(){ screenPixel = new google.maps.Point(divPixel.x - leftX, divPixel.y - topY); var roundedPoint = this.pixelTransform(screenPixel); - - d.data.push({ + + d.data.push({ x: roundedPoint.x, y: roundedPoint.y, count: this.latlngs[len].c @@ -96,17 +105,17 @@ HeatmapOverlay.prototype.draw = function(){ } HeatmapOverlay.prototype.pixelTransform = function(p){ - var w = this.heatmap.get("width"), - h = this.heatmap.get("height"); + var w = i3GEO.parametros.w,//this.heatmap.get("width"), + h = i3GEO.parametros.h; //this.heatmap.get("height"); while(p.x < 0){ p.x+=w; } - + while(p.x > w){ p.x-=w; } - + while(p.y < 0){ p.y+=h; } @@ -117,7 +126,7 @@ HeatmapOverlay.prototype.pixelTransform = function(p){ p.x = (p.x >> 0); p.y = (p.y >> 0); - + return p; } @@ -131,32 +140,34 @@ HeatmapOverlay.prototype.setDataSet = function(data){ }, d = data.data, dlen = d.length, - projection = me.getProjection(), + projection = heatmapBarOverlay.getProjection(),//me.getProjection(), latlng, point; me.latlngs = []; - - while(dlen--){ + + while(dlen--){ latlng = new google.maps.LatLng(d[dlen].lat, d[dlen].lng); - - if(!currentBounds.contains(latlng)) { - continue; + + if(!currentBounds.contains(latlng)) { + continue; } me.latlngs.push({latlng: latlng, c: d[dlen].count}); point = me.pixelTransform(projection.fromLatLngToDivPixel(latlng)); mapdata.data.push({x: point.x, y: point.y, count: d[dlen].count}); } - me.heatmap.clear(); - me.heatmap.store.setDataSet(mapdata); + if(me.heatmap){ + me.heatmap.clear(); + me.heatmap.store.setDataSet(mapdata); + } } HeatmapOverlay.prototype.addDataPoint = function(lat, lng, count){ - var projection = this.getProjection(), + var projection = heatmapBarOverlay.getProjection(),//this.getProjection(), latlng = new google.maps.LatLng(lat, lng), point = this.pixelTransform(projection.fromLatLngToDivPixel(latlng)); - + this.heatmap.store.addDataPoint(point.x, point.y, count); this.latlngs.push({ latlng: latlng, c: count }); } diff --git a/pacotes/heatmap/src/heatmap.js b/pacotes/heatmap/src/heatmap.js index f198a7d..02e76b1 100755 --- a/pacotes/heatmap/src/heatmap.js +++ b/pacotes/heatmap/src/heatmap.js @@ -53,7 +53,7 @@ // if count parameter is set increment by count otherwise by 1 data[x][y]+=(arguments.length<3)?1:arguments[2]; - + me.set("data", data); // do we have a new maximum? if(me.max < data[x][y]){ @@ -75,7 +75,7 @@ this.max = obj.max; // if a legend is set, update it heatmap.get("legend") && heatmap.get("legend").update(obj.max); - + if(internal != null && internal){ for(var one in d){ // jump over undefined indexes @@ -85,7 +85,7 @@ if(two === undefined) continue; // if both indexes are defined, push the values into the array - heatmap.drawAlpha(one, two, d[one][two], false); + heatmap.drawAlpha(one, two, d[one][two], false); } } }else{ @@ -162,28 +162,28 @@ config = me.config, title = config.title || "Legend", position = config.position, - offset = config.offset || 10, + offset = config.offset || [10,10], gconfig = config.gradient, labelsEl = document.createElement("ul"), labelsHtml = "", grad, element, gradient, positionCss = ""; - + me.processGradientObject(); - + // Positioning // top or bottom if(position.indexOf('t') > -1){ - positionCss += 'top:'+offset+'px;'; + positionCss += 'top:'+offset[1]+'px;'; }else{ - positionCss += 'bottom:'+offset+'px;'; + positionCss += 'bottom:'+offset[1]+'px;'; } // left or right if(position.indexOf('l') > -1){ - positionCss += 'left:'+offset+'px;'; + positionCss += 'left:'+offset[0]+'px;'; }else{ - positionCss += 'right:'+offset+'px;'; + positionCss += 'right:'+offset[0]+'px;'; } element = document.createElement("div"); @@ -191,7 +191,7 @@ element.innerHTML = "

"+title+"

"; // create gradient in canvas labelsEl.style.cssText = "position:relative;font-size:12px;display:block;list-style:none;list-style-type:none;margin:0;height:15px;"; - + // create gradient element gradient = document.createElement("div"); @@ -199,7 +199,7 @@ element.appendChild(labelsEl); element.appendChild(gradient); - + me.set("element", element); me.set("labelsEl", labelsEl); @@ -244,7 +244,7 @@ ctx.fillRect(0,5,256,10); ctx.strokeStyle = "black"; ctx.beginPath(); - + for(var i = 0; i < length; i++){ ctx.moveTo(((1/(length-1)*i*256) >> 0)+.5, 0); ctx.lineTo(((1/(length-1)*i*256) >> 0)+.5, (i==0)?15:5); @@ -253,7 +253,7 @@ ctx.lineTo(255.5, 15); ctx.moveTo(255.5, 4.5); ctx.lineTo(0, 4.5); - + ctx.stroke(); // we re-use the context for measuring the legends label widths @@ -283,7 +283,7 @@ offset *= 2; } labelsHtml += '
  • '+labelText+'
  • '; - } + } labels.innerHTML = labelsHtml; } }; @@ -351,7 +351,7 @@ legendCfg.gradient = me.get("gradient"); me.set("legend", new legend(legendCfg)); } - + }, resize: function () { var me = this, @@ -372,7 +372,7 @@ actx = acanvas.getContext("2d"), element = me.get("element"); - + me.initColorPalette(); me.set("canvas", canvas); @@ -382,7 +382,7 @@ me.resize(); canvas.style.cssText = acanvas.style.cssText = "position:absolute;top:0;left:0;z-index:10000000;"; - + if(!me.get("visible")) canvas.style.display = "none"; @@ -390,14 +390,14 @@ if(me.get("legend")){ element.appendChild(me.get("legend").getElement()); } - + // debugging purposes only if(me.get("debug")) document.body.appendChild(acanvas); - - actx.shadowOffsetX = 15000; - actx.shadowOffsetY = 15000; - actx.shadowBlur = 15; + + actx.shadowOffsetX = 15000; + actx.shadowOffsetY = 15000; + actx.shadowBlur = 15; }, initColorPalette: function(){ @@ -420,7 +420,7 @@ ctx.putImageData(testData, 0, 0); testData = ctx.getImageData(0,0,1,1); me.set("premultiplyAlpha", (testData.data[0] < 60 || testData.data[0] > 70)); - + for(var x in gradient){ grad.addColorStop(x, gradient[x]); } @@ -465,9 +465,9 @@ palette = me.get("gradient"), opacity = me.get("opacity"), bounds = me.get("bounds"), - left, top, bottom, right, + left, top, bottom, right, image, imageData, length, alpha, offset, finalAlpha; - + if(x != null && y != null){ if(x+x2>width){ x=width-x2; @@ -506,7 +506,7 @@ bottom = height; }else{ bottom = bounds['b']; - } + } } image = actx.getImageData(left, top, right-left, bottom-top); @@ -528,7 +528,7 @@ imageData[i-3]=palette[offset]; imageData[i-2]=palette[offset+1]; imageData[i-1]=palette[offset+2]; - + if (premultiplyAlpha) { // To fix browsers that premultiply incorrectly, we'll pass in a value scaled // appropriately so when the multiplication happens the correct value will result. @@ -536,7 +536,7 @@ imageData[i-2] /= 255/finalAlpha; imageData[i-1] /= 255/finalAlpha; } - + // we want the heatmap to have a gradient from transparent to the colors // as long as alpha is lower than the defined opacity (maximum), we'll use the alpha value imageData[i] = finalAlpha; @@ -558,9 +558,9 @@ ctx.shadowColor = ('rgba(0,0,0,'+((count)?(count/me.store.max):'0.1')+')'); - ctx.shadowOffsetX = 15000; - ctx.shadowOffsetY = 15000; - ctx.shadowBlur = 15; + ctx.shadowOffsetX = 15000; + ctx.shadowOffsetY = 15000; + ctx.shadowBlur = 15; ctx.beginPath(); ctx.arc(x - 15000, y - 15000, radius, 0, Math.PI * 2, true); @@ -621,7 +621,7 @@ return { create: function(config){ return new heatmap(config); - }, + }, util: { mousePosition: function(ev){ // this doesn't work right -- libgit2 0.21.2