Talk:Openlayers POI layer example

From OpenStreetMap Wiki
Jump to navigation Jump to search

Discuss Openlayers POI layer example here:


OpenLayers 2.6 / Example does not work

"In a future version of OpenLayers (it will be in 2.6 which is soon to be released),..." - OpenLayers 2.6 is out, maybe somebody wants to change this? I haven't tried OpenLayers with POI yet, so I don't know anything about it.--Beate 15:57, 13 July 2008 (UTC)


Okay, it seems to be available, but at least the example doesn´t work. Do I need to link different OpenLayers.js or OpenStreetMap.js files or something? But maybe the reason is that I haven´t understood the following rows:

maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
numZoomLevels: 19,
maxResolution: 156543.0399,

What do the numbers exactly stand for? As long I don´t know its meaning (the openlayers website doesn´t really help understanding it) I don´t know how to modify them when changing the center coordinates of the map like this (which works - the map is centered correctly):

map.setCenter(new OpenLayers.LonLat(6.9538,50.96468).transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), 15);

A brief explanation would be great - else the example is useless. By the way: The Mercator coordinates in the first textfile.txt example do neither match the spherical nor the elliptical Mercator formulas from the mentioned page. What´s wrong with that?

Best regards, --Krza 23:01, 19 July 2008 (UTC)

This POI layer example increases the height of the textbox when ever i click on the icon more than once. (see: example) Any solution for that problem? Regards --Makracht 18:04, 3 August 2008 (UTC)

I found out it works with a WMS layer but not with any other type. See the following example. Thomas P 12:41, 12 September 2008 (UTC)

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <style type="text/css">
#map {
        width: 100%;
        height: 100%;
        border: 0px;
        padding: 0px;
        position: absolute;
     }
body {
        border: 0px;
        margin: 0px;
        padding: 0px;
        height: 100%;
     }
    </style>
    <script src="http://www.openlayers.org/api/OpenLayers.js"></script>
    <script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script>
    <script type="text/javascript">

        var map;

        function init(){
            map = new OpenLayers.Map('map');

            // Alternative 1: works
            layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", "http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} );  

            // alternative 2: does NOT work => all coordinates default to somewhere around the coast of central west africa
            //layer = new OpenLayers.Layer.OSM.Mapnik("Mapnik");             

            map.addLayer(layer);

            var pois = new OpenLayers.Layer.Text( "My Points", { location:"./textfile.txt" } );
            map.addLayer(pois);

            map.setCenter(new OpenLayers.LonLat(11.59,48.14),4);
        }

    </script>
  </head>
  <body onload="init();">
    <div id="map"></div>
  </body>
</html>

Working example for OSM

What to know beforehand

  • You need to manually include the function osm_getTileURL() into your script.
  • When using coordinates you might have to convert then using transform(map.displayProjection, map.projection)
// Calculate URL of OSM's tiles
function osm_getTileURL(bounds) {
    var res = this.map.getResolution();
 
    var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
    var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
    var z = this.map.getZoom();
    var limit = Math.pow(2, z);
 	  	  	
    // ----

    if (y < 0 || y >= limit) {
        return OpenLayers.Util.getImagesLocation() + "404.png";
    } else {
        x = ((x % limit) + limit) % limit;
        //alert(this.url + z + "/" + x + "/" + y + "." + this.type);
        return this.url + z + "/" + x + "/" + y + "." + this.type;
    }

Examples for converting coordinates

// Example 1: 'magic numbers'  (untested code)
  var lonLat = new OpenLayers.LonLat(10,50).transform(new OpenLayers.Projection("EPSG:4326"),  new OpenLayers.Projection("EPSG:4326"));

  // Use converted coordinates to eg. zoom into the map
  map.setCenter (lonLat, zoom);


// Example 2: Using variables
  // Somewhere else in the code: The variables we use later are declared
  var lat=10.0
  var lon=50.0
  var zoom=12	

  var options = {
      projection: new OpenLayers.Projection("EPSG:900913"),
      displayProjection: new OpenLayers.Projection("EPSG:4326"),
      units: "m",
      numZoomLevels: 18,
      maxResolution: 156543.0339,
      maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508.34)
  };
  map = new OpenLayers.Map('map', options); 

  // ...

  // Convert
  var lonLat = new OpenLayers.LonLat(lat,lon).transform(map.displayProjection,  map.projection);

  // Use converted coordinates to eg. zoom into the map
  map.setCenter (lonLat, zoom);


The Copy-Pase example: File 1: index.php

<html>
<head>
	<title>OpenStreetMap</title>

	<!-- bring in the OpenLayers javascript library
		 (here we bring it from the remote site, but you could
		 easily serve up this javascript yourself) -->
	<script src="http://www.openlayers.org/api/OpenLayers.js"></script>

	<!-- bring in the OpenStreetMap OpenLayers layers.
		 Using this hosted file will make sure we are kept up
		 to date with any necessary changes -->
	<script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script>

	<script type="text/javascript">
		// Start position for the map (hardcoded here for simplicity,
		// but maybe you want to get from URL params)
		var lat=10.0
		var lon=50.0
		var zoom=12		
		var map; //complex object of type OpenLayers.Map

                // Calculate URL of OSM's tiles
                function osm_getTileURL(bounds) {

                var res = this.map.getResolution();
 	  	  	
                var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
                var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
                var z = this.map.getZoom();
                var limit = Math.pow(2, z);
 	  	  	
                // ----

                if (y < 0 || y >= limit) {
                        return OpenLayers.Util.getImagesLocation() + "404.png";
                    } else {
                        x = ((x % limit) + limit) % limit;
                    //alert(this.url + z + "/" + x + "/" + y + "." + this.type);
                        return this.url + z + "/" + x + "/" + y + "." + this.type;
                    }
	  	}

                // ----

		//Initialise the 'map' object
		function init() {
	            var options = {
                projection: new OpenLayers.Projection("EPSG:900913"),
                displayProjection: new OpenLayers.Projection("EPSG:4326"),
                units: "m",
                numZoomLevels: 18,
                maxResolution: 156543.0339,
                maxExtent: new OpenLayers.Bounds(-20037508, -20037508,
                                                 20037508, 20037508.34)
            };
            map = new OpenLayers.Map('map', options); 

            // ----

            // Declare and add an OpenStreetmap layer
            var layer = new OpenLayers.Layer.TMS(
                "OpenStreetMap (Tiles@Home)",
                "http://tah.openstreetmap.org/Tiles/tile/",
                {
                    type: 'png', getURL: osm_getTileURL,
                    displayOutsideMaxExtent: true,
                    attribution: '<a href="http://www.openstreetmap.org/">OpenStreetMap</a>'
                }
            );
            map.addLayer(layer);
			
            // ----

            // Variant 1: Using coordinates and a zoom factor
            //var lonLat = new OpenLayers.LonLat(lat,lon).transform(map.displayProjection,  map.projection);
            //map.setCenter (lonLat, zoom);

            // Variant 2: Zoom to show all            
            //map.zoomToMaxExtent();

            // Variant 3: Using a bounding box: Most but not all of the world
            map.zoomToExtent(
                new OpenLayers.Bounds(-150.0,68.0,150.0,-50.0).transform(
                    map.displayProjection,  
                    map.projection));

            // Add klickable markers  which are defined in a text file
            // IMPORTANT: 'projection' must be set to map's 'displayProjection', NOT to maps's 'projection'
            var newl = new OpenLayers.Layer.Text( "text", { location:"./textfile.txt"
                ,projection:map.displayProjection
                } );
            map.addLayer(newl);

        }
	</script>
</head>
<!-- body.onload is called once the page is loaded (call the 'init' function) -->
<body onload="init();">
	<!-- define a DIV into which the map will appear. Make it take up the whole window -->
	<div style="width:75%; height:50%" id="map"></div>
</body>
</html>


The Copy-Pase example: File 2: textfile.txt

point	title	description	icon
2,4	my aqua title	my aqua description	
42,-71	my purple title	my purple description<br/>is great.	http://www.openlayers.org/api/img/zoom-world-mini.png
50,10	my orange title	my orange description

poi customisation

it would be helpful if somebody could provide intructions on how to customise poi textareas (with very, very simple working examples :) ).

1. currently popup area is very large, i'd like it to only contain single row of text; 2. i'd like to reduce font used; 3. i'd like to have multiple poi texts open simultaneously - currently clicking another closes the previous one.

as there's no user interface to place markers in osm itself, this is the only way to add multiple markers for non-coding users, so coding in js isn't an option, unfortunately. simply changing a parameter or two might be ;)

--Richlv 13:03, 20 July 2009 (UTC)


openlayers.text umwandeln

hier ist mein vorschlag, er funktioniert noch nicht ganz, ist aber wesentlich flexibler... ich wandele die Openlayers.text-datei in einen GML layer um. damit funktionieren auch viele openlayers-formatierungen wieder.

nur der Schließen-Button funktioniert noch nicht

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>osmolt Ergebnis</title>
    <link type="text/css" rel="stylesheet" href="map.css" />
    <script src="http://openstreetmap.org/openlayers/OpenStreetMap.js"></script>
    <style type="text/css">
      #map {
        width: 100%;
        height: 100%;
        border: 0px;
        padding: 0px;
        position: absolute;
      }
      body {
        border: 0px;
        margin: 0px;
        padding: 0px;
        height: 100%;
      }
    </style>
    <script type="text/javascript" src="http://www.openlayers.org/api/OpenLayers.js"></script> 
    <!-- OpenStreetMap OpenLayers-Layers laden
             (hier wird die JavaScript-Datei direkt vom Server geladen,
              man kann sie aber auch auf den eigenen Server speichern) -->

    <script type="text/javascript" src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script>
    <script type="text/javascript">  
      <!--
        var map;

        function init(){
          map = new OpenLayers.Map('map',
                  { maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
                    numZoomLevels: 20,
                    maxResolution: 156543.0399,
                    units: 'm',
                    projection: new OpenLayers.Projection("EPSG:900913"),
                    displayProjection: new OpenLayers.Projection("EPSG:4326"),
	                  controls:[
		                  new OpenLayers.Control.Permalink(),
		                  new OpenLayers.Control.MouseDefaults(),
		                  new OpenLayers.Control.LayerSwitcher(),
		                  new OpenLayers.Control.MousePosition(),
		                  new OpenLayers.Control.PanZoomBar()
		                ]
                  });

          // Basis-Karten definieren, hier sind "Mapnik und Osmarender die Basiskarten
	  // andere Basiskarten können einfach als Auswahl dazugefügt werden
          // weitere Basiskarten: OpenLayers.Layer.OSM.Maplint oder OpenLayers.Layer.OSM.CycleMap
          var layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");

          var layerTah = new OpenLayers.Layer.OSM.Osmarender("Osmarender");

          map.addLayers([layerMapnik,layerTah]);

// ================das wichtige========================

         var myLayer = new OpenLayers.Layer.GML("layerName","poi.txt",{format: OpenLayers.Format.Text, projection: map.displayProjection });
         map.addLayer(myLayer);

         var myLayersfc = new OpenLayers.Control.SelectFeature(Doener);
         map.addControl(myLayersfc);

         myLayersfc.activate();

         myLayer.events.on({
            'featureselected': onFeatureSelect,
            'featureunselected': onFeatureUnselect
          });
// ========================================
          // Karte ausrichten
          var theArgs = getArgs();          
          if (theArgs.lon)
          {
            var lon = theArgs.lon ? theArgs.lon : 7.8402899999999995;
            var lat = theArgs.lat ? theArgs.lat : 48.009775;
            var zoom = theArgs.zoom ? theArgs.zoom : 12;
            var lonLat = new OpenLayers.LonLat(lon,lat).transform(map.displayProjection,  map.projection);
            map.setCenter (lonLat,zoom); // Zoomstufe einstellen
          }else{
            var bounds=new OpenLayers.Bounds(7.77077,47.96832,7.90981,48.05123).transform(map.displayProjection,  map.projection);
            map.zoomToExtent(bounds); 
          }
        }   


        function onPopupClose(evt) {
            // 'this' is the popup.
            selectControl.unselect(this.feature);
        }

        function onFeatureSelect(evt) {
            feature = evt.feature;
            popup = new OpenLayers.Popup.FramedCloud("featurePopup",
                                     feature.geometry.getBounds().getCenterLonLat(),
                                     new OpenLayers.Size(100,100),
                                     "<h2>"+feature.attributes.title + "</h2>" +
                                     feature.attributes.description,
                                     null, true, onPopupClose);
            feature.popup = popup;
            popup.feature = feature;
            map.addPopup(popup);
        }

        function onFeatureUnselect(evt) {
            feature = evt.feature;
            if (feature.popup) {
                popup.feature = null;
                map.removePopup(feature.popup);
                feature.popup.destroy();
                feature.popup = null;
            }
        }
        
        function getArgs() {
            var args = new Object();
            var query = location.search.substring(1);  // Get query string.
            var pairs = query.split("&");              // Break at ampersand. //+pjl
       
            for(var i = 0; i < pairs.length; i++) {
                var pos = pairs[i].indexOf('=');       // Look for "name=value".
                if (pos == -1) continue;               // If not found, skip.
                var argname = pairs[i].substring(0,pos);  // Extract the name.
                var value = pairs[i].substring(pos+1); // Extract the value.
                args[argname] = unescape(value);          // Store as a property.
            }
            return args;                               // Return the object.
        }

      // -->
    </script>
  </head>

  <!-- body.onload is called once the page is loaded (call the 'init' function) -->
  <body onload="init();">
  
    <div id="map"></div>
    <div style="position:absolute; bottom:10px;width:700px;z-index: 1001;">
      <img src="mag_map-120x120.png" height="60px" title="Copyright 2007 OpenStreetMap and contributors" onClick="window.open('http://wiki.openstreetmap.org')" />
      <img src="somerights20.png" height="30px" title="This work is licensed under the Creative Commons Attribution-ShareAlike 2.0 License" onClick="window.open('http://creativecommons.org/licenses/by-sa/2.0')" />
    </div>
  </body>
</html>


DOCTYPE html problem

I try to practice with simple POI example, it works fine. But when I added "<!DOCTYPE html>" in the top of index page, it does not work; if I change to "<!DOCTYPE html />", it will work again. But for HTML5, I suppose add "<!DOCTYPE html>". And I cannot find any error when I use Chrome to debug. Any suggestion? Thanks.

User:Swimming 16:56, 2 October 2013‎

Yes. I don't know why, but in HTML5 mode my browser decides to shrink the div down to 0px in height (find it using the inspector. I'm sure you'll see the same), whereas otherwise without the DOCTYPE in this example it seems to default to 100%.
If you want a full height map, it's safer to set all the containers to 100% explicitly like so:
 <!DOCTYPE html> 
 <html> 
 <head><title>OpenLayers Text File Example</title>
 <style>
 html,body,div {
    height:100%; /* set all map containers to full height */
 }
 </style> 
 </head>
-- Harry Wood (talk) 01:47, 3 October 2013 (UTC)
For me the right CSS directive is this one:
div#mapdiv {height:500px;}
Freezed (talk) 09:12, 24 September 2014 (UTC)

POIs with Link?

Moin,

möchte gerne erreichen, dass bei Klick auf einen POI sich ein Link auf eine HTML-Seite öffnet, oder dass bei mouseover die Seite aufscheint. Wie kann ich das erreichen? – Hintergrund: wir arbeiten für den hiesigen ADFC an einer Karte, wo die Gefährdungspunkte in der Stadt verzeichnet sein sollen und diese mit einem Bild und einer Beschreibung verknüpft werden sollen.

I would like to achieve that a mouse click onto a POI opens a link to an HTML page, or that the page shows up on mouseover. How can I implement that? – Background: for the local bicycle club, we are working on a map which shall display the danger points in our town, each linked to a photo and a description.

Für Hinweise dankbar, thanks, cheers, --Mussklprozz (talk) 07:55, 15 November 2020 (UTC)