前言

本文记录 Vue 使用 OpenLayers 入门,使用 OpenLayers 创建地图组件,分别使用 OpenLayers 提供的地图和本地图片做为地图。

Overview
OpenLayers makes it easy to put a dynamic map in any web page. It can display map tiles, vector data and markers loaded from any source. OpenLayers has been developed to further the use of geographic information of all kinds. It is completely free, Open Source JavaScript, released under the 2-clause BSD License (also known as the FreeBSD).

官方地址:https://openlayers.org/

1. 安装 OpenLayers 库

	cnpm install ol 

2. Vue 创建 OpenLayers 组件

效果图

在这里插入图片描述

Code

	<template>
	  <div id="map" class="map"></div>
	</template>
	
	<script>
	import "ol/ol.css";
	import Map from "ol/Map";
	import OSM from "ol/source/OSM";
	import TileLayer from "ol/layer/Tile";
	import View from "ol/View";
	
	export default {
	  mounted() {
	    this.initMap();
	  },
	  methods: {
	    initMap() {
	      new Map({
	        layers: [
	          new TileLayer({
	            source: new OSM()
	          })
	        ],
	        target: "map",
	        view: new View({
	          center: [0, 0],
	          zoom: 2
	        })
	      });
	
	      console.log("init finished");
	    }
	  }
	};
	</script>
	<style>
	.map {
	  width: 100%;
	  height: 400px;
	}
	</style>

3. OpenLayers 使用本地图片作为地图

效果图:

Code

	<template>
	  <div>
	    <div id="map" class="map"></div>
	  </div>
	</template>
	
	<script>
	import "ol/ol.css";
	import ImageLayer from "ol/layer/Image";
	import Map from "ol/Map";
	import Projection from "ol/proj/Projection";
	import Static from "ol/source/ImageStatic";
	import View from "ol/View";
	import { getCenter } from "ol/extent";
	
	let extent = [0, 0, 338, 600];
	let projection = new Projection({
	  code: "xkcd-image",
	  units: "pixels",
	  extent: extent
	});
	
	export default {
	  data() {
	    return {
	      map: {}
	    };
	  },
	
	  mounted() {
	    this.initMap();
	  },
	
	  methods: {
	    initMap() {
	      this.map = new Map({
	        layers: [
	          new ImageLayer({
	            source: new Static({
	              attributions: '© <a href="http://xkcd.com/license.html">xkcd</a>',
	              url: "http://localhost:8080/img/123.5cba1af6.jpg",
	              projection: projection,
	              imageExtent: extent
	            })
	          })
	        ],
	        target: "map",
	        view: new View({
	          projection: projection,
	          center: getCenter(extent),
	          zoom: 1,
	          maxZoom: 4,
	          minZoom: 1
	        })
	      });
	    }
	  }
	};
	</script>
	<style>
	.map {
	  width: 100%;
	  height: 400px;
	}
	</style>
Logo

前往低代码交流专区

更多推荐