【发布时间】: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