var mapPanel;
var oUtilizador = "";
var oEmail = "";
var storeOcupacoes;
Ext.onReady(function() {
Ext.QuickTips.init();
// pink tile avoidance
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
// make OL compute scale according to WMS spec
OpenLayers.DOTS_PER_INCH = 25.4 / 0.28;
// Neste exemplo, os layers provêem todos da mesma origem, pelo que o proxy não é utilizado
// No entanto, como queremos forçar o uso do proxy, o mesmo é usado precendento os pedidos todos...
// OpenLayers.ProxyHost = "http://84.91.3.11/cgi-bin/proxy.cgi?url=";
// OpenLayers.ProxyHost = "http://localhost/cgi-bin/proxy.original.cgi?url=";
// COm este proxy, funciona o WFS, mas o GWC deixa de dar....
// OpenLayers.ProxyHost = "http://webgis.di.uminho.pt/cgi-bin/proxy.original.cgi?url=";
OpenLayers.ProxyHost = "";
var GeoLayer = Ext.data.Record.create([{
name : 'id',
type : 'int'
}, {
name : 'ord',
type : 'int'
}/*, {
name : 'nome',
type : 'string'
}*/ , {
name : 'titulo',
type : 'string'
}, {
name : 'layer',
type : 'string'
}, {
name : 'grupo',
type : 'string'
}, {
name : 'url',
type : 'string'
}, {
name : 'tipo',
type : 'string'
}, {
name : 'srid',
type : 'int'
}, {
name : 'estilo',
type : 'string'
}, {
name : 'qtip',
type : 'string'
}, {
name : 'singletile',
type : 'boolean'
}, {
name : 'activo',
type : 'boolean'
}, {
name : 'regulamento',
type : 'string'
}, {
name : 'observacoes',
type : 'string'
}, {
name : 'visivel',
type : 'boolean'
}, {
name : 'dataalteracao',
type : 'date',
dateFormat : 'c' // impecável: a data vem no formato ISO8601
}]);
var storeLayers = new Ext.data.JsonStore({
url : 'json_layers.php',
root : 'camadas',
idProperty : 'id',
fields : GeoLayer,
listeners : {
'load' : function() {
storeLayers.each(function(r) {
tip = '';
if (r.data['qtip'] == '') {
// tipURL = 'http://localhost:8080' + '/geoserver/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=' + r.data['layer'] + '&legend_options=forceLabels:on';
tipURL = '/geoserver/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=' + r.data['layer'] + '&legend_options=forceLabels:on';
// tipURL = OpenLayers.ProxyHost + r.data['url'] + 'REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=' + r.data['layer'] + '&legend_options=forceLabels:on';
// tipURL = r.data['url'] + 'REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=' + r.data['layer'] + '&legend_options=forceLabels:on';
// tipURL = OpenLayers.ProxyHost + encodeURIComponent(tipURL); // http://84.91.3.11/geoserver/gwc/service/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=pdm_condicionantes_etrs89:ren_etrs89&legend_options=forceLabels:onhttp%3A//84.91.3.11/geoserver/gwc/service/wms%3FREQUEST%3DGetLegendGraphic%26VERSION%3D1.0.0%26FORMAT%3Dimage/png%26LAYER%3Dpdm_condicionantes_etrs89%3Aren_etrs89%26legend_options%3DforceLabels%3Aon
// tipURL = OpenLayers.ProxyHost + tipURL; // http://84.91.3.11/geoserver/gwc/service/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=pdm_condicionantes_etrs89:ren_etrs89&legend_options=forceLabels:onhttp%3A//84.91.3.11/geoserver/gwc/service/wms%3FREQUEST%3DGetLegendGraphic%26VERSION%3D1.0.0%26FORMAT%3Dimage/png%26LAYER%3Dpdm_condicionantes_etrs89%3Aren_etrs89%26legend_options%3DforceLabels%3Aon
tip = r.data['titulo'] + '
' + '';
// tip = r.data['titulo'] + '
' + '';
} else {
tip = r.data['qtip'];
}
map.addLayer(new OpenLayers.Layer.WMS(r.data['titulo'], OpenLayers.ProxyHost + r.data['url'], {
layers : r.data['layer'],
format : format,
transparent : true
}, {
singleTile : r.data['singletile'],
ratio : 1,
isBaseLayer : false,
visibility : r.data['visivel'],
group : r.data['grupo'],
iconCls : "xnd-icon",
icon : r.data['tipo'],
qtip : tip
}));
// console.log('Adicionado o layer ' + r.data['layer']);
});
Ext.getCmp('tree').setTitle(storeLayers.getCount() + ' Camadas', '');
}
}
});
storeLayers.load();
var bounds = new OpenLayers.Bounds(-119191.40749999962, -300404.80399999936, 162129.08110000013, 276083.7674000006);
var options = {
maxExtent : bounds,
// scales : [100000, 500000, 250000, 100000, 50000, 25000, 10000, 5000, 1000, 500],
resolutions : [140.0, 70.0, 27.999999999999996, 13.999999999999998, 6.999999999999999, 2.8, 1.4, 0.27999999999999997, 0.13999999999999999],
// maxResolution : "auto",
projection : "EPSG:3763", // string
displayProjection : new OpenLayers.Projection("EPSG:3763"),
title : 'Mapa',
units : 'm',
allOverlays : true
};
map = new OpenLayers.Map(options);
map.addControl(new OpenLayers.Control.ScaleLine());
map.addControl(new OpenLayers.Control.Scale());
var panel = new OpenLayers.Control.Panel({
div : OpenLayers.Util.getElement('botoesEdicao')
});
var navigate = new OpenLayers.Control.Navigation({
title : "Pan Map"
});
var victor = new OpenLayers.Layer.Vector("Editable Vectors", {
displayInLayerSwitcher : false
});
var drawPoint = new OpenLayers.Control.DrawFeature(victor, OpenLayers.Handler.Point, {
title : "Marca pontos",
displayClass : 'olControlDrawFeaturePoint',
handlerOptions : {
multi : true
}
});
var drawPath = new OpenLayers.Control.DrawFeature(victor, OpenLayers.Handler.Path, {
title : "Traça linhas",
displayClass : "olControlDrawFeaturePath",
handlerOptions : {
multi : true
}
});
var drawPolygon = new OpenLayers.Control.DrawFeature(victor, OpenLayers.Handler.Polygon, {
title : "Desenha polígonos",
displayClass : "olControlDrawFeaturePolygon",
handlerOptions : {
multi : true
}
});
var drag = new OpenLayers.Control.DragFeature(victor, {
title : "Move",
displayClass : "olControlNavigation"
});
var edit = new OpenLayers.Control.ModifyFeature(victor, {
title : "Altera a geometria",
displayClass : "olControlModifyFeature"
});
panel.addControls([edit, drag, drawPolygon, drawPath, drawPoint]);
map.addLayers([victor]);
panel.defaultControl = navigate;
map.addControl(panel);
format = 'image/png';
// http://84.91.3.13/cgi-bin/tilecache/tilecache.cgi?LAYERS=cartobase&SERVICE=WMS&BBOX=-36002.0,89990.0,-8000.0,115000.0
// http://192.254.254.3/cgi-bin/tilecache/tilecache.cgi?LAYERS=cartobase&SERVICE=WMS&BBOX=-36002.0,89990.0,-8000.0,115000.0
// var vecLayer = new OpenLayers.Layer.Vector("Ocupações");
var context = {
getColor : function(feature) {
if (feature.attributes.extra == 'McDrive:') {
return 'red';
}
if (feature.attributes.extra != '') {
return 'orange';
}
return 'green';
}
};
var template = {
cursor : "pointer",
fillOpacity : 0.5,
fillColor : "${getColor}",
pointRadius : 5,
strokeWidth : 1,
strokeOpacity : 1,
strokeColor : "${getColor}",
graphicName : "triangle"
};
var style = new OpenLayers.Style(template, {
context : context
});
function saveSuccess(event) {
console.log('Changes saved');
}
function saveFail(event) {
console.log('Error! Changes not saved');
}
var saveStrategy = new OpenLayers.Strategy.Save();
saveStrategy.events.register('success', null, saveSuccess);
saveStrategy.events.register('fail', null, saveFail);
var wfs = new OpenLayers.Layer.Vector("Ocupações", {
styleMap : new OpenLayers.StyleMap({
'default' : style
}),
strategies : [new OpenLayers.Strategy.Fixed(), saveStrategy],
protocol : new OpenLayers.Protocol.WFS({
version : "1.1.0",
srsName : "EPSG:3763",
featurePrefix : "topp",
// url : "http://webgis.di.uminho.pt/cgi-bin/proxy.original.cgi?url=http://webgis.di.uminho.pt:8080/geoserver/wfs",
// url : "http://webgis.di.uminho.pt/geoserver/wfs",
url : "http://localhost/geoserver/wfs",
featureType : "ocupacao",
featureNS : "http://www.openplans.org/topp",
geometryName : "wkb_geometry",
// schema : "http://webgis.di.uminho.pt/cgi-bin/proxy.original.cgi?url=http://webgis.di.uminho.pt:8080/geoserver/topp/wfs?service=WFS&version=1.0.0&request=DescribeFeatureType&typeName=topp:ocupacao"
// schema : "http://webgis.di.uminho.pt/geoserver/topp/wfs?service=WFS&version=1.0.0&request=DescribeFeatureType&typeName=topp:ocupacao"
schema : "http://localhost/geoserver/topp/wfs?service=WFS&version=1.0.0&request=DescribeFeatureType&typeName=topp:ocupacao"
})
});
// map.addLayers([wfs]);
var mostraDados = function(e) {
// console.log('mostraDados' + e.feature.attributes["fotografia"]);
if ( typeof (e.feature.attributes["fotografia"]) != "undefined") {
createPopup(e.feature);
}
};
var limpaDados = function(e) {
var comWin = Ext.getCmp('pipocas');
comWin.close();
// console.log('limpaDados');
};
function createPopup(feature) {
var popup = new GeoExt.Popup({
id : 'pipocas',
title : "Ocupação " + feature.fid,
location : feature,
width : 200,
html : "
",
// html : "" + thumbLink(feature.attributes["fotografia"]) + "
",
collapsible : true,
location : feature
});
popup.show();
}
var highlightCtrl = new OpenLayers.Control.SelectFeature(wfs, {
hover : true,
highlightOnly : true,
eventListeners : {
beforefeaturehighlighted : mostraDados,
featureunhighlighted : limpaDados
}
});
map.addControl(highlightCtrl);
// activar só depois de ler o store...
/*
wfs.events.on({
'beforefeatureadded' : function() {
console.log('wfs beforefeatureadded');
},
'featureadded' : function() {
console.log('wfs featureadded');
}
});
*/
var distancia = new OpenLayers.Control.Measure(OpenLayers.Handler.Path, {
eventListeners : {
measure : function(evt) {
alert("Distância: " + evt.measure + evt.units);
}
}
});
var area = new OpenLayers.Control.Measure(OpenLayers.Handler.Polygon, {
eventListeners : {
measure : function(evt) {
alert("Área: " + evt.measure + evt.units);
}
}
});
// map.addControl(distancia);
// map.addControl(area);
var toggleGroup = "measure controls";
var buttonDistancia = new Ext.Toolbar.Button({
text : 'Distância',
enableToggle : true,
toggleGroup : toggleGroup,
listeners : {
toggle : function(button, pressed) {
// console.log("User toggled the '" + button.text + "' button: " + ( pressed ? 'on' : 'off'));
if (pressed) {
// console.log('Vai activar ' + this.text);
distancia.activate();
} else {
// console.log('Vai desactivar ' + this.text);
distancia.deactivate();
}
}
}
});
var buttonArea = new Ext.Toolbar.Button({
text : 'Área',
enableToggle : true,
toggleGroup : toggleGroup,
listeners : {
toggle : function(button, pressed) {
// console.log("User toggled the '" + button.text + "' button: " + ( pressed ? 'on' : 'off'));
if (pressed) {
// console.log('Vai activar ' + this.text);
area.activate();
} else {
// console.log('Vai desactivar ' + this.text);
area.deactivate();
}
}
}
});
map.addControl(new OpenLayers.Control.Attribution());
// map.addControl(new OpenLayers.Control.MousePosition( {id: "coordenadas_rato", prefix: "ETRS89-TM06 ", displayProjection: map.baseLayer.projection, numDigits: 0} ));
var posicaoRato = new OpenLayers.Control.MousePosition({
id : "coordenadas_rato"
});
map.addControl(posicaoRato);
/*
informacoes = new OpenLayers.Control.WMSGetFeatureInfo({
url : 'http://webgis.di.uminho.pt/geoserver/wms',
title : 'Identify features by clicking',
layers : ["topp:margem"],
queryVisible : true,
infoFormat : 'application/vnd.ogc.gml',
eventListeners : {
getfeatureinfo : function(event) {
map.addPopup(
new OpenLayers.Popup.FramedCloud("chicken",
map.getLonLatFromPixel(event.xy),
null,
GenPopText(event), null, true));
}
}
});
*/
// https://getsatisfaction.com/opengeo/topics/error_in_wmsgetfeatureinfo#reply_2612983
informacoes = new OpenLayers.Control.WMSGetFeatureInfo({
autoActivate : true,
infoFormat : "application/vnd.ogc.gml",
url : "http://webgis.di.uminho.pt/geoserver/wms",
layerUrls : ["http://webgis.di.uminho.pt/geoserver/gwc/service/wms"],
maxFeatures : 3,
queryVisible : true,
eventListeners : {
"getfeatureinfo" : function(e) {
var items = [];
var fotos = [];
Ext.each(e.features, function(feature) {
// pode ser algo do género...
// se for foto, acrescenta às fotos
// se for outra coisa, acrescenta aos items
// console.debug(feature);
if (feature.gml.featureType === 'geofotos') {
fotos.push(new Ext.Panel({
title : feature.fid,
// cls: 'look',
// falta agora por um thumbnail e com um clique salta para a resolução máqima
html : '',
}));
} else {
items.push({
xtype : "propertygrid",
title : feature.fid,
source : feature.attributes
/*
, customRenderers : {
name : function(v) {
console.log(v);
return '';
},
link2_href : function(v) {
console.log(v);
return '';
}
}
*/
});
}
// console.debug(items);
// console.log(items.length);
});
// console.log('Fotos = ' + fotos.length);
// console.log('Items = ' + items.length);
var painelDetalhes = Ext.getCmp('detalhes');
// console.log('Paineis existenes: ' + painelDetalhes.items.items.length);
painelDetalhes.removeAll();
painelDetalhes.doLayout();
// panel.remove(id);
if (fotos.length > 0) {
/*
new GeoExt.Popup({
title : "Fotografias",
width : 200,
height : 200,
layout : "accordion",
map : mapPanel,
location : e.xy,
items : fotos
}).show();
*/
painelDetalhes.add(fotos);
painelDetalhes.doLayout();
tabsGestao.activate(3);
}
if (items.length > 0) {
/*
new GeoExt.Popup({
title : "Informações detalhadas",
width : 200,
height : 200,
layout : "accordion",
map : mapPanel,
location : e.xy,
items : items
}).show();
*/
painelDetalhes.add(items);
painelDetalhes.doLayout();
tabsGestao.activate(3);
}
// painelDetalhes.doLayout();
}
}
});
// console.debug(informacoes);
map.addControl(informacoes);
// informacoes.activate();
// highlightCtrl.activate();
var displayProjectionSelectorCombo = new GeoExt.ux.DisplayProjectionSelectorCombo({
map : map,
controls : [posicaoRato],
updateMapDisplayProjection : true,
projections : ['EPSG:3763', 'EPSG:4326', 'EPSG:900913', 'EPSG:27492', 'EPSG:20790'],
width : 200
});
/*
var zoomin_action = new GeoExt.Action({
text : "Zoom In",
control : new OpenLayers.Control.ZoomBox({
alwaysZoom : true
}),
map : map,
// button options
toggleGroup : "tools",
allowDepress : false,
tooltip : "Zoom In",
// check item options
group : "tools"
});
*/
var nav = new OpenLayers.Control.NavigationHistory();
map.addControl(nav);
// panel.addControls([nav.next, nav.previous]);
// map.addControl(panel);
var zoom_next = new GeoExt.Action({
text : "Seguinte",
control : nav.next,
toggleGroup : toggleGroup,
enableToggle : true,
map : map,
tooltip : "Vista Seguinte"
});
var zoom_previous = new GeoExt.Action({
text : "Anterior",
control : nav.previous,
toggleGroup : toggleGroup,
enableToggle : true,
map : map,
tooltip : "Vista Anterior"
});
var scaleStore = new GeoExt.data.ScaleStore({
map : map
});
// console.debug(scaleStore);
var zoomSelector = new Ext.form.ComboBox({
store : scaleStore,
emptyText : "Escala",
tpl : '1 : {[Math.round(values.scale)]}
',
editable : false,
triggerAction : 'all', // needed so that the combo box doesn't filter by its current content
mode : 'local', // keep the combo box from forcing a lot of unneeded data refreshes
width : 80
});
zoomSelector.on('select', function(combo, record, index) {
map.zoomTo(record.data.level);
}, this);
map.events.register('zoomend', this, function() {
var scale = scaleStore.queryBy(function(record) {
return this.map.getZoom() == record.data.level;
});
if (scale.length > 0) {
scale = scale.items[0];
zoomSelector.setValue("1 : " + Math.round(scale.data.scale));
} else {
if (!zoomSelector.rendered)
return;
zoomSelector.clearValue();
}
});
/*
var zoom_max = new GeoExt.Action({
control : new OpenLayers.Control.ZoomToMaxExtent(),
map : map,
text : "Ver tudo",
tooltip : "Ver todo o município"
});
*/
var storeMunicipios = new Ext.data.SimpleStore({
fields : ['value', 'text', 'bbox'],
data : [['1', 'CAMINHA', new OpenLayers.Bounds(-61791, 234832, -44596, 249969)], ['2', 'VIANA DO CASTELO', new OpenLayers.Bounds(-62207, 215437, -42363, 240207)], ['3', 'ESPOSENDE', new OpenLayers.Bounds(-56552, 199831, -47389, 217466)], ['4', 'PÓVOA DE VARZIM', new OpenLayers.Bounds(-54840, 188542, -38261, 200494.25)], ['5', 'VILA DO CONDE', new OpenLayers.Bounds(-53112, 176401, -39968, 195312)], ['6', 'MATOSINHOS', new OpenLayers.Bounds(-49964, 167066, -38786, 178367)], ['7', 'VILA NOVA DE GAIA', new OpenLayers.Bounds(-45540, 148978, -26534, 164378)], ['8', 'ESPINHO', new OpenLayers.Bounds(-43774, 144096, -38737, 150847.171875)]]
});
// console.debug(scaleStore);
var municipioSelector = new Ext.form.ComboBox({
store : storeMunicipios,
emptyText : "Município",
tpl : '{[values.text]}
',
editable : false,
triggerAction : 'all', // needed so that the combo box doesn't filter by its current content
mode : 'local', // keep the combo box from forcing a lot of unneeded data refreshes
width : 120
});
municipioSelector.on('select', function(combo, record, index) {
map.zoomToExtent(record.data.bbox);
}, this);
var storePOA = new Ext.data.JsonStore({
root : 'features',
totalProperty : 'total',
idProperty : 'ogc_fid',
remoteSort : false,
baseParams : {
tabela : 'albufeiras.poa'
},
fields : ['ogc_fid', 'nome', 'st_xmin', 'st_ymin', 'st_xmax', 'st_ymax'],
proxy : new Ext.data.HttpProxy({
url : 'json_boundingbox.php'
}),
autoLoad : true
});
var poaSelector = new Ext.form.ComboBox({
store : storePOA,
emptyText : "Albufeiras",
tpl : '{[values.nome]}
',
editable : false,
triggerAction : 'all', // needed so that the combo box doesn't filter by its current content
mode : 'local', // keep the combo box from forcing a lot of unneeded data refreshes
width : 160
});
poaSelector.on('select', function(combo, record, index) {
map.zoomToExtent(new OpenLayers.Bounds(record.data.st_xmin, record.data.st_ymin, record.data.st_xmax, record.data.st_ymax));
}, this);
// create map panel
mapPanel = new GeoExt.MapPanel({
id : "mapa",
title : "Mapa",
region : "center",
// height: 400,
// width: 600,
map : map,
// center : new OpenLayers.LonLat(-7.849731, 39.639538).transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:3763")),
center : new OpenLayers.LonLat(-24500, 209000),
zoom : 5,
tbar : ['->', displayProjectionSelectorCombo, /* buttonDistancia, buttonArea, */ zoom_previous, zoom_next],
bbar : [zoomSelector, /* municipioSelector, poaSelector*/ ]
});
Ext.QuickTips.init();
// turn on validation errors beside the field globally
Ext.form.Field.prototype.msgTarget = 'side';
//make a new form
// var form_user = new Ext.form.FormPanel({
// (...)
////////////////////////////////////////////////
var layerSelecionado = null;
var slider = new GeoExt.LayerOpacitySlider({
// layer: wms,
// aggressive : true,
width : 100,
disabled : true,
// isFormField : true,
// inverse : true, // não funciona se inverter; dá erro no browser
// fieldLabel : "opacity",
// renderTo: "slider",
plugins : new GeoExt.LayerOpacitySliderTip({
template : 'Transparência: {opacity}%
'
}),
listeners : {
change : function(slider, value) {
/*
var node = tree.getSelectionModel().getSelectedNode();
if(node) {
node.layer.setOpacity(value / 100.0); // / 100.0
}
*/
if (layerSelecionado) {
layerSelecionado.setOpacity(value / 100.0);
}
}
}
});
var LayerNodeUI = Ext.extend(GeoExt.tree.LayerNodeUI, new GeoExt.tree.TreeNodeUIEventMixin());
var buttonObject = new Ext.Button({
id : 'associar',
text : "Associar",
visible : false,
handler : function() {
if (layerSelecionado) {
if (( layerSelecionado instanceof OpenLayers.Layer) && layerSelecionado.getVisibility()) {
slider.enable();
slider.setLayer(layerSelecionado);
} else {
layerSelecionado = null;
slider.disable();
}
} else {
layerSelecionado = null;
slider.disable();
}
}
});
var tree = new GeoExt.ux.tree.LayerTreeBuilder({
id : 'tree',
title : 'Camadas',
// region: "east",
// width: 250,
autoScroll : true,
enableDD : true,
rootVisible : false,
lines : false,
// widget custom properties
wmsLegendNodes : false,
vectorLegendNodes : false,
listeners : {
click : function(treenode, event) {
layerSelecionado = treenode.layer;
buttonObject.onClick(event);
// var node = tree.getSelectionModel().getSelectedNode(); // Urh... ainda está o anterior
}
},
bbar : [/* {
text: "Regulamento",
handler: function() {
var node = tree.getSelectionModel().getSelectedNode();
if(node) {
alert("Vai aceder ao regulamento da camada " + node.text + ".");
} else {
alert("Tem que ter um layer selecionado.");
}
}
},{
text: "Imprimir",
handler: function() {
var node = tree.getSelectionModel().getSelectedNode();
if(node) {
alert("Vai imprimir a camada " + node.text + ".");
} else {
alert("Tem que ter um layer selecionado.");
}
}
}, */
// 1 buttonNext = new Ext.Button({text:'Touch me'});
{
text : "Remover",
handler : function() {
var node = tree.getSelectionModel().getSelectedNode();
if (node) {
map.removeLayer(node.layer);
}
}
}, {
text : "Exportar para KML",
handler : function() {
var node = tree.getSelectionModel().getSelectedNode();
if (node) {
// http://webgis.di.uminho.pt/geoserver/topp/wms/kml?layers=topp:jurisdicao
location.href = OpenLayers.ProxyHost + 'http://webgis.di.uminho.pt' + '/geoserver/kml?layers=' + node.layer.params['LAYERS'];
} else {
alert("Tem que ter um layer selecionado.");
}
}
}, slider]
});
/*
var pParticipacao = new Ext.Panel({
xtype : 'panel',
id : 'idpParticipacao',
border : false,
title : 'Participação',
collapsible : true,
collapsed : false,
items : [form_user, form_participacao, form_logout],
});
*/
var myData = [['', 'Pontos'], ['', 'Linhas'], ['', 'Áreas'], ['', 'Pontos e Áreas'], ['', 'Pontos e Linhas'], ['', 'Pontos, Linhas e Áreas'], ['', 'Pontos, Linhas e Áreas (na mesma cor)'], ['', 'Superfície (raster)']];
var store = new Ext.data.SimpleStore({
fields : ['icone', 'significado']
});
store.loadData(myData);
var grid = new Ext.grid.GridPanel({
store : store,
// width: 280,
// stripeRows: true,
// autoExpandColumn: 'significado',
columns : [{
header : "Símbolo",
width : 68,
dataIndex : 'icone'
}, {
id : 'significado',
header : "Significado",
width : 215,
dataIndex : 'significado'
}]
});
wfs.events.on({
"featureselected" : function(e) {
// console.log('Toca a actualizar o form');
// console.debug(e.feature);
gridForm.getForm().loadRecord(e.feature);
},
"scope" : wfs
});
storeOcupacoes = new GeoExt.data.FeatureStore({
layer : wfs,
fields : [// string, int, float
{
name : 'ogc_fid',
type : 'int'
}, {
name : 'pp',
type : 'string'
}, {
name : 'praia',
type : 'string'
}, {
name : 'proc_ant',
type : 'string'
}, {
name : 'proc',
type : 'string'
}, {
name : 'lic_num',
type : 'string'
}, {
name : 'titular',
type : 'string'
}, {
name : 'a_cob',
type : 'float'
}, {
name : 'a_total',
type : 'float'
}, {
name : 'prev_pooc',
type : 'string'
}, {
name : 'adap_pooc',
type : 'string'
}, {
name : 'pt_situac',
type : 'string'
}, {
name : 'data_lic',
type : 'string'
// type: 'date',
// dateFormat: 'n/j h:ia'
}, {
name : 'lic_val',
type : 'string'
}, {
name : 'tipoocupacao',
type : 'int'
}, {
name : 'tipodominio',
type : 'int'
}, {
name : 'nif',
type : 'string'
}, {
name : 'fotografia',
type : 'string',
tpl : ''
}, {
name : 'observacoes',
type : 'string'
}, {
name : 'contacto',
type : 'string'
}, {
name : 'morada',
type : 'string'
}]
});
var gridOcupacoes = new Ext.grid.GridPanel({
id : 'gridOcupacoes',
title : "Tabela das Ocupações",
autoWidth : true,
// autoHeight: true,
height : 200,
store : storeOcupacoes,
viewConfig : {
forceFit : true
},
/*
+ ogc_fid integer NOT NULL DEFAULT nextval('ocupacoes_ogc_fid_seq'::regclass),
wkb_geometry geometry(Point,3763),
concelho character varying(254),
ordem_geo_ numeric(16,6),
+ pp character varying(254),
+ praia character varying(254),
+ proc_ant character varying(254),
+ proc character varying(254),
+ lic_num character varying(254),
coord_m numeric(16,6),
coord_p numeric(16,6),
+ titular character varying(254),
+ a_cob numeric(16,6),
a_descob numeric(16,6),
a_praia numeric(16,6),
+ a_total numeric(16,6),
+ prev_pooc character varying(254),
+ adap_pooc character varying(254),
+ pt_situac character varying(254),
+ data_lic character varying(254),
+ lic_val character varying(254),
+ tipoocupacao integer,
+ tipodominio integer,
+ nif character varying(9),
+ fotografia character varying(255),
+ observacoes character varying(255),
+ contacto character varying(32),
+ morada character varying(140),
*/
columns : [{
header : "ID",
dataIndex : "ogc_fid"
}, {
header : "Processo",
dataIndex : "proc"
}, {
header : "Proc. Ant.",
dataIndex : "proc_ant",
hidden : true
}, {
header : "Lic. Nº",
dataIndex : "lic_num"
}, {
header : "Titular",
dataIndex : "titular"
}, {
header : "NIF",
dataIndex : "nif"
}, {
header : "Morada",
dataIndex : "morada",
hidden : true
}, {
header : "Contacto",
dataIndex : "contacto",
hidden : true
}, {
header : "Tipo Ocupação",
dataIndex : "tipoocupacao",
hidden : true
}, {
header : "Domínio",
// width: 100,
dataIndex : "tipodominio",
hidden : true
}],
sm : new GeoExt.grid.FeatureSelectionModel({
singleSelect : true,
autoPanMapOnSelection : true
}),
selType : 'featuremodel',
listeners : {
'rowclick' : {
'fn' : function(grid, index, evt) {
var r = grid.getStore().getAt(index);
gridForm.getForm().loadRecord(r);
var feature = r.get('feature');
var geometry = feature.geometry;
var center = geometry.getBounds().getCenterLonLat();
map.setCenter(center, 6);
// console.debug(r);
// console.log(r.get('nif'));
pesquisaContribuintes.reset();
pesquisaContribuintes.setValue(r.get('nif'));
pesquisaContribuintes.onTrigger2Click();
// console.log(r.get('lic_num'));
pesquisaTitulos.reset();
pesquisaTitulos.setValue(r.get('lic_num'));
pesquisaTitulos.onTrigger2Click();
}
}
}
});
// http://workshops.opengeo.org/geoext/wfs/editing.html
var storeContribuintes = new Ext.data.JsonStore({
root : 'contribuintes',
totalProperty : 'total',
idProperty : 'nif',
remoteSort : true,
baseParams : {
limit : 25
},
sortInfo : {
"field" : "nome",
"direction" : "ASC"
},
fields : ['nif', 'nome', 'morada', 'localidade', 'codpostal', 'codpostallocal', 'numcc', 'datanascimento', 'email', 'telefone', 'telemovel', 'obs'],
proxy : new Ext.data.HttpProxy({
url : 'json_contrib.php'
})
});
storeContribuintes.setDefaultSort('nome', 'asc');
var pesquisaContribuintes = new Ext.ux.form.SearchField({
store : storeContribuintes,
width : 160
});
var gridContribuintes = new Ext.grid.GridPanel({
// width: 540,
height : 250,
title : 'Contribuintes',
store : storeContribuintes,
region : 'south',
// trackMouseOver: false,
// disableSelection: true,
loadMask : true,
viewConfig : {
forceFit : true
}, // this is the option which will force the grid to the width of the containing panel
// grid columns
columns : [{
id : 'nif', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
header : "NIF",
dataIndex : 'nif',
width : 60,
// renderer: renderTopic,
sortable : true
}, {
header : "Nome",
dataIndex : 'nome',
width : 200,
// hidden: true,
sortable : true
}, {
header : "Morada",
dataIndex : 'morada',
width : 40,
sortable : true
}, {
id : 'codpostal',
header : "C. P.",
dataIndex : 'codpostal',
width : 60,
sortable : true
}],
// 'nif', 'nome', 'morada', 'localidade', 'codpostal', 'codpostallocal', 'numcc', 'datanascimento', 'email', 'telefone', 'telemovel', 'obs'
tbar : ['Pesquisar: ', ' ', pesquisaContribuintes],
bbar : new Ext.PagingToolbar({
pageSize : 25,
store : storeContribuintes,
displayInfo : true,
displayMsg : 'Contribuintes {0} a {1} de {2}',
emptyMsg : "Sem contribuintes para apresentar"
}),
sm : new GeoExt.grid.FeatureSelectionModel({
singleSelect : true,
listeners : {
rowselect : function(sm, row, rec) {
if (gridRequerimentos.getSelectionModel().hasSelection()) {
gridRequerimentos.getSelectionModel().clearSelections();
}
var contribuinte = rec.data.numero;
// r.data['numero'];
pesquisaContribuintes.reset();
// pesquisaRequerimentos.setValue(contribuinte);
// pesquisaRequerimentos.onTrigger2Click();
}
}
})
});
storeContribuintes.load({
params : {
start : 0,
limit : 25
}
});
var storeTitulos = new Ext.data.JsonStore({
root : 'titulos',
totalProperty : 'total',
idProperty : 'id',
remoteSort : true,
baseParams : {
limit : 25
},
sortInfo : {
"field" : "nome",
"direction" : "ASC"
},
// dateFormat utilizado para o parsing...
fields : ['titulo', 'utilizacoes', 'nif', {
name : 'data_inicio_validade',
type : 'date',
dateFormat : 'Y-m-d'
}, {
name : 'data_fim_validade',
type : 'date',
dateFormat : 'Y-m-d'
}, 'situacao_titulo', 'tipo_titulo', 'bacia', 'tipo_utilizacao', 'tipoocupacao'],
proxy : new Ext.data.HttpProxy({
url : 'json_titulo.php'
})
});
storeTitulos.setDefaultSort('data_inicio_validade', 'desc');
var pesquisaTitulos = new Ext.ux.form.SearchField({
store : storeTitulos
// width: 160
});
var gridTitulos = new Ext.grid.GridPanel({
// width: 540,
height : 200,
title : 'Títulos de utilização',
store : storeTitulos,
region : 'south',
// trackMouseOver: false,
// disableSelection: true,
loadMask : true,
viewConfig : {
forceFit : true
}, // this is the option which will force the grid to the width of the containing panel
// grid columns
columns : [{
id : 'titulo', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
header : "Título",
dataIndex : 'titulo',
width : 120,
// renderer: renderTopic,
sortable : true
}, {
header : "Utilizações",
dataIndex : 'utilizacoes',
width : 80,
// hidden: true,
sortable : true
}, {
header : "Início de Validade",
dataIndex : 'data_inicio_validade',
width : 80,
sortable : true,
// xtype : 'datecolumn',
renderer : Ext.util.Format.dateRenderer("Y-m-d")
}, {
header : "Fim de Validade",
dataIndex : 'data_fim_validade',
width : 80,
sortable : true,
// xtype : 'datecolumn', // Não se pode usar o xtype com o renderer
renderer : Ext.util.Format.dateRenderer("Y-m-d")
}],
tbar : ['Pesquisar: ', ' ', pesquisaTitulos],
bbar : new Ext.PagingToolbar({
pageSize : 25,
store : storeTitulos,
displayInfo : true,
displayMsg : 'Títulos {0} a {1} de {2}',
emptyMsg : "Sem títulos para apresentar"
}),
sm : new GeoExt.grid.FeatureSelectionModel({
singleSelect : true,
listeners : {
rowselect : function(sm, row, rec) {
if (gridRequerimentos.getSelectionModel().hasSelection()) {
gridRequerimentos.getSelectionModel().clearSelections();
}
var titulo = rec.data.numero;
// r.data['numero'];
pesquisaTitulos.reset();
// pesquisaRequerimentos.setValue(titulo);
// pesquisaRequerimentos.onTrigger2Click();
}
}
})
});
storeTitulos.load({
params : {
start : 0,
limit : 25
}
});
var storePraias = new GeoExt.data.FeatureStore({
// layer : praia_layer,
fields : ['nome', 'municipio', 'lx', 'ly'],
proxy : new GeoExt.data.ProtocolProxy({
protocol : new OpenLayers.Protocol.HTTP({
url : 'json_procura_praia.php',
format : new OpenLayers.Format.GeoJSON()
})
})
});
/*
map.events.register('zoomend', map, function(e){
// jgr zumLevel=map.getZoom()+5;
// OpenLayers.Console.log('map.getZoom()= ', map.getZoom(), ' map.getResolution()=', map.getResolution());
if (map.getResolution() > fronteira)
storeVias.removeAll();
});
*/
var pesquisaPraias = new Ext.ux.form.SearchField({
store : storePraias,
width : 120
});
// create grid panel configured with feature store
var gridPraias = new Ext.grid.GridPanel({
id : 'gridResultados',
/* title : "Pesquisa livre", */
/* region : "east",*/
store : storePraias,
collapsible : false,
// collapsed: true, // se começar encolhido, o search fiel fica muito estreito...
// width : "100%",
height : 200,
loadMask : true,
viewConfig : {
forceFit : true
},
columns : [// { header: 'id', dataIndex: 'id', width: 50 },
{
header : 'Designação',
dataIndex : 'nome',
width : 60
}, {
header : 'Concelho',
dataIndex : 'municipio',
width : 60
}],
tbar : ['Pesquisar: ', ' ', pesquisaPraias],
bbar : new Ext.PagingToolbar({
pageSize : 25,
store : storePraias,
displayInfo : true,
displayMsg : 'Resultados {0} a {1} de {2}',
emptyMsg : "Sem resultados para apresentar"
}),
sm : new GeoExt.grid.FeatureSelectionModel({
singleSelect : true
}),
listeners : {
'rowclick' : {
'fn' : function(grid, index, evt) {
var r = grid.getStore().getAt(index);
// lx e ly vêem da base de dados
var lx = r.get('lx');
var ly = r.get('ly');
var center = new OpenLayers.LonLat(lx, ly);
map.setCenter(center, 6);
}
}
}
//"Feature: " + feature.id +"
Area: " + feature.geometry.getArea()+"
"
});
/*
* Presquisa por Freguesias
*/
/*
var storeFreguesia = new Ext.data.JsonStore({
root : 'features',
totalProperty : 'total',
idProperty : 'ogc_fid',
remoteSort : false,
baseParams : {
tabela : 'albufeiras.poa'
},
fields : ['ogc_fid', 'nome', 'st_xmin', 'st_ymin', 'st_xmax', 'st_ymax' ],
proxy : new Ext.data.HttpProxy({
url : 'json_boundingbox.php'
}),
autoLoad : true
});
*/
var storeFreguesias = new GeoExt.data.FeatureStore({
// layer : praia_layer,
fields : ['freguesia', 'municipio', 'st_xmin', 'st_ymin', 'st_xmax', 'st_ymax'],
proxy : new GeoExt.data.ProtocolProxy({
protocol : new OpenLayers.Protocol.HTTP({
url : 'json_procura_freguesia.php',
format : new OpenLayers.Format.GeoJSON()
})
})
});
var pesquisaFreguesias = new Ext.ux.form.SearchField({
store : storeFreguesias,
width : 120
});
var gridFreguesias = new Ext.grid.GridPanel({
id : 'gridResultadosFreguesias',
/* title : "Pesquisa livre", */
/* region : "east",*/
store : storeFreguesias,
collapsible : false,
// collapsed: true, // se começar encolhido, o search fiel fica muito estreito...
// width : "100%",
height : 200,
loadMask : true,
viewConfig : {
forceFit : true
},
columns : [// { header: 'id', dataIndex: 'id', width: 50 },
{
header : 'Freguesia',
dataIndex : 'freguesia',
width : 60
}, {
header : 'Concelho',
dataIndex : 'municipio',
width : 60
}],
tbar : ['Pesquisar: ', ' ', pesquisaFreguesias],
bbar : new Ext.PagingToolbar({
pageSize : 10,
store : storeFreguesias,
displayInfo : true,
displayMsg : 'Resultados {0} a {1} de {2}',
emptyMsg : "Sem resultados para apresentar"
}),
sm : new GeoExt.grid.FeatureSelectionModel({
singleSelect : true
}),
listeners : {
'rowclick' : {
'fn' : function(grid, index, evt) {
var r = grid.getStore().getAt(index);
map.zoomToExtent(new OpenLayers.Bounds(r.get('st_xmin'), r.get('st_ymin'), r.get('st_xmax'), r.get('st_ymax')));
}
}
}
//"Feature: " + feature.id +"
Area: " + feature.geometry.getArea()+"
"
});
var MyField = new Ext.form.TextField({
name : 'fotografia',
fieldLabel : "Fotografia",
width : 200,
flex : 1
});
var novoCampo = new Ext.form.CompositeField({
fieldLabel : 'Fotografia',
items : [MyField, {
xtype : 'button',
text : 'Abrir',
handler : function() {
// Show a menu or selection dialog, then set the user's
// selected value with:
// console.log(MyField.getValue());
OpenNewWindow(MyField.getValue(), 1024, 768);
return true;
}
}]
});
var gridForm = new Ext.form.FormPanel({
bodyPadding : 0,
// autoWidth : true,
autoHeight : true,
layout : 'column', // Specifies that the items will now be arranged in columns
fieldDefaults : {
labelAlign : 'left',
msgTarget : 'side'
},
items : [{
// columnWidth : 0.4,
// margin : '0 0 0 10',
// width: 'auto',
xtype : 'fieldset',
title : 'Caraterísticas da Ocupação',
defaults : {
width : 240,
// labelWidth : 90
flex : 1
},
defaultType : 'textfield',
items : [{
name : 'ogc_fid',
fieldLabel : "ID"
}, {
name : 'pp',
fieldLabel : "PP"
}, {
name : 'praia',
fieldLabel : "Praia"
}, {
name : 'proc_ant',
fieldLabel : "Proc. Ant.",
width : 120
}, {
name : 'proc',
fieldLabel : "Proc.",
width : 120
}, {
name : 'lic_num',
fieldLabel : "Lic.",
width : 120
}, {
name : 'titular',
fieldLabel : "Titular"
}, {
name : 'morada',
fieldLabel : "Morada"
}, {
name : 'contacto',
fieldLabel : "Contacto"
}, {
name : 'a_cob',
fieldLabel : "Área coberta"
}, {
name : 'a_total',
fieldLabel : "Área Total"
}, {
name : 'prev_pooc',
fieldLabel : "Prev. POOC"
}, {
name : 'adap_pooc',
fieldLabel : "Adap. POOC"
}, {
name : 'pt_situac',
fieldLabel : "Situação"
}, {
name : 'data_lic',
fieldLabel : "Data Lic."
// xtype: 'datefield'
}, {
name : 'lic_val',
fieldLabel : "Validade Lic."
}, {
name : 'tipoocupacao',
fieldLabel : "Tipo Ocupação"
}, {
name : 'tipodominio',
fieldLabel : "Domínio"
}, {
name : 'nif',
fieldLabel : "NIF"
}, novoCampo, {
name : 'observacoes',
fieldLabel : "Observacoes"
}]
}],
buttons : [{
// Existe um layer victor onde tudo se passa.
// As edições são feitas neste layer
// Depois são passadas para o verdadeiro layer (e consequentemente para o WFS)
// Será que dá?
text : 'Gravar', //text for submit button
type : 'submit', //type for button
// disabled : true,
handler : function() {
// Só fica ativo depois de se fazer Novo ou Editar
// Os botões de edição só aparecem depois de se fazer Novo ou Editar
console.log('Abre o layer para edição; cria novo feature; copia tudo para uma coleção; strategy.save()');
// Só grava se os required fields estiverem preenchidos
var ponto = new OpenLayers.Geometry.Point(-40000, 169000);
var attributes = {
proc : "proc sem numero",
tipoocupacao : 1
};
var novoFeature = new OpenLayers.Feature.Vector(ponto, attributes);
novoFeature.state = OpenLayers.State.INSERT;
console.log(novoFeature);
console.log(wfs);
wfs.addFeatures([novoFeature]);
wfs.strategies[1].save();
}
}, {
text : 'Cancelar', //text for submit button
handler : function() {
console.log('Cancela as alterações feitas');
}
}, {
text : 'Editar', //text for submit button
handler : function() {
console.log('Permite editar o feature já existente');
}
}, {
text : 'Novo', //text for submit button
handler : function() {
console.log('Cria um novo feature');
}
}]
});
var tabs = new Ext.TabPanel({
region : 'center',
/* margins : '3 3 3 0', */
activeTab : 0,
defaults : {
autoScroll : true
},
items : [/* {
title : 'Praia',
items : [gridPraias]
}, */
{
title : 'Freguesia',
items : [gridFreguesias]
} /*, {
title : 'Outras',
html : 'Pesquisas adicionais a definir...'
} */ ]
});
var tabsGestao = new Ext.TabPanel({
title : 'Gestão',
id : 'paineis',
activeTab : 0,
items : [{
title : 'Ocupações',
id : 'tabocupacoes',
height : 840,
// autoHeight : true,
layout : {
type : 'vbox',
align : 'stretch'
},
items : [gridOcupacoes, {
title : 'Desenhe a Localização Pretendida',
contentEl : 'barraEdicao',
height : 64
}, gridForm]
}, {
title : 'Contribuintes',
id : 'tabcontribuintes',
items : [gridContribuintes]
}, {
title : 'Títulos',
id : 'tabtitulos',
items : [gridTitulos]
}, {
title : 'Detalhes',
id : 'detalhes',
items : []
}] /* ,
// os dois controls são independetes; podem estar os dois activos ao mesmo tempo!
listeners : {
'tabchange' : function(tabPanel, tab) {
if (tab.id == 'detalhes') {
console.log('Oi ' + tabPanel.id + ' ' + tab.id + ' activa detalhes');
mLayers = mapPanel.map.layers;
console.log('mLayers existenes: ' + mLayers.length);
for ( a = 0; a < mLayers.length; a++) {
str = "Layer name is: " + mLayers[a].name + " Layer geo_type is: " + mLayers[a].CLASS_NAME;
console.log(str);
}
if (!informacoes.active) {
console.log('Vai ativar o informacoes');
informacoes.activate();
}
} else {
// console.log(tabPanel.id + ' ' + tab.id + ' desactiva detalhes');
if (!highlightCtrl.active) {
console.log('Vai ativar o highlightCtrl');
highlightCtrl.activate();
}
}
}
} */
});
var viewport = new Ext.Viewport({
layout : 'border',
items : [{
region : 'north',
xtype : 'panel',
height : 100,
collapsible : false,
border : true,
// bodyCssClass : 'painelNorte',
contentEl : 'norte'
}, {
region : 'west',
title : 'Navegação',
autoScroll : true,
id : 'tools',
//title: "Menus",
collapsible : true,
//border: true,
width : 280,
layout : 'accordion',
layoutConfig : {
animate : true
},
items : [{
title : 'Pesquisas',
id : 'pesquisa',
autoScroll : true,
items : [tabs]
}, tree],
split : true
}, mapPanel /* , {
region : 'east',
title : 'Gestão',
width : 400,
autoScroll : true,
items : [tabsGestao]
} */ ]
});
// form_logout.hide();
viewport.doLayout();
});