Javascript – Open Layers 3 – Convert Lat Long to Point

gisjavascriptopenlayers-3ruby-on-rails

I have an array of Lat Longs in an array called lat_longs (which looks like this – [[39.749318, -104.9701129], [..], [..]]), I'm trying to plot them in an OpenStreetMap using Open Layers 3. Here is the code I have –

var icon_features = [];

$.each(lat_longs, function(index, item){
   var point = new ol.geom.Point(item);
   point.transform('EPSG:4326', 'EPSG:900913');
   // I tried it the other way too, but doesn't seem to work

   var iconFeature = new ol.Feature({
       geometry: point,
       name: item.name
   });

   icon_features.push(iconFeature);
});

var vectorSource = new ol.source.Vector({
   features: icon_features
});

var vectorLayer = new ol.layer.Vector({
   source: vectorSource
});

var view = new ol.View({
   center: [0,0],
   zoom: 2
});

var map = new ol.Map({
    layers: [
       new ol.layer.Tile({
           source: new ol.source.OSM()
       }),
       vectorLayer
    ],
    target: 'map',
    controls: ol.control.defaults({
        attributionOptions:  ({
        collapsible: false
    })
  }),
  view: view
});

For some reason, it seems to be either plotting the location near Africa or not plotting the location at all.

How do I fix this?

I found codes to do projections and transforms in Open Layers 2. Couldn't exactly find how to do it in Open Layers 3.

NOTE: I got it working with tsauerwein 's comment. But note, I had to transform the point from EPSG:4326 to EPSG:900913

Best Answer

OpenLayers expects the coordinates to be [lon, lat] instead of [lat, lon]. So in your case you would have to change the order.