【问题标题】:Google Maps v3 Marker Always Appears at Top LeftGoogle Maps v3 标记始终出现在左上角
【发布时间】:2012-11-27 16:49:32
【问题描述】:

我正在编写一些 Google Maps API v3 代码,它似乎与多个标记一起工作得很好,但是当只有 1 个时,它总是将标记绘制在地图的左上角,就在可见区域之外:

这是我的咖啡脚本代码:

class SimpleMap
    constructor: (div_id, lat = 40.783627, lng = -73.942583) ->
        # L.Icon.Default.imagePath = "/assets"
        @div_id = div_id
        @map_options = {center: new google.maps.LatLng(lat, lng), zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP}
        @markers = []
        @map = new google.maps.Map document.getElementById(div_id), @map_options
        @loadMarkers() # gets them and plots on the map
        @autoFit()
    loadMarkers: ->
        items = $(".grid-item[data-lat], .apartment[data-lat]")
        for item in items
        console.log "Adding #{item}"
        @addMarker(item)
    @autoFit()

    addMarker: (item) ->
        console.log "Adding marker"
        lat = $(item).attr("data-lat")
        lng = $(item).attr("data-lng")

        console.log "#{lat}, #{lng}"

        marker = new google.maps.Marker(
            position: new google.maps.LatLng lat, lng
            map: @map
            title: "This is my marker"
        )

        @markers.push marker

    autoFit: ->
        bounds = new google.maps.LatLngBounds()
        for marker in @markers
            bounds.extend marker.getPosition()
        @map.fitBounds bounds
        # if you leave out the below, the marker appears int he same position as in the screenshot (slightly off screen) but at the max zoom level. 
        listener = google.maps.event.addListener(@map, "idle", =>
            @map.setZoom 9 if @map.getZoom() > 8
            @map.setCenter @markers[0].getPosition()
            google.maps.event.removeListener listener
        )

地图似乎忽略了我设置setCenter(@markers[0].getPosition()) 的尝试。有什么想法吗?

【问题讨论】:

  • 在创建 Map 对象之前确保您的地图 DIV 具有大小(宽度和高度),并且 lat 和 lng 实际上是数字而不是字符串。如有必要,请使用 parseFloat(lat) 和 parseFloat(lng)。
  • loadMarkers 发生了什么?如果有网络流量,则可能会在加载数据之前调用 autofit。
  • 我添加了 loadMarkers 的代码。在这种情况下,我从与地图位于同一页面上的 HTML 加载标记。地图 div 也通过 CSS 明确设置了样式,我正在使用 LatLngs 创建标记,而不是字符串——标记本身总是出现在正确的位置,只有一个标记时,缩放/中心问题仍然存在。使用多个标记,它可以很好地显示并合理地适应边界。

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


【解决方案1】:

我认为问题出在:

    bounds = new google.maps.LatLngBounds()
    for marker in @markers
        bounds.extend marker.getPosition()
    @map.fitBounds bounds

如果您正在扩展当前地图边界以包含所有标记,但您只有一个标记,则边界将以标记位于地图边界边界中的方式扩展。

问候

【讨论】:

    【解决方案2】:

    在 cmets 之后,仅当有 1 个标记时才会出现此问题。

    基于这一事实,我将问题归结为这一行:

    @map.fitBounds bounds
    

    当只有 1 个标记时,边界的 NE 角等于 SW 角。

    在这种情况下,当您将边界用作 fitBounds() 参数时,我注意到了意外的交互。

    建议:

    只有在至少有 2 个标记时才使用 fitBounds()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      • 2011-12-17
      • 1970-01-01
      • 2013-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多