OpenLayers Marker Example

From OpenStreetMap Wiki
Jump to navigation Jump to search

trash bin

It has been proposed that this page be deleted or replaced by a redirect. See the discussion page for further information.
The given reason is: This page contains an example with the outdated (for years) OpenLayers version 2. There are plenty of tutorials elsewhere. Using Leaflet for simple maps is easier than OpenLayers. I don't see the use of keeping this page. Therefore, I propose its deletion. --Nakaner (talk) 09:34, 13 August 2021 (UTC).

broom

This article or section may contain out-of-date information: This page is based on the outdated and unmaintained OpenLayers 2. Consider switching to Leaflet or a later version of OpenLayers, and ignore this page.
If you know about the current state of affairs, please help keep everyone informed by updating this information. (Discussion)

This is a simple example of adding a marker to an OpenLayers map.

Example

Here is the code that is needed (Copy the following into a new HTML file, and view it in a browser.) :

<html><body>
  <div id="mapdiv"></div>
  <script src="http://www.openlayers.org/api/OpenLayers.js"></script>
  <script>
    map = new OpenLayers.Map("mapdiv");
    map.addLayer(new OpenLayers.Layer.OSM());

    var lonLat = new OpenLayers.LonLat( -0.1279688 ,51.5077286 )
          .transform(
            new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
            map.getProjectionObject() // to Spherical Mercator Projection
          );
          
    var zoom=16;

    var markers = new OpenLayers.Layer.Markers( "Markers" );
    map.addLayer(markers);
    
    markers.addMarker(new OpenLayers.Marker(lonLat));
    
    map.setCenter (lonLat, zoom);
  </script>
</body></html>

This uses the same lonLat object to place a marker and then to also centre the map. You can add further markers using markers.addMarker(new OpenLayers.Marker(newLonLat)); if you define newLonLat to be another OpenLayers.LonLat object

iframe approach

There is an even simpler HTML fragment to use on your website, using an <iframe> tag. You can easily get the necessary HTML using the Export tab, and choosing the "embeddable HTML" option. The iframe approach is rather limited. If you're interested in trying out additional javascript tricks then the OpenLayers example above is a better starting point.

OpenLayers example with marker and popup

Here is an OpenLayers example with marker and popup. This could be the typical "you can find us here" example...

http://dev.openlayers.org/examples/osm-marker-popup.html

See also