Pull to refresh

Vue добавляем нативную карту Google Map без библиотек

Google Maps API — Набор приложений, построенных на основе бесплатного картографического сервиса и технологии, предоставляемых компанией Google.

Я покажу вам, как подключить и использовать нативную карту Google Maps без использования библиотек для Vuejs.

Добавляем Google Maps


Первое что нужно сделать, это добавить в наш основной index.html 2 скрипта, где Your_API_Key ваш ключ Google Maps Key, второй скрипт нужен для marker clusterer:

<!-- google map-->
<script src="https://maps.googleapis.com/maps/api/js?key=Your_API_Key&language=ru&region=RU">
  </script>
  <!-- google map markerclusterer-->
  <script src="https://unpkg.com/@google/markerclustererplus@4.0.1/dist/markerclustererplus.min.js"> </script>

Создание компонента Google Map


Так как это компонент, сразу определим, что будем пробрасывать в props, locations — это ваши данные координаты точек:

<template>
  <div ref='googleMap' class='google-map'></div>
</template>

export default {
name: 'GoogleMap',
  props: {
    locations: {
      type: [Array, Object],
      required: true
    }
},
data() {
    return {
      bounds: new google.maps.LatLngBounds(), // Авто масштабирование карты
      mapOptions: {
        center: { lat: -34.397, lng: 140.644 },
        zoomControl: true,
        zoom: 8,
        gestureHandling: 'cooperative'
    }
}

Сам locations выглядит так:

locations: {
 imgClusterUrl: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m',
  locations: [
    {id: 1, lat: -31.563944, lng: 147.154355, name_point: 'A', title: 'text on hover'},
    {id: 2, lat: -33.718234, lng: 150.363181, name_point: 'B', title: 'text on hover'},
    {id: 3, lat: -33.727111, lng: 150.371124, name_point: 'C', title: 'text on hover'},
    {id: 4, lat: -33.848588, lng: 151.209834, name_point: 'D', title: 'text on hover'}, 
    {id: 5, lat: -34.853202, lng: 150.55, name_point: 'E', title: 'text on hover'}, 
    {id: 6, lat: -34.851702, lng: 150.216968, name_point: 'F', title: 'text on hover'}
  ],
}

и сразу добавим стили:

<style lang="scss">
.google-map {
  width: 100%;
  height: 450px;
}
</style>

добавим наш метод initMap:

methods: {
 // Сразу вытащим переменные которые нам понадобятся
 const  { imgClusterUrl, locations } = this.locations

  initMap() {
   // create map
    const map = new google.maps.Map(this.$refs.googleMap, {
      ...this.mapOptions
    })
  }
}

и добавим его при монтировании:

mounted() {
  this.initMap()
}

Далее, нам понадобится маркеры, допишем наш метод initMap():

methods: {
    initMap() {
      const  { imgClusterUrl, locations } = this.locations
      // create map
      const map = new google.maps.Map(this.$refs.googleMap, {
        ...this.mapOptions
      })
      
      // create Markers
      let markers = locations.map((location) => {
        // set locations for auto zoom map
        const setLocations = new google.maps.LatLng(location.lat, location.lng)
        this.bounds.extend(setLocations)

        // set Markers on Map
        return new google.maps.Marker({
          position: location,
          map: map,
          label: location.name_point,
          title: location.title  + ' ' + location.name_point,
        })
      })

      // create MarkerClusterer and add Image
      let markerCluster = new MarkerClusterer(map, markers,
        
        { imagePath: imgClusterUrl })

      // авто масштабирование
      map.fitBounds(this.bounds)
    },
}

Вот что в итоге у нас получилось:

image
Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.