[GIS] Inserting custom latitude-longitude data in OpenLayers Heatmap

coordinatesheat maplayersopenlayerspoint

I need to be able to insert custom latitude and longitude data into my heatmap, and I thought I found a way by following this previous answer.

However, the point is always centered at the same location, regardless if I change the point's lat-lon. Below is a snippet of my code:

// Map
var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    }),
  ],
  target: 'map',
  controls: ol.control.defaults({
    attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
      collapsible: false
    })
  }),
  view: new ol.View({
    center: [0, 0],
    zoom: 2
  }),
  interactions: ol.interaction.defaults().extend([
    new ol.interaction.DragRotateAndZoom(),
    new ol.interaction.PinchRotate(),
  ])
});

// created for owl range of data
var data = new ol.source.Vector();
var coord = [2.1734, 41.3851];  // Barcelona, Spain
var lonLat = new ol.geom.Point(coord);
var pointFeature = new ol.Feature({
   geometry: lonLat,
   weight: 20 // e.g. temperature
});
data.addFeature(pointFeature);

// create the layer
heatMapLayer = new ol.layer.Heatmap({
   source: data,
   radius: 50
});

// add to the map
map.addLayer(heatMapLayer);

I cannot seem to figure this out. I was able to create a proper heatmap following the example provided by OSM here, but that would require me to load a KML file. However, I need to be able to use entries in my database to populate this heatmap instead. Below is a picture of what the heatmap looks like:

enter image description here

Any ideas? Does it have something to do with needing to transform the map view so the coordinates are read correctly? I've been wracking my brain over this for days.

Best Answer

The default projection of the OpenLayers ol.View object is: EPSG:3857 (which is in meters), which means features that are added must be transformed into this projection to be correctly displayed.

The coordinates you're using are using the EPSG:4326 projection (which is in degrees). That's why they seem to be always added at the center.

OpenLayers natively supports transforming from and to both these projection. In your code, try replacing:

var coord = [2.1734, 41.3851];  // Barcelona, Spain

by:

var coord = ol.proj.fromLonLat([2.1734, 41.3851]); // Barcelona, Spain
Related Question