分享

如何在 Vue 中显示地图.js使用 MapLibre GL JS

 Jcstone 2023-06-09 发布于湖北

在本教程中,您将学习如何创建一个 Vue.js 组件来使用 MapLibre GL JS 渲染地图。我们将一起制作一个简单的全屏地图应用程序,作为如何将MapTiler地图与Vue.js和MapLibre GL .js JS一起使用的示例。

在本教程结束时,您将能够在指定位置创建带有标记的全屏地图。您的最终地图将如下所示:

在 Vue 中显示地图.js使用 MapLibre GL JS

开始

完成本教程的最低要求。

  • Vue的一些经验.js对于本教程,您不需要太多使用 Vue.js 的经验,但您应该熟悉基本概念和工作流程。

  • MapTiler API key.您的MapTiler帐户访问密钥位于您的MapTiler云帐户页面上或免费获取API密钥。

  • MapLibre GL JS.用于构建 Web 地图的 JavaScript 库。在本教程中,您将学习如何安装它。

  • Node.js 和 npm。在本地运行 Vue.js 应用程序是必需的。节点.js

  • Vue CLI。你需要安装 Vue CLI。要安装 Vue CLI,请打开终端窗口并运行以下命令:

npm install -g @vue/cli

砰砰��

复制

创建应用

在此步骤中,我们将学习如何创建 Vue.js 应用程序。

要创建一个新的 Vue.js 项目,请在命令行中运行:

vue create my-vue-map

砰砰��

复制

该命令会提示您输入有关要包含在初始应用程序中的功能的信息。选择该选项。vue createDefault (Vue 3) ([Vue 3] babel, eslint)

Vue.js CLI 选项

使用箭头键并按 Enter 或 Return 键选择一个选项。Vue CLI 安装必要的 Vue.js npm 包和其他依赖项,并创建一个新的工作区和一个简单的欢迎应用程序,准备运行。有关更多信息,请参阅创建项目。

导航到新创建的项目文件夹my-vue-map

cd my-vue-map

砰砰��

复制

在新创建的项目文件夹中,运行以启动本地环境。您会发现您的应用程序在地址上运行。npm run servehttp://localhost:8080/

现在,您应该在浏览器中看到该应用程序。

Vue.js应用程序

安装和设置

要安装 MapLibre GL 库,请导航到您的项目文件夹并运行以下命令:

npm i maplibre-gl

砰砰��

复制

导航到该文件夹并删除文件的所有内容。在文件中写入以下行srcApp.vueApp.vue

<template>
  <div class="app">
    This is my map App  </div></template><script>export default {
  name: 'App',
  components: {
  }}</script><style>body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;}code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
    monospace;}.app {
  text-align: center;}</style>

.HTML

复制

现在,您应该在浏览器中看到“这是我的地图应用程序”。

导航到文件夹并删除 de 文件src/componentsHelloWorld.vue

创建导航栏组件

在此步骤中,我们将创建一个简单的标题导航栏组件。

创建一个在文件夹内调用的新文件并编写以下行:Navbar.vuecomponents

<template>
  <div class="heading">
    <h1>This is my map App</h1>
  </div></template><script>export default {
  name: 'Navbar'}</script><style scoped>.heading {
  margin: 0;
  padding: 0px;
  background-color: black;
  color: white;}.heading > h1 {
  padding: 20px;
  margin: 0;}</style>

.HTML

复制

Finally, to display the we need to import the Navbar component and add it to our main component template section .NavbarApp.vue

Import the navbar component into script blockApp.vue

<script>
  import Navbar from './components/Navbar.vue';

  export default {
    name: 'App',
    components: {
      Navbar    }
  }</script>

HTML

Copy

Replace the text This is my map Appwith . Your file should look like this:<Navbar />App.vue

<template>
  <div class="app">
    <Navbar />
  </div></template><script>import Navbar from './components/Navbar.vue';export default {
  name: 'App',
  components: {
    Navbar  }}</script><style>body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;}code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
    monospace;}.app {
  text-align: center;}</style>

HTML

Copy

Now you should see the black navbar at the top of your browser.

App navigation bar

Create a map component

In this step, we will create a simple map component.

Create a new file called inside the folder and write these lines:Map.vuecomponents

<template>
  <div class="map-wrap">
    <a href="https://www." class="watermark"><img
        src="https://api./resources/logo.svg" alt="MapTiler logo"/></a>
    <div class="map" ref="mapContainer"></div>
  </div></template><script>import { Map } from 'maplibre-gl';import { shallowRef, onMounted, onUnmounted, markRaw } from 'vue';export default {
  name: "Map",
  setup () {
    const mapContainer = shallowRef(null);
    const map = shallowRef(null);

    onMounted(() => {
      const apiKey = 'YOUR_MAPTILER_API_KEY_HERE';

      const initialState = { lng: 139.753, lat: 35.6844, zoom: 14 };

      map.value = markRaw(new Map({
        container: mapContainer.value,
        style: `https://api./maps/streets-v2/style.json?key=${apiKey}`,
        center: [initialState.lng, initialState.lat],
        zoom: initialState.zoom      }));

    }),
    onUnmounted(() => {
      map.value?.remove();
    })

    return {
      map, mapContainer    };
  }};</script><style scoped>@import '~maplibre-gl/dist/maplibre-gl.css';.map-wrap {
  position: relative;
  width: 100%;
  height: calc(100vh - 77px); /* calculate height of the screen minus the heading */}.map {
  position: absolute;
  width: 100%;
  height: 100%;}.watermark {
  position: absolute;
  left: 10px;
  bottom: 10px;
  z-index: 999;}</style>

HTML

Copy

We use on the map itself and on the wrap around the map for more possibilities in future styling.position: absoluteposition: relative

Here you will need to replace with your actual MapTiler API key.YOUR_MAPTILER_API_KEY_HERE

  1. The option sets the DOM element in which the map will be rendered. We will assign the ref expected by our component to an HTML element, which will act as a container. Keep in mind that the reference to can only be used after the execution of the hook.containermapContainermapContaineronMounted

  2. The option defines what style is the map going to use.style

  3. The and options set the starting position of the map.centerzoom

  4. The function does the cleanup that should occur when the instance is destroyed.onUnmounted

Render a map

Finally, to display the we need to import the Map component and add it to our main component .MapApp.vue

Import the map component into script blockApp.vue

<script>import Navbar from './components/Navbar.vue';import Map from './components/Map.vue';export default {
  name: 'App',
  components: {
    Navbar,
    Map  }}</script>

HTML

Copy

Add the just below the Navbar in the template section. The template block should look like this<Map />

<template>
  <div class="app">
    <Navbar />
    <Map />
  </div></template>

HTML

Copy

With everything done up until now, you should be able see your beautiful map in your browser.

Full-screen map

Your file should look like this:App.vue

<template>
  <div class="app">
    <Navbar />
    <Map />
  </div></template><script>import Navbar from './components/Navbar.vue';import Map from './components/Map.vue';export default {
  name: 'App',
  components: {
    Navbar,
    Map  }}</script><style>body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;}code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
    monospace;}.app {
  text-align: center;}</style>

HTML

Copy

Basic additional options

The last topic of this tutorial will be adding basic objects to your map. For more detailed information you can visit the MapLibre documentation.

Map Controls

We will navigate back to our file and add map navigation controls to our map.Map.vue

Add the next to the Map object import from MapLibre GL.NavigationControl

import { Map, NavigationControl } from 'maplibre-gl';

JavaScript

Copy

On line 30 (just after the initialization of the map) of the file, add the following line:Map.vue

map.value.addControl(new NavigationControl(), 'top-right');

JavaScript

Copy

new NavigationControl()will create new controls object which we add to current map using the function in the position.addControl()'top-right'

Map navigation control

Map marker

Another basic thing to add to your map could be a marker of some location.

Add the next to the Map object import from MapLibre GL.Marker

import { Map, NavigationControl, Marker } from 'maplibre-gl';

JavaScript

Copy

In the following line where we declare the navigation control, we add these lines:

new Marker({color: "#FF0000"})
  .setLngLat([139.7525,35.6846])
  .addTo(map);

JavaScript

Copy

We create a new marker using the function. We added the color option to make it red, then set Lng/Lat of the marker using function, and finally added it to the current map using function.Marker.setLngLat().addTo()

We are finished with our basic map objects, your file should look like this:Map.vue

<template>
  <div class="map-wrap">
    <a href="https://www." class="watermark"><img
        src="https://api./resources/logo.svg" alt="MapTiler logo"/></a>
    <div class="map" ref="mapContainer"></div>
  </div></template><script>import { Map, NavigationControl, Marker } from 'maplibre-gl';import { shallowRef, onMounted, onUnmounted, markRaw } from 'vue';export default {
  name: "Map",
  setup () {
    const mapContainer = shallowRef(null);
    const map = shallowRef(null);

    onMounted(() => {
      const apiKey = 'YOUR_MAPTILER_API_KEY_HERE';

      const initialState = { lng: 139.753, lat: 35.6844, zoom: 14 };

      map.value = markRaw(new Map({
        container: mapContainer.value,
        style: `https://api./maps/streets-v2/style.json?key=${apiKey}`,
        center: [initialState.lng, initialState.lat],
        zoom: initialState.zoom      }));
      map.value.addControl(new NavigationControl(), 'top-right');
      new Marker({color: "#FF0000"})
        .setLngLat([139.7525,35.6846])
        .addTo(map.value);
    }),
    onUnmounted(() => {
      map.value?.remove();
    })

    return {
      map, mapContainer    };
  }};</script><style scoped>@import '~maplibre-gl/dist/maplibre-gl.css';.map-wrap {
  position: relative;
  width: 100%;
  height: calc(100vh - 77px); /* calculate height of the screen minus the heading */}.map {
  position: absolute;
  width: 100%;
  height: 100%;}.watermark {
  position: absolute;
  left: 10px;
  bottom: 10px;
  z-index: 999;}</style>

HTML

Copy

使用 React JS 显示 MapLibre GL JS 地图

要下载的完整代码

我们利用本教程的结果创建了一个模板,该模板将作为构建未来应用程序的基础。您可以在 Vue.js 的 MapLibre 模板中GitHubLogo访问模板存储库。

在线演示:

您可以在 https://labs./vue-template-maplibre-gl-js/

结论

祝贺!您已经使用 Vue.js 完成了简单的全屏地图应用程序,在东京皇宫上用标记显示东京。您可以在 MapLibre API 参考中为您的地图探索有关 MapLibre GL JS 的更多信息。

有用的链接

MapTiler - JavaScript Maps API

Vue.js

NPM - MapLibre GL

MapLibre official web

MapTiler Cloud - Customize

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约