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

介绍

Google Maps 提供了一组强大的 API,用于构建地图并与之交互、可视化位置数据以及通过自动完成进行搜索,仅举几例。

vue-google-maps已针对 Vue.js 2 进行了更新,为 Vue.js 应用程序提供了利用这些 API 的工具。它带有一套完善的组件,用于与谷歌地图交互以及双向数据绑定。

在本教程中,您将使用该vue2-google-maps库并创建一个使用自动完成功能来显示位置的地图。

先决条件

要完成本教程,您需要:

警告:为避免在使用 Google Maps API 时出现“仅用于开发目的”消息,您需要提供有效的信用卡并与 Google Cloud 项目的结算帐户相关联。请注意与使用这些 API 相关的费用。

本教程已通过 Node v14.13.1、npmv6.14.8、vuev2.6.11 和vue2-google-mapsv0.10.7 验证。

步骤 1 — 设置项目

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

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

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

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

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

  • cd vue-google-maps-example

启动项目以验证没有错误。

  • npm run serve

如果您localhost:8080在 Web 浏览器中访问本地应用程序(通常位于),您将看到一条"Welcome to Your Vue.js App"消息。

设置好这个脚手架后,您可以安装该vue2-google-maps软件包。

第 2 步 – 实施 vue2-google-maps

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

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

  • npm install vue2-google-maps@0.10.7

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

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

源代码/main.js
import Vue from 'vue'
import * as VueGoogleMaps from 'vue2-google-maps'
import App from './App.vue'

Vue.config.productionTip = false

Vue.use(VueGoogleMaps, {
  load: {
    key: 'YOUR_GOOGLE_MAPS_API_KEY_GOES_HERE',
    libraries: 'places',
  }
});

new Vue({
  render: h => h(App),
}).$mount('#app')

请务必'YOUR_GOOGLE_MAPS_API_KEY_GOES_HERE'使用您的实际 API 密钥替换此外,指定places使用自动完成功能所需库。

警告:请务必避免将您的 API 密钥保存在您提交到公共存储库(如 GitHub)的任何文件中,因为它可能会被其他人用于您不想要的目的。

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

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

接下来,您将创建一个新的组件,它的用途GmapMapGmapAutocompleteGmapMarker

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

src/components/GoogleMap.vue
<template>
  <div>
    <div>
      <h2>Search and add a pin</h2>
    </div>
    <br>
  </div>
</template>

<script>
export default {
  name: 'GoogleMap'
}
</script>

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

源代码/App.vue
<template>
  <div id="app">
    <GoogleMap />
  </div>
</template>

<script>
import GoogleMap from './components/GoogleMap.vue'

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

当您在 Web 浏览器中访问您的应用程序时,您应该看到一条"Search and add a pin"消息。此检查点有助于验证到目前为止的一切是否正常工作。接下来,您将开始添加地图的所有部分。

出于教程目的,您可以center使用与加拿大蒙特利尔 ( 45.508, -73.587)对齐的经纬度坐标定义默认位置这将是您地图的初始焦点。随意更改这些值。

添加GmapMap组件。并定义center, zoom, 和style

src/components/GoogleMap.vue
<template>
  <div>
    <div>
      <h2>Search and add a pin</h2>
    </div>
    <br>
    <GmapMap
      :center='center'
      :zoom='12'
      style='width:100%;  height: 400px;'
    />
  </div>
</template>

<script>
export default {
  name: 'GoogleMap',
  data() {
    return {
      center: { lat: 45.508, lng: -73.587 },
    }
  },
};
</script>

此时,如果您在浏览器中访问您的应用程序,您应该会看到以蒙特利尔为中心的 Google 地图。

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

src/components/GoogleMap.vue
<template>
  <div>
    <div>
      <h2>Search and add a pin</h2>
    </div>
    <br>
    <GmapMap
      :center='center'
      :zoom='12'
      style='width:100%;  height: 400px;'
    />
  </div>
</template>

<script>
export default {
  name: 'GoogleMap',
  data() {
    return {
      center: { lat: 45.508, lng: -73.587 },
    }
  },
  mounted() {
    this.geolocate();
  },
  methods: {
    geolocate: function() {
      navigator.geolocation.getCurrentPosition(position => {
        this.center = {
          lat: position.coords.latitude,
          lng: position.coords.longitude,
        };
      });
    },
  },
};
</script>

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

注意:您可能需要接受提示以允许浏览器使用您的geolocation信息。

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

src/components/GoogleMap.vue
<template>
  <div>
    <div>
      <h2>Search and add a pin</h2>
      <GmapAutocomplete
        @place_changed='setPlace'
      />
    </div>
    <br>
    <GmapMap
      :center='center'
      :zoom='12'
      style='width:100%;  height: 400px;'
    />
  </div>
</template>

<script>
export default {
  name: 'GoogleMap',
  data() {
    return {
      center: { lat: 45.508, lng: -73.587 },
      currentPlace: null,
    }
  },
  mounted() {
    this.geolocate();
  },
  methods: {
    setPlace(place) {
      this.currentPlace = place;
    },
    geolocate: function() {
      navigator.geolocation.getCurrentPosition(position => {
        this.center = {
          lat: position.coords.latitude,
          lng: position.coords.longitude,
        };
      });
    },
  },
};
</script>

此代码将添加GmapAutocomplete组件。当它更新place, 时setPlace调用并currentPlace更新值。

此时,如果您在浏览器中访问您的应用程序,您将看到一个自动完成字段,该字段将根据字段中键入的内容提供位置建议。如果您感到好奇,可以添加一个console.logtosetPlace来检查place变量的值

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

src/components/GoogleMap.vue
<template>
  <div>
    <div>
      <h2>Search and add a pin</h2>
      <GmapAutocomplete
        @place_changed='setPlace'
      />
      <button
        @click='addMarker'
      >
        Add
      </button>
    </div>
    <br>
    <GmapMap
      :center='center'
      :zoom='12'
      style='width:100%;  height: 400px;'
    >
      <GmapMarker
        :key="index"
        v-for="(m, index) in markers"
        :position="m.position"
        @click="center=m.position"
      />
    </GmapMap>
  </div>
</template>

<script>
export default {
  name: 'GoogleMap',
  data() {
    return {
      center: { lat: 45.508, lng: -73.587 },
      currentPlace: null,
      markers: [],
      places: [],
    }
  },
  mounted() {
    this.geolocate();
  },
  methods: {
    setPlace(place) {
      this.currentPlace = place;
    },
    addMarker() {
      if (this.currentPlace) {
        const marker = {
          lat: this.currentPlace.geometry.location.lat(),
          lng: this.currentPlace.geometry.location.lng(),
        };
        this.markers.push({ position: marker });
        this.places.push(this.currentPlace);
        this.center = marker;
        this.currentPlace = null;
      }
    },
    geolocate: function() {
      navigator.geolocation.getCurrentPosition(position => {
        this.center = {
          lat: position.coords.latitude,
          lng: position.coords.longitude,
        };
      });
    },
  },
};
</script>

让我们回顾一下您在此处完成的工作。

您创建了 aGmapAutocomplete和 a GmapMap(与孩子GmapMarkers)。最初,地图是以蒙特利尔为中心创建的。在实例是 之后mounted(),您调用geolocate并重新居中。

一旦用户输入搜索词并从自动完成下拉列表中进行选择,GmapAutocomplete调用setPlace. 此选择然后存储在currentPlace. 单击添加按钮时,它调用addPlacewhich 将标记位置存储在 中markers,从而触发GmapMap(以及随后的GmapMarkers)更新。您还将更新center到最后一个标记的位置。

此外,您将每个地方的完整place对象存储places属性中。这将允许根据需要在此组件或任何子组件中使用从自动完成查询返回的任何其他数据。

“应用程序”应该是这样的(如果你在冰岛的话):

Vue.js 谷歌地图示例,冰岛居中

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

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

结论

在本教程中,您学习了如何vue2-google-maps在 Vue.js 应用程序中使用Google Maps API 功能。

这具有向访客显示企业、旅游目的地和兴趣点位置的巨大潜力。

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

觉得文章有用?

点个广告表达一下你的爱意吧 !😁