openlayers官方教程(二)Basics——Creating a map

Creating a map

Working example

The markup

首先,我们在工程目录下创建一个index.html文件,如下所示:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>OpenLayers</title>
    <style>
      html, body, #map-container {
        margin: 0;
        height: 100%;
        width: 100%;
        font-family: sans-serif;
      }
    </style>
  </head>
  <body>
    <div id="map-container"></div>
  </body>
</html>

此处注意不需要加<script>,模块打包机制会将main.js中js代码加入这里。

The application

为了让openlayers正常工作,我们需要从npm库安装ol package。当然如果之前已经执行过npm install就会安装此包。如果你才开始一个新的应用,你需要运行下面代码来安装这个包。

npm install ol@beta

我们再创建一个main.js文件作为应用的入口,将其放置工程文件根目录下。(默认就会创建)

import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZSource from 'ol/source/XYZ';

new Map({
  target: 'map-container',
  layers: [
    new TileLayer({
      source: new XYZSource({
        url: 'http://tile.stamen.com/terrain/{z}/{x}/{y}.jpg'
      })
    })
  ],
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});

在最顶上,我们从ol包中导入需要的模块。注意导入ol/ol.css是将openlayers需要的UI组件导入。当需要的都导入后,我们创建一个map,将其target指向上面markup中的div容器,我们配置一个瓦片地图,最后再定义center和zoom。

一切顺利,浏览器中打开http://localhost:3000/,可以看到如下地图:


猜你喜欢

转载自blog.csdn.net/u011435933/article/details/80439684
Map