OpenLayers JavaScript – How to Animate View to Custom Coordinates in OpenLayers 5

coordinatesjavascriptopenlayers

Given just a basic ol.Map using OpenLayers 5

var map = new ol.Map({
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM()
        })
    ]
    target: 'map'
    view: new ol.View({
        center: [0,0],
        zoom: 2
    })
});

I am attempting to allow for a user to enter a lat/lon coordinate in format latitude, longitude in decimal degrees. I want to create an event that animates the map to move to that entered coordinate.

var panToPosition = function (latlon) { 
    if (/^(\-?[0-9]{1,3}\.?[0-9]{0,10}\s{0,10}\,\s{0,10}\-?[0-9]{1,3}\.?[0-9]{0,10})$/.test(latlon)) {                  
        var arrLatLon = latlon.split(',');
        var latitude = arrLatLon[0];
        var longitude = arrLatLon[1];
        var coords = [parseFloat(longitude), parseFloat(latitude)];
        Ext.GeoSpatialSearch.map.getView().animate({center: coords});               
    }
};

When this function fires, the map animates, but it always goes to [0,0], not the coordinate array I have selected.

I have found this example on another site

var coords = fromLonLat([parseFloat(latLong[1]), parseFloat(latLong[0])]);

but it is unusable as fromLonLat is not a usable function in OpenLayers 5, only 6+. Why is it always going to 0,0 instead of the given coordinates? If I do need to transform to a different projection, how do I do so?

Best Answer

The example code you found is for ES6 code where there is first import of the fromLonLat function form ol\proj module, something like:

import {fromLonLat} from 'ol/proj';

This code has either to be first compiled to run or run on node.js.

If you want to use function in vanilla JS environment, you have to reference function using the whole object path: ol.proj.fromLonLat (see docs at https://openlayers.org/en/v5.3.0/apidoc/module-ol_proj.html#.fromLonLat).