SoFunction
Updated on 2025-04-04

Implementation method of uploading KML files in Vue 3 and displaying them on map

Preface

In modern geographic information system (GIS) applications, we often need to load geospatial data into maps for visual display. KML (Keyhole Markup Language) is a file format based on XML format, which is widely used to store geographic information data, especially in Google Earth and other GIS systems. This article will explain how to upload a KML file in a Vue 3 project and display its contents on a map.

Introduction to KML file format

KML (Keyhole Markup Language) is an XML format used to describe geographic information. KML files usually contain geo-coordinates, geo-tagging, paths, regions, and other geo-objects. KML files can be used in a variety of map tools, including Google Earth and OpenLayers.

Basic structure of KML files

The basic structure of a KML file usually includes the following parts:

  • <kml>: Root element, declaring the file version and namespace.
  • <Document>: Contains multiple geotagging and other geographic information.
  • <Placemark>: Represents a geotagged mark, usually including name, description, and coordinate information.
  • <Point><LineString><Polygon>: Represents a specific geographical shape, such as points, lines or surfaces.

Here is a simple KML file example:

<?xml version="1.0" encoding="UTF-8"?> 
<kml xmlns="/kml/2.2"> 
    <Document> 
    <name>Sample KML</name> 
    <Placemark> 
        <name>Point 1</name> 
        <Point> 
<coordinates>-95.6185,37.6185,0</coordinates> </Point> </Placemark> <Placemark> <name>Point 2</name> <Point> <coordinates>-118.2437,34.0522,0</coordinates> 
        </Point> 
    </Placemark> 
    </Document> 
</kml>

This file contains two geographical points, located in Kansas and Los Angeles, USA.

Implementation function: Upload KML files and display them on the map

Next, we will implement the following functions in the Vue 3 project:

  • User uploads KML files.
  • Parses the content of the KML file and displays the geotagging on the map.

1. Create a Vue 3 project

If a Vue 3 project has not been created, you can use the following command to create a new project:

npm install -g @vue/cli vue create vue-kml-upload

Select Vue 3 configuration and go to the project directory:

cd vue-kml-upload

2. Installation dependencies

This project requires use OpenLayers To display the map,as well as To read and parse KML document。 Installation dependencies:

npm install ol d3-fetch

3. Write components: Upload KML files and display them on the map

existsrc/componentsCreate a new component file in the folder, and write code in it:

&lt;!--
 * @Author: Peng Qi
 * @Date: 2024/12/17
 * @Email: 1062470959@
 * @Description: Copyright of this source code belongs to Ji Tanjiali,Available for learning and reference or commercial use。
 --&gt;
&lt;template&gt;
  &lt;button class="back-button" @click="goBack"&gt;return&lt;/button&gt;
  &lt;div class="container"&gt;
    &lt;div class="w-full flex justify-center"&gt;
      &lt;div class="font-bold text-[24px]"&gt;existVue3Used inOpenLayersUploadKMLdocument,并existmapShown on&lt;/div&gt;
      &lt;h4&gt;
        &lt;input style="margin-top: 16px" type="file"  accept=".kml"/&gt;
      &lt;/h4&gt;
      &lt;div &gt;&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;
&lt;script setup&gt;
import {ref, onMounted} from 'vue';
import 'ol/';
import {Map, View} from 'ol';
import SourceVector from 'ol/source/Vector';
import LayerVector from 'ol/layer/Vector';
import KML from 'ol/format/KML';
import {Tile} from 'ol/layer';
import OSM from 'ol/source/OSM';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import Text from 'ol/style/Text';
import router from "@/router";
const goBack = () =&gt; {
  ('/OpenLayers');
};
const map = ref(null); // Responsive map objectconst source = ref(
  new SourceVector({
    wrapX: false,
    format: new KML({
      extractStyles: false, // No style extraction    }),
  })
);
const view = ref(
  new View({
    projection: 'EPSG:3857', // Map projection    center: [11585992.5, 3585872.5], // Center point of map (Chengdu City)    zoom: 3, // Map zoom level  })
);
// Read the uploaded KML file and add it to the mapconst readFile = () =&gt; {
  const fileselect = ('#fileselect'); // Get file selector  ('change', function (e) {
    const files = ; // Get the selected file    if ( === 0) {
      alert('No data, please upload the new file again!  '); // Prompt no file is selected      return;
    }
    const reader = new FileReader();
    (files[0]); // Read the contents of the KML file     = function (evt) {
      const shparray = ; // Get the file content      // Read data in KML format      const allFeatures = 
        .getFormat()
        .readFeatures(shparray, {
          dataProjection: 'EPSG:4326', // Data projection          featureProjection: 'EPSG:3857', // Feature projection        });
      // Add all Features to Source      (allFeatures);
      // Set style      (function (feature) {
        const style = new Style({
          fill: new Fill({color: 'purple'}), // Fill color          stroke: new Stroke({color: 'orange'}), // Border color          text: new Text({
            text: ('name'), // Displayed text            font: '12px Calibri,sans-serif', // Font style            fill: new Fill({color: '#000'}), // Text fill color            stroke: new Stroke({
              color: '#fff', // Text border color              width: 2,
            }),
          }),
        });
        (style); // Application style      });
    };
  });
};
// Initialize the mapconst initMap = () =&gt; {
   = new Map({
    target: 'vue-openlayers', // The target element of the map rendering    layers: [
      new Tile({
        source: new OSM(), // Add OSM layer      }),
      new LayerVector({
        source: , // Add vector layer      }),
    ],
    view: ,
  });
};
onMounted(() =&gt; {
  initMap(); // Initialize the map when component is mounted  readFile(); // Read the file});
&lt;/script&gt;
&lt;style scoped&gt;
.container {
  width: 840px;
  height: 590px;
  margin: 50px auto;
  border: 1px solid #42b983;
}
#vue-openlayers {
  width: 800px;
  height: 400px;
  margin: 0 auto;
  border: 1px solid #42b983;
  position: relative;
}
&lt;/style&gt;

4. Functional analysis

1. Read the file:

We used HTML<input type="file">Element to allow users to upload KML files. passFileReaderobject, we are able to read the contents of the file and pass it to the OpenLayersKMLFormat parser.

2. Show the map:

Through the OpenLayers library, we useTileThe layer loads the basemap (OSM) and passesVectorLayerLoading and displaying geotagging in KML files (Placemark)。

3. Style settings:

We are for eachPlacemarkBasic styles (purple fill, orange border and text) are set to make it easier to distinguish on the map.

4. Data projection:

Geographic data in KML files is usually usedEPSG:4326Projection, while OpenLayers maps useEPSG:3857projection. For correct display, we perform projection conversion when reading KML data.

5. Summary

With this article's implementation, you can easily upload a KML file in Vue 3 and display it on a map. KML files are a standard geographic data format and are widely used in the Geographic Information System (GIS). Through the combination of OpenLayers and Vue 3, you can easily visualize and interact map data. I hope this article will be helpful to you. If you have any questions, please leave a message in the comment area.

This is the article about uploading KML files in Vue 3 and displaying them on the map. For more related contents of Vue uploading KML files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!