Open Layers 3 - Convert Lat Long to Point
Asked Answered
T

1

6

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

Tight answered 7/2, 2015 at 7:23 Comment(3)
Are the coordinates [lat, lon] or [lon, lat]? ol3 expects [lon, lat].Racing
Ah.. They are [lat, lon].. Let me try inverting them with different EPSGsTight
Alright, reversing them worked like a charm! Can you post it as an answer? I hope it'll help someone.Tight
R
5

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

Racing answered 9/2, 2015 at 8:56 Comment(1)
I wonder how many times people got this wrong (including myself), I understand there is a small performance issue but why not use something like {"lon": lon, "lat": lat} or an object with .lat and .lon ?Damek

© 2022 - 2024 — McMap. All rights reserved.