I’m writing some Google Maps API v3 code, which seems to work just fine with multiple markers, but when there’s only 1, it always plots the marker in the top left of the map, just beyond the visible area:

Here’s my coffeescript code:
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
)
The map seems to ignore my attempts to set setCenter(@markers[0].getPosition()). Any ideas?
I believe the issue is in:
where you are extending the current map bounds to include all markers, but you have only one marker, the bounds will extend in a way that the marker will be in the map limit border.
Regards