Open layers pt_br

2.268 visualizações

Publicada em

0 comentários
2 gostaram
  • Seja o primeiro a comentar

Sem downloads
Visualizações totais
No SlideShare
A partir de incorporações
Número de incorporações
Incorporações 0
Nenhuma incorporação

Nenhuma nota no slide
  • What is OpenLayers? OpenLayers is a pure JavaScript library for displaying map data in web browsers with no server-side dependencies. It is currently the most used web client for geospatial applications all over the world, and, thanks to its high extensibility, it represents the foundation of the most web mapping interfaces you can see on the Internet (just to be clear, I can say that all the available web clients use OpenLayers as their basis). HISTORY: OpenLayers was created by MetaCarta in June 2005, and was released as open-source software before the Where 2.0 conference of June 2006, by MetaCarta Labs. Since November 2007 OpenLayers is a project of OSGeo (the Open Source Geospatial Foundation). OpenLayers is of course free and open source software and it is released under the 2-clause BSD-License. As Quantum GIS and GeoServer, also OpenLayers is a project of OSGeo and it is currently developed (current version is 2.1) and supported by a number of organizations around the world. Here is the official OpenLayers website, where you can download the software, get the source code, access the documentation, end so on. Basically, OpenLayers implements an API which is similar to the Google Maps and Microsoft Virtual Earth ones, but the great difference is that it is free!
  • This slide summarizes some of the most important OpenLayers functionalities. We are not interested in detail to each of them (also because we are not going to work on all these topics), but what I want you to keep from this overview is that with OpenLayers we can actually do everything we want. First of all, OpenLayers uses typical industry standards and OGC standards (in particular we are interested in WMS, WFS and WCS), so it is really “open” and not depending on specific server-side platforms; it can even display images taken from Google, Bing, Yahoo, ArcGIS and so on. It can display layers coming from different sources (provided that they are available using standards-compliant services) in the same web mapping application, and it can also reproject these data. As I said before, OpenLayers is highly extensible (and many OpenLayers extensions exist) and I want also to mention the possibility of editing vector feature directly on the client-side through the so-called WFS-T protocol, which is another OGC standard. From the OpenLayers website you can access the whole documentation, available also directly at this address.
  • One of the guiding principles of OpenLayers development has been to maintain a set of small examples of most functionalities, allowing the library to demonstrate most of what it can do by example. The examples (that you can find at this website) are typically the most up to date source of documentation, and provide more than 200 different code snippets for u se in the users applications. Typically, if you are interested in how to implement some specific function, y ou can look for this function in the example gallery and copy the source code. New users will most likely find diving into the OpenLayer’s example code and experimenting with the library’s possible functionality the most useful way to begin. We are going also to use some examples of this gallery in the following.
  • Before really starting working with OpenLayers, I suggest you to install a couple of software that will be very useful in the following. As we are going to program (to write code) with OpenLayers, first of all we need a good text editor, and the best one to be used is “gedit”, which is also the official text editor of GNOME desktop environment and proves to be really powerful for many purposes. It features a lot of functionalities, but in few words we use it because it supports an highlighted syntax for various languages, and in particular HTML and JavaScript, that we are going to use. Unfortunately, gedit is not already included in this virtual machine, but the procedure to install it is very easy: from the “Applications” menu, open the “Synaptic Package Manager” (using the default password “user”) and type “gedit” in the search box: then mark the package for installation and wait for the installation. Finally you will find the installed package under the menu “Applications”, “Accessories”.
  • Another tool that will prove to be very useful is Firebug, that you can download from its official website. Firebug is a popular web development tool, that provides a wide range of functionalities: for our goal, it allows us to inspect HTML pages and to debug JavaScript code in order to find possible errors. In other words, possible errors that for sure we are going soon or later to commit while writing code will be detected by Firebug. To install it, it is sufficient in this case to open the official website and download it. After downloaded, and any time you open your web browser, Firebug needs to be activated by clicking its insect icon on the right of the browser toolbar.
  • Open gedit and save the blank file on the desktop with the name you want (for instance “OpenLayers_exercise.html”): in this way, gedit knows that the file is written in the HTML language and, as you will see in a minute, it shows us the code in different colors according to the syntax. Unfortunately you have not the administrator rights to save directly the file in the folder we want, which is var/www/openlayers/examples. For this reason, open the terminal emulator and write these commands. First, move to the folder “Desktop”. Then, you have first to change the owner of the “examples” folder, where you will then copy the file, using the terminal (the password is “user”). Next, copy the file. Then, open your web browser and write as URL this string: in other words, we are opening our file using the web server (and not simply from the file system).
  • As I said before, OpenLayers allows to insert a map viewer in any element of an HTML page. Therefore, the first step is to create a basic HTML page using the <html>, <head> and <body> tags. In the <head> tag, insert a title for the web page that will be displayed in the browser. Then, insert a <script> tag (you can do it here or wherever you want) that adds the OpenLayers JavaScript libraries to the page. The tag <meta> (which is optional) is useful to declare the character encoding of the HTML document (if it not declared, we receive a warning from Firebug). Then, inside the <body> tag of the HTML page, we put a <div> tag that serves as the container for the map we're going to create (we could use any block-level element as the container). Within this tag, we also specify an “id” for the map (in order to refer to it) and the percentages of the screen width and height that we want to use to place the map.
  • Once we have set up our HTML page, we need to first create a map: in order to this, you must use the OpenLayers.Map constructor according to this syntax (line 11): this map constructor requires one argument, that can be either an HTML element or the ID of an HTML element, as in our case (where we use the “map” id of the “div” element): in other words, we tell the map constructor where to render the map. This constructor does not work if the map container has been defined. Here I have also added a title for our HTML page. SYNTAX: each OpenLayers constructor begins with a capital letter: when we use the word “new”, it means that a new object (e.g. “map”) is created with all the properties of the constructor (e.g. “”) used
  • After creating a map, we need at least one layer to be displayed in it. OpenLayers has two types of layers: base layers and overlays. Base layers are mutually exclusive layers, meaning that only one can be enabled at any given time. The currently active base layer determines the available projection (coordinate system) and zoom levels available on the map. Most raster layers (in particular, this is true for WMS layers) are set as base layers by default (this can be changed using the “isBaseLayer” property). Base layers always display below overlay layers. Overlay layers are the opposite: many overlay layers can be enabled at a time, and they do not control the zoom levels of the map, but can be enabled or disabled at certain scales. Overlay layers always display above base layers. In this case, we are going to add a base layer: aBlue Marble WMS image of the whole planet provided by OpenGeo. Inside the <body> tag and after the map creation, we use the OpenLayers.Layer.WMS, which requires as input three parameters: the first is a string name for the layer, that will be used for some display purposes (for instance, it will appear in the layer menu); the second is the URL of the WMS server and the third is an object containing parameters of the WMS request (in this simplified case only the name of the WMS layer). Then, we added two more constructors. The first actually draws the created layer on the map. Finally, in order to display the map, we have to set a center and a zoom level. Using the ZoomToMaxExtent function, we force the full extent of the map to be fitted into the window.
  • Summarizing, this is the full code we have written up to now, and this should be the obtained result.
  • Once we have added a base layer to our map, it's time to start adding also our Ecuador layers we have previously published with GeoServer (again as WMS). In order to to this, we must use the same OpenLayers.Layer.WMS we used before. First of all, choose a name for the layer; then, as the first parameter, write a description of the layer; write then the URL of the WMS server, which is the one of our GeoServer WMS server. Then, you must write exactly the name of the layer, as it appears in the WMS server. To get it, you can have a look at the WMS GetCapabilities document in GeoServer (logout, then login and then look at the GetCapabilities) or you can preview the layer in GeoServer, or you can connect directly to the server using Quantum GIS.
  • Then, in addition to what we did before for the base layer, we add also a “transparent” parameter and we set it to “true”. This choice automatically sets the values of the parameters in the following 2 lines (so, these other two lines could be also omitted). First declaration is the image format for drawing the WMS layer, which is set to image/png (I remind you that png supports transparency) if the browser supports it; the second is instead the option “isBaseLayer”, which is set equal to “false” and tells OpenLayers that this layer has to be drawn with transparency on top of the previous base layer. If you try to set a “true” value, this layer becomes the base layer and you will not see the blue marble layer anymore. Finally, use again the map.addLayer constructor to add the layer to the map.
  • The complete code we have written till now should be the following.
  • And this is the appearance of the web page.
  • Now, as we are interested in viewing Ecuador data, let's center the map on Ecuador. In order to do this, we have to delete (or comment, which is the same because all the commented commands are ignored) the line of code where we selected to initially zoom the map to a level corresponding to its full extent. Then, we use the “map.setCenter” function, that requires to know the coordinates (in this case, latitude and longitude) of the center point of the map, and the zoom level we want to set. Regarding the coordinates, you can open for example the layer in Quantum GIS and find a proper point; regarding the zoom level, you can try some values and then select the best. Another useful command (especially when you want to add more layers that you want to display together) is “map.addLayers”, that requires in input the list of the layer names to be added (be careful to the syntax!). In this way, we can spare some lines of code.
  • This is the appearance of the web page after centering the map on Ecuador region.
  • Once we have understood how to add a WMS layer to our map, we can repeat the procedure to add also the layers of Ecuador roads, rivers and water areas. Of course the WMS server is the same and also the properties of these layers (that are all overlay layers) are the same as before; what differs is just the layer name. Please remember to finally add each layer to the map, by using each time the “map.addLayer” function, or by using at the end the “map.addLayers” function with the list of all the layers we want.
  • If you look at the result, you can see that, for small scales, the layers are not well distinguishable. It is therefore recommended to set a scale range in which the layer becomes visible: this can be achieved using a “scales” parameter inside the WMS layer properties. As you can see from the syntax, the only information required is the maximum and minimum scale factor, corresponding to the minimum and maximum scales. In this case, I chose a value of 3000000 for the maximum scale factor, but the choice is up to you.
  • In OpenLayers, controls provide a way for users to interact with your map. Some controls have a visual representation while others are invisible to the user. When you create a map with the default options, you are provided with a few visible default controls. These controls allow users to navigate with mouse movements (e.g., drag to pan, double-click to zoom in) and buttons to pan & zoom. At this point, we can enrich our client with some useful elements, such as the updated cursor position, the layer menu, the indication of current map scale and the scalebar. To add all these elements, we must use the function “addControl”, whose argument is in turn determined by different constructors. To add the pointer position, which will be located by default in the bottom right corner of the map, we must use the “OpenLayers.Control.MousePosition” constructor. There are few possible parameters we can add to this constructor: “prefix” to set a string to be written before the first coordinate; “separator” to set a string to be written between the two coordinates; “numDigits” to set the number of digits for each coordinate. To add the current map scale, the constructor to be used is “OpenLayers.Control.Scale”: the scale will be displayed as a ratio, and by default in the bottom right corner of the map. Finally, to add a scalebar to the map (by default in the bottom left corner of the map), the constructor to be used is “OpenLayers.control.ScaleLine”. Unfortunately, the default color for the cursor coordinates, the scale and the scalebar is red; to modify the color, the style and the position, you have to define a CSS style to be then used as parameter of the different constructors.
  • To add a layer menu, which will appear on the right side of the page, the constructor to be used is “OpenLayers.Control.LayerSwitcher”.
  • We could also try to add one of the Ecuador layers we published with GeoServer as WFS, instead of WMS. In this case, the lines of code we should write are these. Now, instead of using the “OpenLayers.Layer.WMS” constructor, we must use the “OpenLayers.Layer.Vector” constructor and specify in a second time, using the “protocol” parameter, that the protocol use to get the vector layer is the WFS one. Then we must also specify the name of the layer, as it has been previously defined in GeoServer, and the workspace URI defined in the “Edit Workspace” menu within GeoServer. At this website (which is the official OpenLayers example gallery), you can find a very easy example of adding a WFS layer (actually I took the code from there). [Se mi chiedono di provare a farlo, o perchè non funziona, dico che non l'ho mai provato]
  • As I said at the beginning, almost all raster layers (this is true in particular for WMS layers) are drawn by default as base layers, and remember that obviously only one base layer can be active at each time. If we want that a WMS layer is an overlay layer instead of a base layer (as we did before for provinces, roads, rivers and water areas), it is sufficient to use the “isBaseLayer” parameter setting it to “false”. The definition of the WMS layer is the same as before: the only thing to note is that, if the “addLayer” function for this layer is written before the one for the other base layer, this layer will be the first to be written in the layer menu (as you can see in the figure), and so the base layer actually used in the client.
  • As I said at the beginning, almost all raster layers (this is true in particular for WMS layers) are drawn by default as base layers, and remember that obviously only one base layer can be active at each time. If we want that a WMS layer is an overlay layer instead of a base layer (as we did before for provinces, roads, rivers and water areas), it is sufficient to use the “isBaseLayer” parameter setting it to “false”. The definition of the WMS layer is the same as before: the only thing to note is that, if the “addLayer” function for this layer is written before the one for the other base layer, this layer will be the first to be written in the layer menu (as you can see in the figure), and so the base layer actually used in the client.
  • A very useful functionality is to let users add new layers to the map by simply drawing polygons, lines or points. This code can be used to just draw new features of a new vector layer that has been created ad hoc. This is the zero level, in the sense that the user cannot then edit features and save them. This is a second and more complex step, that requires the use of the WFS-Transactional OpenLayers protocol that we have not time to see in this brief practice.
  • Last point of this practice is to add some predefined base layers provided by commercial API providers such as Google, Microsoft and by OpenStreetMap. All these layers are projected using a Spherical Mercator projection, that for this reason has become a de facto term used inside the OpenLayers community – and also by the existing Open Source GIS community. This term refers to the fact that these providers use a Mercator projection which treats the earth as a sphere, rather than an ellipsoid. This affects calculations done based on treating the map as a flat plane, and it is therefore important to be aware of, when working with these map providers. In order to properly overlay data on top of the maps provided by the commercial API providers, it is necessary to use this projection: this implies first of all to declare the projection (using its EPSG code) in the creation of the map viewer; here we say also that we want the coordinates displayed as latitude and longitude in a WGS84 reference system. Then, when we use the “map.setCenter” function to center the map on a desired point, we can use again the same geographic coordinates as before, but they must be projected correctly in the Spherical Mercator system. This implies that we have to specify the transformation between the two reference systems using the “transform” function.
  • To add the google layers to your map, first of all use a <script> tag (before the <script> tag containing the whole javascript code) that takes the Google API key, and then add the 4 layers (physical map, streets, hybrid map and satellite image) with the usual commands: note that OpenLayers provides a specific function to add Google layers, which is “OpenLayers.Layer.Google”.
  • This is an example of visualization with the Google Physical map as base layers and the roads, rivers and water areas as overlay layers.
  • To add the Bing layers to your map, first of all you need an API key. For today and for sample applications like this that you can build in the future, you can use this one, that I took from an OpenLayers example in the gallery. But if you will create and publish real applications, you need to get your personal key at the Bing maps portal website (so that you act in a legally correct way).
  • This is an example of visualization in which I set the Bing aerial map as background layer and the rivers and roads as overlay layers.
  • Finally, it is possible also to add an OpenStreetMap base layer: as you know, OpenStreetMap is a global project where users actually create cartography: each of you can register at the website and start drawing buildings and so on. In order to add an OpenstreetMap layer in OpenLayers, the function to be used is “OpenLayers.Layer.OSM”
  • Open layers pt_br

    1. 1. Elaborado por: Marco Minghini (Politécnico de Milão, Itália) Traduzido e adaptado por: Marcos R. Rosa (CIH) Foz do Iguaçu, 2013 Tutorial de OpenLayers
    2. 2. 2 OpenLayers ✔ Criado em 2005 pela MetaCarta, OpenLayers é uma biblioteca de mapeamento geográfico Javascript-based que permite aos usuários exibir mapas dinâmicos em navegadores mais modernos, sem qualquer dependência do lado do servidor. ✔ É altamente extensível e serve como base de todas as interfaces comuns de mapeamento web. Sua atual versão é a 2.13. ✔ OpenLayers é completamente livre e de código aberto (free and open source), provido sobre a licença 2-clause BSD License (também conhecido como FreeBSD). ✔ É um projeto da fundação Open Source Geospatial; desenvolvido e suportado por muitas organizações ao redor do mundo. ✔ OpenLayers implementa uma API Javascript para construir ricas aplicações geográficas web-based, similar ao Google Maps e a MSN Virtual Earth APIs, mas com uma importante diferença: ele é um software livre!
    3. 3. 3 OpenLayers ✔ Algumas funções incluem: ➔ Sobreposição de camadas de mapas em uma única aplicação; ➔ Exibe feições/imagens a partir: WMS, WMTS, TMS, WMS-C, WMTS, Google Maps, Bing Maps, Yahoo Maps, OpenStreetMap, ArcGIS Server, ArcIMS; ➔ Renderização de feições vetoriais e estilos com suporte para KML, GeoJSON, WKT GML, WFS, GeoRSS; ➔ Edição web-based, incluindo operações via WFS-T (WFS-Transactional); ➔ Permite integração com outras bibliotecas JavaScript (Jquery, Ext, Dojo, MooTools); ➔ Reprojeção de mapa ➔ Completa documentação (
    4. 4. 4 OpenLayers - Exemplos ✔ Uma das melhores fontes de documentação é a página de exemplos (
    5. 5. 5 ✔ gedit é um editor de textos poderoso presente no gerenciador de janelas desktop GNOME ( ➔ Oferece uma ambiente de texto configurável para múltiplas linguagens (C, C++, Java, HTML, XML, Python, Perl e muitas outras) ✔ Para instalar o gedit: ➔ Abra o Synaptic Package Manager no menu Application (senha: user) ➔ Procure o pacote gedit, marque para instalação e clique em Apply ➔ Para acessar selecione o menu Applications → Accessories → gedit
    6. 6. 6 Firebug ✔ Firebug é um dos mais populares ferramentas para depuração web development tool: ➔ Permite inspeção do código HTML, estilo e do leiaute e modificação em tempo real; ➔ Utiliza um dos mais avançados debugador de código JavaScript debugger para qualquer navegador; ✔ Para instalar o Firebug: ➔ Abra o website e selecione Install Firebug: ➔ ative o Firebug clicando no ícone de inseto localizado no canto superior direito do navegador
    7. 7. 7 Iniciando com OpenLayers ✔ Para construir visualizações em OpenLayers deve-se criar primeiro uma página HTML onde o mapa será inserido, para isto deve-se: ➔ Abrir o editor gedit e salvar um arquivo no desktop com o nome OpenLayers_exercise.html ➔ Abra o terminal no menu Applications → Accessories → Terminal Emulator e copie o arquivo para a pasta var/www/openlayers/examples com os seguintes comandos (senha: user): cd Desktop sudo chown user /var/www/openlayers/examples cp OpenLayers_exercise.html /var/www/openlayers/examples ➔ Abra o arquivo pelo navegador web digitando a URL localhost/openlayers/examples/OpenLayers_exercise.html
    8. 8. 8 Iniciando com OpenLayers ✔ Vamos agora digitar alguns códigos HTML para construção de nossa primeira página. ➔ Inicie sua página HTML digitando os seguintes códigos: ✗ line 3: a tag title define o título da página web que será apresentado no navegador ✗ line 4: a tag script permite adicionar a biblioteca OpenLayers na página (é necessário inserir antes de escrever o código customizado em JavaScript) ✗ line 5: na tag meta define o tipo de codificação caracter do HTML ✗ line 8: nós vamos usar a tag div como espaço para nosso mapa
    9. 9. 9 Criando a visualização do mapa ✗ Na ordem de criação da visualização, vamos primeiro criar um mapa: ✗ line 8: a tag h1 adiciona o título (“OpenLayers exercise”) centralizado na página ✗ line 10: a tag script, especifica a linguagem JavaScript, neste bloco conterá todo o código utilizando OpenLayers ✗ line 11: para adiconar o mapa, utilize o construtor OpenLayers.Map. O construtor requer um argumento, que pode ser também um elemento HTML ou um ID em um elemento HTML (aplicável ao map): este é o elemento onde será inserido o mapa.
    10. 10. 10 Adicionando uma camada WMS ✔ Na ordem de visualização do mapa, nós devemos incluir ao menos uma camada. Vamos agora adicionar um simples camada WMS (Blue Marble image) disponibilizada pelo OpenGeo: ✗ lines 12-13: o construtor OpenLayers.Layer.WMS adiciona uma camada WMS no mapa. Ele requer três argumentos: a primeira string define o nome da camada; o segundo é o endereço, ou seja, a URL do servidor WMS; o terceiro contém um objeto contendo um conjunto de parâmetros anexada a requisição WMS (neste caso, somente o nome da camada WMS, ou seja, a camada bluemarble) ✗ line 14: o construtor map.addLayer irá desenhar a camada do mapa e como argumento deverá ser passado o nome da variável que contém o objeto da camada. ✗ line 15: a função zoomToMaxExtent provê um zoom de nível inicial para encaixar o mapa na caixa de visualização.
    11. 11. 11 Adicionando uma camada base WMS ✔ O código completo da página ficará assim:
    12. 12. 12 Adicionando uma sobreposição de camada WMS ✔ Vamos agora adicionar a segunda camada WMS (a camada contendo as províncias do Equador, que nós publicamos no GeoServer) por cima da camada base do mapa: ➔ Inserir somente estas linhas de código depois da definição da camada base: ✗ line 18: escolha o nome da camada (neste caso utilize Ec_prov) e como construtor utilize OpenLayers.Layer.WMS para adicionar a camada WMS no mapa. O primeiro argumento é a descrição da camada. ✗ line 19: o segundo argumento é o endereço URL do servidor WMS, vamos utilizar nosso servidor local WMS GeoServer http://localhost:8082/geoserver/wms ✗ line 20: o terceiro argumento é um objeto contendo os parâmetros para a requisição WMS. O primeiro é o nome da camada WMS que foi definido no Geoserver (OSGIS_course:ECU_adm1)
    13. 13. 13 Adicionando uma sobreposição de camada WMS ✔ Vamos agora adicinar a segunda camada WMS (a camada contendo as províncias do Equador, que nós publicamos no GeoServer) por cima da camada base do mapa: ➔ Inserir somente estas linhas de código depois da definição da camada base: ✗ lines 21-22-23: o parâmetro de transparência atribuir com o valor true, e também definir mais dois campos. O primeiro é o parâmetro format, deve ser atribuído como image/png se o seu navegador suporta imagens com transparência em PNG (para o navegador Internet Explorer 6, deve ser atribuído como image/gif). O segundo é a opção isBaseLayer, que controla se a camada pode ser mostrada ao mesmo tempo que as outras camadas (se definir como true, a camada vai se tornar a camada base e não poderá visualizar mais a camada anterior) ✗ line 24: o método map.addLayer desenha a camada Ec_prov no mapa
    14. 14. 14 Adicionando uma sobreposição de camada WMS ✔ O código completo ficará assim:
    15. 15. 15 Adicionando uma sobreposição de camada WMS ✔ A página HTML terá a seguinte aparência:
    16. 16. 16 Centralizando o mapa em um local específico ✔ Suponhamos que queremos centralizar o mapa no Equador: ➔ Comente (ou apague) a linha de código: ➔ E substitua pela seguinte linha de código: ✗ lines 26-27: a função setCenter irá atribuir o centro do mapa a partir das coordenadas definidas como parâmetro (Longiture e Latitude) e o nível de zoom inicial do mapa. ✔ Também é possível incluir várias camadas ao mesmo tempo: ➔ Comente (ou apague) as linhas de código : ➔ E substitua elas por uma linha de código: ✗ line 26: a função map.addLayers toma como parâmetro uma lista de todas as camadas a serem adicionadas
    17. 17. 17 Centralizando o mapa em um local específico ✔ A página HTML terá a seguinte visualização:
    18. 18. 18 Adicionando sobreposição de camada WMS ✔ Agora vamos adicionar várias sobreposições de camadas WMS do Equador como rodovias, rios e áreas com água (as camadas que publicamos no GeoServer previamente): ➔ Inserir estas linhas de código após a definição das camadas posteriores: ✗ line 50: lembre-se de atualizar a lista de camadas na função map.addLayers!
    19. 19. 19 Exibindo camadas além de uma certa escala ✗ line 31: nos parâmetros de escala é necessário definir os valores: mínimo (3000000) e valor máximo (1) . Em outras palavras, a camada será visível entre as escalas 1:3000000 e 1:1. ✔ Para propósitos de visualização, recomenda-se configurar estas camadas visíveis para além de uma escala fixa, por exemplo 1:3000000: ➔ Inserir uma linha de código junto com os parâmetros da camada WMS, como no exemplo abaixo em rodovias do Equador:
    20. 20. 20 Adicionando elementos no mapa ✗ line 59: o parâmetro prefix define o texto que será o prefixo das coordenadas do cursor ✗ line 60: o parâmetro separator define o texto separador usado para separar as duas coordenadas ✗ line 61: o parâmetro suffix define o sufixo a ser inserido no cursor das coordenadas ✔ Vamos agora adicionar alguns elementos no mapa: ➔ Para inserir a posição do mouse no mapa, vamos inserir os seguintes códigos: ➔ Para adicionar a indicação da escala do mapa atual, insira a linha de código: ➔ Para adicionar a barra de escala, insira a linha de código:
    21. 21. 21 Adicionando elementos no mapa ✔ Vamos agora adicionar alguns elementos no mapa: ➔ Para adicionar um menu de camadas: ➔ Para criar cantos arredondados no menu de camadas, deve-se inserir as seguintes linhas de código fora do código javascript: ✗ line 11: o parâmetro border-radius determina a configuração de pixels do canto arredondado ✗ line 12: o parâmetro opacidade determina o valor da opacidade (de 0 até 1)
    22. 22. 22 Adicionando uma camada WFS ✔ Vamos agora adicionar uma sobreposição de camada WFS: ➔ Para criar a camada, devem ser escritas as seguintes linhas de código: ➔ Um exemplo WFS padrão está disponível em ✗ line 61: o construtor OpenLayers.Layer.Vector adiciona uma camada vetorial na visualização do mapa ✗ line 63: o parâmetro protocol especifica o que protocolo WFS protocol será utilizado para adicionar a camada vetorial ✗ line 64: o parâmetro url define o link do servidor WFS, o endereço de nosso WFS Geoserver local é http://localhost:8082/geoserver/wfs ✗ line 65: o parâmetro featureType especifica o nome da camada, definido no GeoServer ✗ line 66: o parâmetro featureNS especifica o workspace namespace URI, definido no GeoServer
    23. 23. 23 Adicionando um segunda camada base WMS ✔ É possível adicionar outras camadas base em seu mapa. Lembre-se que toda camada WMS é considerada camada base por padrão: ➔ Para adicionar uma cartografia global no mapa, deve-se inserir as seguintes linhas de código antes da definição da camada base anterior: ✗ lines 21-22-23: o construtor OpenLayers.Layer.WMS adiciona a camapa WMS no mapa. Ele requer três argumentos: o nome da camada a ser visualizada; o endereço do servidor WMS; e o terceiro um objeto contendo os parâmetros a serem adicionados na requisição WMS (neste caso somente o nome da camada WMS basic) ✗ line 24: a função map.addLayer desenha a camada no mapa.
    24. 24. 24 Adicionando uma sobreposição de mapa ✔ A sobreposição dinâmica é inserida na visualização corrente do mapa respeitando a extensão do mapa inicial: ➔ Para inserir uma sobreposição de mapa, inserir o seguinte código: ✔ A página HTML deverá ser apresentada assim:
    25. 25. 25 Criando uma camada vetorial desenhada ✔ Vamos agora criar uma camada vetorial que será utilizada para desenhar polígonos, linhas e pontos: ➔ Para adicionar uma camada vetorial no mapa, inserir o seguinte código: ➔ Para adicionar um editing toolbar no mapa, inserir o seguinte código: ➔ Atenção: esta não é uma aplicação completa, pois não habilita editar e salvar os dados gerados (será necessário utilizar o protocolo WFS-T)!
    26. 26. 26 Adicionando as camadas Google, Bing e OpenStreetMap ✔ Com a finalidade de melhorar a aparência do mapa, é possível adicionar algumas camadas base fornecida por terceiros como Google, Microsoft e OpenStreetMap. Todas estas camadas são referenciadas utilizando a projeção Spherical Mercator (EPSG code: 900913): ➔ Para declara o uso da projeção, criar a visualização de mapa desta forma: ➔ Para centralizar o mapa na posição correta, escreva o seguinte código: ✗ line 19: o parâmetro da projection define que a projeção Spherical Mercator projection é usada ✗ line 20: o parâmetro displayProjection diz que as coordenadas serão exibidos em WGS84 (como latitude e longitude) ✗ lines 130-131: as coordenadas geograficasdo mapa centralizado (previamente definido) são transformadas em coordenadas da projeção Spherical Mercator. Desta forma, o mapa está corretamente centralizado no Equador.
    27. 27. 27 Adicionando a camada Google ✔ Para adicionar as camadas Google (physical map, streets map, hybrid map and satellite map) na visualização do mapa ➔ Escreva este código antes (e fora) do código customizado javascript: ➔ Insira as seguintes linhas de código: ✗ lines 23-27-31-35: a função OpenLayers.Layer.Google adiciona uma camada base Google na visualização do mapa
    28. 28. 28 Adicionando a camada Google ✔ Um exemplo de visualização é o seguinte:
    29. 29. 29 Adicionando a camada Microsoft (Bing) ✔ Para adicionar as camadas Microsoft (Bing) (roads map, aerial map and hybrid map) na visualização do mapa ➔ Escreva os seguintes códigos: ✗ line 52: esta chava da API key para Deve-se gerar a chave no link ✗ lines 54-59-64: a função OpenLayers.Layer.Bing adiciona a camada base Microsoft (Bing) na visualização do mapa
    30. 30. 30 Adicionando a camada Microsoft (Bing) ✔ Um exemplo de visualização é o seguinte:
    31. 31. 31 Adicionar a camada do OpenStreetMap ✔ Para adicionar a camada OpenStreetMap ➔ Escreva os seguintes códigos: ✗ line 73: a função OpenLayers.Layer.OSM adiciona a camada base OpenStreetMap na visualização do mapa ✔ Um exemplo de visualização é o seguinte:
    32. 32. 32 Referências ✔ OpenLayers official website: ✔ OpenLayers user documentation: ✔ OpenLayers developer documentation: ✔ OpenLayers example gallery: ✔ OpenGeo OpenLayers Workshop at FOSS4G 2011, Denver (CO, USA), September 12-16 2011 : ➔