Monthly Archives: January 2012

X Marks the Spot With OpenLayers Vector Layer

One of my recent work projects requires plotting a point on a map.  Of course, OpenLayers immediately came to mind.  The coordinates for the point were coming out of a database, but it wasn’t a spatial database, so using WFS would have been difficult.  Instead of WFS, I wanted a simple solution where I could just generate a URL with X and Y positions for the marker, and have the X,Y plotted in a map on a web page.

OpenLayers has a Markers layer that would do the trick, but I read that it’s deprecated, and it wasn’t immediately obvious what to replace it with.  Plenty of tutorials  show how to use Marker to put a point on the map, but I couldn’t find any tutorials showing how to do it in a non-Markers way.   Eventually I came across the right OpenLayers example which shows how to do it using a Vector layer, and it’s super-easy.

Here’s the OpenLayers code that reads the X and Y position of a marker off the URL, and puts a red X at that point:

var map;
function init() {

   map = new OpenLayers.Map('map');

   //load free WMS source for background
   var wms = new OpenLayers.Layer.WMS(
     "OpenLayers WMS",
     {layers: 'basic'}

   var renderer = OpenLayers.Layer.Vector.prototype.renderers;

   var layer_style = OpenLayers.Util.extend({},['default']);
   layer_style.fillOpacity = 0.90;
   layer_style.graphicOpacity = 1;

   //set up style for the marker
   var style_marker = OpenLayers.Util.extend({}, layer_style);
   style_marker.strokeColor = "black";
   style_marker.fillColor = "red";
   style_marker.graphicName = "x";
   style_marker.pointRadius = 10;
   style_marker.strokeWidth = 1;

   // get X and Y from URL
   var xpos = OpenLayers.Util.getParameters(window.location.href).xpos;
   var ypos = OpenLayers.Util.getParameters(window.location.href).ypos;

   //create a point feature at x,y,  using previous marker style
   var point = new OpenLayers.Geometry.Point(xpos, ypos);
   var pointFeature = new OpenLayers.Feature.Vector(point,null,style_marker);

   //create a new vector layer and add the marker to it
   var vectorLayer = new OpenLayers.Layer.Vector("Treasure Here", {
       style: layer_style,
       renderers: renderer


   map.setCenter(new OpenLayers.LonLat(point.x, point.y), 11);

And here’s what the looks like for a URL like





PS: A shout out to whiteshadow’s raw html plugin for enabling Javascript inside this post.