如何使用 vue-google-maps 在 Vue 中使用谷歌地图

介绍

谷歌地图提供了一套可靠的API(LINK0),用于构建和与地图互动,可视化位置数据,并通过自动完成搜索,仅举几个。

vue-google-maps,它已更新为Vue.js 2,提供Vue.js应用程序的工具来利用这些API。

在本教程中,您将使用vue2-google-maps库创建一张使用 autocomplete 显示位置的地图。

前提条件

要完成本教程,您将需要:

  • 这将需要一个 Google 帐户
  • 登录到 Google Cloud Platform Console
  • 创建一个新项目
  • 启用 Google Maps 和 JavaScript API 定位项目
  • 以及为

<$>[警告] 警告: 若要在使用 Google 地图 API 时避免出现仅用于开发目的消息,您需要提供有效的信用卡并与 Google Cloud Project 的计费帐户相关联。

此教程是用 Node v14.13.1, 'npm' v6.14.8, 'vue' v2.6.11 和 'vue2-google-maps' v0.10.7 进行验证的。

步骤1 - 设置项目

您可以使用 @vue/cli创建新的 Vue.js 项目。

在您的终端窗口中,使用以下命令:

1npx @vue/cli create --default vue-google-maps-example

这将使用默认配置来创建 Vue.js 项目。

导航到新创建的项目目录:

1cd vue-google-maps-example

启动项目以确保没有错误。

1npm run serve

如果您访问本地应用程序(通常在localhost:8080)在您的 Web 浏览器中,您将看到一个欢迎来到您的 Vue.js 应用程序的消息。

有了这个设置,您可以安装vue2-google-maps包。

步骤 2 — 实施vue2-google-maps

接下来,您将安装vue2-google-maps包,并将其添加到您的Vue.js项目中。

首先,您需要安装vue2-google-maps:

1npm install [email protected]

在代码编辑器中打开src/main.js

导入‘vue2-google-maps’并使用您的 API 密钥实例化插件:

 1[label src/main.js]
 2import Vue from 'vue'
 3import * as VueGoogleMaps from 'vue2-google-maps'
 4import App from './App.vue'
 5
 6Vue.config.productionTip = false
 7
 8Vue.use(VueGoogleMaps, {
 9  load: {
10    key: 'YOUR_GOOGLE_MAPS_API_KEY_GOES_HERE',
11    libraries: 'places',
12  }
13});
14
15new Vue({
16  render: h => h(App),
17}).$mount('#app')

请务必用实际的 API 密钥代替YOUR_GOOGLE_MAPS_API_KEY_GOES_HERE 并指定使用自动完成功能所需的位置库。

<$>[警告] 警告: 请确保避免将 API 密钥保存到您向公共存储库(如 GitHub)承诺的任何文件中,因为它可以被其他人用于您不打算的目的。

随着应用程序已准备好使用vue2-google-maps,您可以创建一个自定义组件来使用它。

步骤 3 – 构建地图搜索组件

接下来,您将创建一个使用GmapMap,GmapAutocompleteGmapMarker的新组件。

在代码编辑器中,创建一个名为GoogleMap.vue的新组件:

 1[label src/components/GoogleMap.vue]
 2<template>
 3  <div>
 4    <div>
 5      <h2>Search and add a pin</h2>
 6    </div>
 7    <br>
 8  </div>
 9</template>
10
11<script>
12export default {
13  name: 'GoogleMap'
14}
15</script>

然后,在代码编辑器中,修改App.vue,以使用此新组件:

 1[label src/App.vue]
 2<template>
 3  <div id="app">
 4    <GoogleMap />
 5  </div>
 6</template>
 7
 8<script>
 9import GoogleMap from './components/GoogleMap.vue'
10
11export default {
12  name: 'App',
13  components: {
14    GoogleMap
15  }
16}
17</script>

当你在网页浏览器中访问你的应用程序时,你应该观察到一个搜索并添加点的消息. 这个检查点有助于验证到目前为止的一切都正常工作。

对于教程的目的,您可以定义一个默认的中心位置,其纬度和长度坐标与加拿大蒙特利尔(`45.508, -73.587)相匹配。

添加GmapMap组件,并定义中心,缩小风格:

 1[label src/components/GoogleMap.vue]
 2<template>
 3  <div>
 4    <div>
 5      <h2>Search and add a pin</h2>
 6    </div>
 7    <br>
 8    <GmapMap
 9      :center='center'
10      :zoom='12'
11      style='width:100%;  height: 400px;'
12    />
13  </div>
14</template>
15
16<script>
17export default {
18  name: 'GoogleMap',
19  data() {
20    return {
21      center: { lat: 45.508, lng: -73.587 },
22    }
23  },
24};
25</script>

在这一点上,如果你在浏览器中访问你的应用程序,你应该看到一个以蒙特利尔为中心的Google地图。

接下来,你会添加一些地理位置来获取用户的当前位置,并相应地图更新:

 1[label src/components/GoogleMap.vue]
 2<template>
 3  <div>
 4    <div>
 5      <h2>Search and add a pin</h2>
 6    </div>
 7    <br>
 8    <GmapMap
 9      :center='center'
10      :zoom='12'
11      style='width:100%;  height: 400px;'
12    />
13  </div>
14</template>
15
16<script>
17export default {
18  name: 'GoogleMap',
19  data() {
20    return {
21      center: { lat: 45.508, lng: -73.587 },
22    }
23  },
24  mounted() {
25    this.geolocate();
26  },
27  methods: {
28    geolocate: function() {
29      navigator.geolocation.getCurrentPosition(position => {
30        this.center = {
31          lat: position.coords.latitude,
32          lng: position.coords.longitude,
33        };
34      });
35    },
36  },
37};
38</script>

在此时,如果你在浏览器中访问你的应用程序,你应该看到一个以你的位置为中心的Google地图。

<$>[注] **注:**您可能需要接受提示,以允许您的浏览器使用您的地理位置信息。

接下来,您将添加自动完成,让用户更改地图上的位置:

 1[label src/components/GoogleMap.vue]
 2<template>
 3  <div>
 4    <div>
 5      <h2>Search and add a pin</h2>
 6      <GmapAutocomplete
 7        @place_changed='setPlace'
 8      />
 9    </div>
10    <br>
11    <GmapMap
12      :center='center'
13      :zoom='12'
14      style='width:100%;  height: 400px;'
15    />
16  </div>
17</template>
18
19<script>
20export default {
21  name: 'GoogleMap',
22  data() {
23    return {
24      center: { lat: 45.508, lng: -73.587 },
25      currentPlace: null,
26    }
27  },
28  mounted() {
29    this.geolocate();
30  },
31  methods: {
32    setPlace(place) {
33      this.currentPlace = place;
34    },
35    geolocate: function() {
36      navigator.geolocation.getCurrentPosition(position => {
37        this.center = {
38          lat: position.coords.latitude,
39          lng: position.coords.longitude,
40        };
41      });
42    },
43  },
44};
45</script>

此代码将添加GmapAutocomplete组件.当更新位置时,将呼叫setPlace,并更新currentPlace值。

在此时,如果您在浏览器中访问您的应用程序,您将看到一个自动填写字段,根据字段中输入的内容提供位置建议。

接下来,您将添加标记来表示地图上的位置:

 1[label src/components/GoogleMap.vue]
 2<template>
 3  <div>
 4    <div>
 5      <h2>Search and add a pin</h2>
 6      <GmapAutocomplete
 7        @place_changed='setPlace'
 8      />
 9      <button
10        @click='addMarker'
11      >
12        Add
13      </button>
14    </div>
15    <br>
16    <GmapMap
17      :center='center'
18      :zoom='12'
19      style='width:100%;  height: 400px;'
20    >
21      <GmapMarker
22        :key="index"
23        v-for="(m, index) in markers"
24        :position="m.position"
25        @click="center=m.position"
26      />
27    </GmapMap>
28  </div>
29</template>
30
31<script>
32export default {
33  name: 'GoogleMap',
34  data() {
35    return {
36      center: { lat: 45.508, lng: -73.587 },
37      currentPlace: null,
38      markers: [],
39      places: [],
40    }
41  },
42  mounted() {
43    this.geolocate();
44  },
45  methods: {
46    setPlace(place) {
47      this.currentPlace = place;
48    },
49    addMarker() {
50      if (this.currentPlace) {
51        const marker = {
52          lat: this.currentPlace.geometry.location.lat(),
53          lng: this.currentPlace.geometry.location.lng(),
54        };
55        this.markers.push({ position: marker });
56        this.places.push(this.currentPlace);
57        this.center = marker;
58        this.currentPlace = null;
59      }
60    },
61    geolocate: function() {
62      navigator.geolocation.getCurrentPosition(position => {
63        this.center = {
64          lat: position.coords.latitude,
65          lng: position.coords.longitude,
66        };
67      });
68    },
69  },
70};
71</script>

让我们来回顾一下你在这里取得的成就。

您创建了一个GmapAutocomplete和一个GmapMap(有GmapMarker的孩子)。 最初,地图是以蒙特利尔为中心创建的。

一旦用户输入搜索术语并从自动完成下载中进行选择,GmapAutocomplete会调用setPlace。此选项会被存储在currentPlace。当点击添加按钮时,它会调用addPlace,将标记位置存储在标记中,从而触发GmapMap(随后是GmapMarker)进行更新。

此外,您将每个位置的完整位置对象存储在位置属性中,这将允许从自动完成查询中返回的任何额外数据在该组件或任何必要的子组件中使用。

app应该是这样的(如果你在冰岛):

Vue.js Google Maps example with Iceland centered in the middle

<$>[警告] **警告:**完成实验后,建议您登录您的 Google Cloud Console 并删除 API 密钥并删除相关的计费帐户以避免潜在的滥用。

您现在有一个具有自动完成和标记功能的Google地图。

结论

在本教程中,您了解如何在 Vue.js 应用程序中使用vue2-google-maps和 Google 地图 API 功能。

这有很大的潜力向游客展示业务,旅游目的地和景点的位置。

如果您想了解有关 Vue.js 的更多信息,请参阅 我们的 Vue.js 主题页面以获取练习和编程项目。

Published At
Categories with 技术
Tagged with
comments powered by Disqus