Interactive Polygon Drawing and Area Calculation with Vue and OpenLayers
This tutorial shows how to import the required OpenLayers modules into a Vue project, configure a map, add a Polygon draw interaction, handle the drawend event to compute and format the polygon's area using OpenLayers' getArea function, and provides a complete working example with code.
Overview
Extends a Vue + OpenLayers example to draw polygons and compute their area directly in the browser.
Module imports
// basic OpenLayers CSS and core classes
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import { Fill, Style, Stroke } from "ol/style";
// layer and source modules
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import { TileWMS, Vector as VectorSource } from "ol/source";
// interaction modules
import { Select, Draw } from "ol/interaction";
// utility for area calculation
import { getArea } from "ol/sphere";Polygon drawing interaction
Instantiate a Draw interaction with type: 'Polygon' and attach it to the map.
this.onAddInteraction('Polygon');Draw‑end handler
When the user finishes drawing, the drawend event provides the feature geometry. The handler calls getArea(geometry) (square metres), formats the result as km² when the value exceeds 10 000 m², otherwise as m², logs the output, stores the coordinate array, and removes the interaction.
this.draw.on('drawend', function(e) {
const geometry = e.feature.getGeometry();
var area = getArea(geometry);
console.log('area=' + area);
var output;
if (area > 10000) {
output = (Math.round(area / 1000000 * 100) / 100) + ' km<sup>2</sup>';
} else {
output = (Math.round(area * 100) / 100) + ' m<sup>2</sup>';
}
console.log('output=' + output);
let pointArr = geometry.getCoordinates();
self.coordinate.push(pointArr);
console.log('self.coordinate=' + self.coordinate);
self.removeDraw();
});Map initialization
Creates a base WMS layer (GeoServer example) and a vector layer for drawn features. Configures the view centre, zoom range, and a selection tool with a custom style.
this.layer = new TileLayer({
source: new TileWMS({
ratio: 1,
url: "http://localhost:8000/geoserver/nyc/wms",
params: { LAYERS: "nyc:nyc_roads", STYLES: "", VERSION: "1.1.1", tiled: true },
serverType: "geoserver",
}),
});
this.lineSource = new VectorSource({ wrapX: false });
this.lineLayer = new VectorLayer({ source: this.lineSource });
this.map = new Map({
target: "map",
layers: [this.layer, this.lineLayer],
view: new View({
center: [987777.93778, 213834.81024],
zoom: 14,
minZoom: 6,
maxZoom: 19,
}),
});
let selectedStyle = new Style({
fill: new Fill({ color: 'rgba(1, 210, 241, 0.2)' }),
stroke: new Stroke({ color: 'yellow', width: 4 })
});
this.selectTool = new Select({
multi: true,
hitTolerance: 10,
style: selectedStyle,
});
this.map.addInteraction(this.selectTool);
// start polygon drawing
this.onAddInteraction('Polygon');Full Vue component
<template>
<div id="app">
<div id="map" class="map"></div>
</div>
</template>
<script>
// imports as shown above
export default {
name: "olMapTileWMSDrawPolygon",
data() {
return {
map: null,
layer: null,
lineLayer: null,
draw: null,
lineSource: null,
coordinate: [],
};
},
mounted() {
this.initMap();
},
methods: {
onAddInteraction(type) {
let self = this;
this.draw = new Draw({ source: self.lineSource, type: type });
this.draw.on('drawend', function(e) {
const geometry = e.feature.getGeometry();
var area = getArea(geometry);
console.log('area=' + area);
var output;
if (area > 10000) {
output = (Math.round(area / 1000000 * 100) / 100) + ' km<sup>2</sup>';
} else {
output = (Math.round(area * 100) / 100) + ' m<sup>2</sup>';
}
console.log('output=' + output);
let pointArr = geometry.getCoordinates();
self.coordinate.push(pointArr);
console.log('self.coordinate=' + self.coordinate);
self.removeDraw();
});
self.map.addInteraction(this.draw);
},
removeDraw() {
this.map.removeInteraction(this.draw);
},
initMap() {
// layer and map setup as described earlier
},
},
};
</script>
<style scoped>
.map { width: 100%; height: 800px; }
</style>Online demonstration
Live demo URL: https://codesandbox.io/s/ol-measure-u3yob?file=/src/measure.ts:8795-8825
Reference blog posts
Line drawing tutorial: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/121287934
Polygon drawing with area calculation: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/121300723
Screenshot
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
The Dominant Programmer
Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
