Using Openlayers 2.13, I am trying to set up multiple markers for New expatriates in our suburb.
As a new user of both JS and Openlayers, I am stuck – I have managed one marker but cannot add another – do I need to upgrade to Openlayers 4 or use an array?
<html>
<head>
<title>OpenLayers Solution</title>
<script src="OpenLayers.js"></script>
<script> function init() {
var lat = -1.3169;
var lon = 36.6903;
var zoom = 15;
var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984
var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
var position = new OpenLayers.LonLat(lon, lat).transform( fromProjection, toProjection) ;
map = new OpenLayers.Map("Map");
var mapnik = new OpenLayers.Layer.OSM();
map.addLayer(mapnik);
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
markers.addMarker(new OpenLayers.Marker(position));
map.setCenter(position, zoom);
}
</script>
</head>
<body onload="init();">
<div style="width: 100%; height: 60%;" id="Map"></div>
</body>
</html>
Best Answer
To add another marker, you'd call
markers.addMarker(new OpenLayers.Marker(position));
again, but this time with a newposition
argument (otherwise the markers would appear on top of each other).As for upgrading to OpenLayers 4, you should do that simply because OpenLayers 2 is no longer supported, won't be receiving bug fixes or updates, and the community knowledge of OpenLayers 2 is going to become stale; you'll have more and more trouble finding help.