【问题标题】:map.setCenter undefinedmap.setCenter 未定义
【发布时间】:2018-05-21 08:40:37
【问题描述】:

我正在使用 GoogleMaps,并希望在方向改变时将其居中,但当我打电话时

map.setCenter({...})

我收到一个未定义的 setCenter 错误。

这是我的代码:

let GoogleMap = {
  lat : "",
  lng : "",
  map : {},
  marker : {},
  point : {},

  init() {
    return this
  },

  create(lat, lng) {
    this.lat = lat
    this.lng = lng
    this.point = {lat: lat,lng: lng};

    this.map = new google.maps.Map(document.getElementById('map'), {
      center: this.point,
      zoom: 17
    });

    this.marker = new google.maps.Marker({
      map: this.map,
      position: this.point
    });

    window.addEventListener('orientationchange', this.doOnOrientationChange);
  },

  doOnOrientationChange() {
    this.map.setCenter({lat: this.lat, lng: this.lng})
  }
}

export default GoogleMap

文档:https://developers.google.com/maps/documentation/javascript/reference#Map

我从 https://maps.googleapis.com/maps/api/js?key=KEY&libraries=geometry,places 获取 google maps api

有什么想法吗?

【问题讨论】:

  • 你是否提供了 lat 和 lng 的值,如果你提供了所有代码可能更容易调试
  • 请访问此解决方案为您解决问题:stackoverflow.com/questions/19537225/…
  • Jason,传入 create 函数的 lat/lng 值只是浮点数,地图显示正常,我遇到的问题是在 doOreientationChange 函数中的地图对象上使用 setCenter 方法- 当方向改变时。
  • 感谢 NikuNj,但您的回答并没有解决我的问题,即; map.setCenter = 未定义。地图显示正常,应该是这样,我的问题是 setCenter 函数,以及为什么它在我的地图对象上不存在。
  • 我怀疑this 不是您在定向事件处理函数中所期望的。

标签: google-maps google-maps-api-3


【解决方案1】:

感谢 geocodezip,问题是范围界定,而这不在方向事件处理程序中的正确范围内。

解决方法是使用绑定方法

window.addEventListener('orientationchange', this.orientationChange.bind(this));

完整的工作代码:

let GoogleMap = {
  lat : "",
  lng : "",
  map : {},
  marker : {},
  point : {},

  init() {
    return this
  },

  create(lat, lng) {
    this.lat = lat
    this.lng = lng
    this.point = {lat: lat,lng: lng};

    this.map = new google.maps.Map(document.getElementById('map'), {
      center: this.point,
      zoom: 17
    });

    this.marker = new google.maps.Marker({
      map: this.map,
      position: this.point
    });

    window.addEventListener('orientationchange', this.orientationChange.bind(this));
  },

  orientationChange() {
    this.map.setCenter({lat: this.lat, lng: this.lng})
  }
}

export default GoogleMap

当方向改变时,地图现在会按预期居中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-21
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    相关资源
    最近更新 更多