简体   繁体   中英

openlayers map center issue

I am very new to working with openlayers. The tutorial below teaches how to show a map and build local, but the problem is I can not change the center of the map. Even If I change the location, it shows aways the "zero" point of the map.

https://openlayers.org/en/latest/doc/tutorials/bundle.html

below are the.js example and.html, the problem is the center: I can't change the map center

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

 const map = new Map({
   target: 'map',
   layers: [
     new TileLayer({
       source: new OSM()
     })
  ],
  view: new View({
    center: [0, 0],
    zoom: 0
  })
});

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Using Parcel with OpenLayers</title>
    <style>
      #map {
        width: 400px;
        height: 250px;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script src="./index.js"></script>
  </body>
</html>

Every GIS map has a coordinate system. GIS web applications are very similar to desktop GIS maps, so they have a coordinate system too. in OpenLayers known as projection.

In OpenLayers, every web app made up of a Map() class that needs a view() to show the map. By default, every view() use Web Mercator projection or EPSG:3857 as its projection. so in your code, you should put the center in EPSG:3857 coordinate system. If you want to use center coordinate in WGS 84 or lat-long numbers you should change the view projection to EPSG:4326 like this:

view: new ol.View({
    center: [0,0],
    projection: 'EPSG:4326',
    zoom: 0
})

Projection is really important for further usages. If you have some data in a specific projection, Openlayers can't display them on a map with another projection. for example, if you have some data in WGS 84 you can't use them on the default view(cause it's Web Mercator).
So before choosing the view projection read about the limits. eg Basemaps are not available in every projection just like normal layers.

Also, there is another option you can use. Projecting the whole layer on the fly(in client browser) needs a massive process but we always can project a point or a single feature and use them among our layers or base map. In your case, you can only project your center point and use the map in Web Mercator. for this option, you need to use fromLonLat() like this:

center: ol.proj.fromLonLat([0,0])

Hope to be clear.

Try this one for your center:

center: ol.proj.fromLonLat([longitude,latitude])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM