32

I have seen the examples presented here of how to draw a line but the examples only show how to do it with the mouse, by clicking.

What I want to do is draw the line manually using JavaScript given a list of Longitude and Latitude coordinates.

The reason I cannot work on the source provided in the link above is because they are only calling activate on the feature, and then let the user point and click on the map.

Has anyone ever drew a path on an OpenLayers map programatically?

What I want to do is exactly this: http://openspace.ordnancesurvey.co.uk/openspace/example4.html, but without using OpenSpace.

Andreas Grech
  • 98,643
  • 98
  • 284
  • 354

3 Answers3

53

You would need to make use of the LineString object

Here is an example:

var lineLayer = new OpenLayers.Layer.Vector("Line Layer"); 

map.addLayer(lineLayer);                    
map.addControl(new OpenLayers.Control.DrawFeature(lineLayer, OpenLayers.Handler.Path));                                     
var points = new Array(
   new OpenLayers.Geometry.Point(lon1, lat1),
   new OpenLayers.Geometry.Point(lon2, lat2)
);

var line = new OpenLayers.Geometry.LineString(points);

var style = { 
  strokeColor: '#0000ff', 
  strokeOpacity: 0.5,
  strokeWidth: 5
};

var lineFeature = new OpenLayers.Feature.Vector(line, null, style);
lineLayer.addFeatures([lineFeature]);

Assuming map is your map object and lon and lat are float values.

whlk
  • 14,969
  • 13
  • 64
  • 93
Drahcir
  • 10,961
  • 18
  • 58
  • 75
  • 4
    I had to use `new OpenLayers.Geometry.Point(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());` instead of just `new OpenLayers.Geometry.Point(lon1, lat1)` as I had wsg84 coordinates – yankee Jun 16 '12 at 21:07
  • 1
    Good sample. The DrawFeature is actually not needed, the line "map.addControl(....DrawFeature...);" can be omitted. – dube Aug 15 '13 at 12:53
1

this page is a classic example of animation via javascript using openlayers.

it uses a filter strategy to define what to show at what moment in time.

full javascript available.

tony gil
  • 9,063
  • 6
  • 72
  • 89
0

I've never done it myself before, but I know OpenSteetMap does it. For example:

http://www.openstreetmap.org/?way=23649627

No idea how difficult it would be to work through their code.

RoToRa
  • 34,985
  • 10
  • 64
  • 97