我正在编写一些 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())
。有任何想法吗?