Vue2-google-maps Api how to recenter map

こ雲淡風輕ζ 提交于 2021-01-29 06:33:45

问题


I am using the vue2-google-maps api with and I want to have a button that will change where the map is centered on. What code do I need to include to get the map re-centered.

I've tried different functions such as map_center and mapCenter, but I just can't find the right one to use, even after many web searches.

<div>
  <button @click="setCenter">Re-center</button>
  <br/>
</div>
<gmap-map
  :center="{ lat: 41.693206, lng: -86.228631 }"
  :zoom="12"
  style="width:100%;  height: 65vh;"
  :options="{
    zoomControl: true,
    mapTypeControl: false,
    scaleControl: false,
    streetViewControl: false,
    rotateControl: false,
    fullscreenControl: false,
    disableDefaultUi: false
  }"
>
</gmap-map>

<script>
export default {
  name: 'Home',
  methods: {
    setCenter () {
      this.map_center = {lat: '41.9028', lng: '12.4964'}
    }
  }
}
</script>

In main.js:

import * as VueGoogleMaps from 'vue2-google-maps'

Vue.use(VueGoogleMaps, {
  load: {
    key: 'AIzaSyBNGgSXjtrJCMkZaqoxo2KGDe-DdJUVMa0',
    libraries: 'places'
  }
})

I expected that when the button is clicked, the map would move from South Bend, IN to Rome, Italy. However, nothing happens when the button is clicked.


回答1:


You have to create a data variable called map_center, so that it's reactive:

export default {
    name: 'Home',
    data() {
        return {
            map_center: { lat: 41.693206, lng: -86.228631 }, 
        };
     },
     methods: {

Then set your <gmap-map> component's center to use the map_center variable:

<gmap-map
    :center="map_center"
    :zoom="12"

I haven't tested the solution. So, if this doesn't work, something very close to it will.




回答2:


lat and lng values are provided as a string values:

{lat: '41.9028', lng: '12.4964'}
       ^^^^^^^^       ^^^^^^^^   
        expects number

which is not correct since Map component expects center property to be of LatLng or LatLngLiteral type.

Here is an updated example which demonstrates how to center a map on button click:

<template>
  <div>
    <div>
      <button @click="setCenter">Re-center</button>
      <br />
    </div>
    <GmapMap :center="center" :zoom="zoom" style="width:100%;  height: 65vh;"></GmapMap>
  </div>
</template>
<script>
export default {
  name: "Home",
  data() {
    return {
      zoom: 8,
      center: { lat: 45.518, lng: -122.672 }
    };
  },
  methods: {
    setCenter() {
      this.center = { lat: 41.9028, lng: 12.4964 };
    }
  }
};
</script>


来源:https://stackoverflow.com/questions/56838714/vue2-google-maps-api-how-to-recenter-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!