How to center the map according to specific coordinates

Viewed 98

I am learning OpenLayers with javascript. I am following this tutorial

http://openlayersbook.github.io/ch01-getting-started-with-openlayers/example-01.html

the code works fine, but when i add the following line:

var birmingham = ol.proj.transform([-1.81185, 52.44314], 'EPSG:4326', 'EPSG:3857');

and type

npm start or 
npm run start

nothing is to be displayed. when I remove the aforementioned line of code the map appears normally on the localhost. I want the center of the map to be set to specific coordinates

please let me knoe what is wrong with the line of code mentioned above and how to fix it. code:

import 'ol/ol.css';
import {Map, View} from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import Projection from 'ol/proj/Projection';
import * as olTransform from 'ol/transform';

var source = new OSM()

var layers = [new TileLayer({
  source: source
})];

ol.projection.transform
//var birmingham = ol.proj.transform([-1.81185, 52.44314], 'EPSG:4326', 'EPSG:3857');// this line results in not to show the map
var view = new View({
  projection: 'EPSG:4326',
  center: [0, 0],
  zoom: 2,
  maxZoom: 40,
  zoomFactor: 4
});

const map = new Map({
  target: 'map',
  layers: layers,
  view: view
  });
1 Answers

Avoid mixing module and full build syntaxes.

If the view projection is EPSG:4326 you do not need to transform, simply use the lon/lat value directly

import 'ol/ol.css';
import {Map, View} from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

var source = new OSM()

var layers = [new TileLayer({
  source: source
})];

var view = new View({
  projection: 'EPSG:4326',
  center: [-1.81185, 52.44314],
  zoom: 2,
  maxZoom: 40,
  zoomFactor: 4
});

const map = new Map({
  target: 'map',
  layers: layers,
  view: view
});

For other projections use

import 'ol/ol.css';
import {Map, View} from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import {fromLonLat} from 'ol/proj';

var source = new OSM()

var layers = [new TileLayer({
  source: source
})];

var view = new View({
  projection: 'EPSG:3857',
  center: fromLonLat([-1.81185, 52.44314], 'EPSG:3857'),
  zoom: 2,
  maxZoom: 40,
  zoomFactor: 4
});

const map = new Map({
  target: 'map',
  layers: layers,
  view: view
});

EPSG:3857 is the default for both View and fromLonLat and can be omitted. fromLonLat is equivalent to

import {transform} from 'ol/proj';
transform([-1.81185, 52.44314], 'EPSG:4326', 'EPSG:3857'),
Related