Google Maps API - 点击活动无效

时间:2013-07-29 03:44:22

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

以下代码呈现地图,但回调未在click事件上运行。有什么想法吗?

google.maps.visualRefresh = true
url = 'http://localhost:3000/closeby'

getCloseBy = (pos) ->
    $.post url, {'center': pos}

initialize = ->
    mapOptions = 
        zoom: 15
        mapTypeId: google.maps.MapTypeId.ROADMAP
    map = new google.maps.Map document.getElementById('map-canvas'), mapOptions

    if navigator.geolocation
    navigator.geolocation.getCurrentPosition (position)->
        pos = new google.maps.LatLng position.coords.latitude, position.coords.longitude
        infowindow = new google.maps.InfoWindow
            map: map
            position: pos
        map.setCenter pos
    , ->
        handleNoGeolocation true        
    else 
    handleNoGeolocation false       

  handleNoGeolocation = (errorFlag) ->
        if errorFlag
            content = 'Geolocation failed'
        else
            content = 'Your browser does not support Geolocation'
        options = 
            map: map
            position: new google.maps.LatLng 60, 105
            content: content
        infowindow = new google.maps.InfoWindow options
        map.setCenter options.position

  placeMarker = (location) ->
    marker = new google.maps.Marker
        position: location
        map: map

  google.maps.event.addListener map, 'click', (event)->
    placeMarker event.latLng    

google.maps.event.addDomListener window, 'load', initialize

1 个答案:

答案 0 :(得分:0)

看起来像是一个范围问题。 placeMarker位于initialize之外,其中map已定义。尝试在placeMarker功能中移动initialize。或者将map作为参数传递给placeMarker

已更新:我没有使用CoffeeScript,但在initialize内呈现(而不是传递map)应该有效:

        var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

        google.maps.event.addListener(map, 'click', function(event) {
            placeMarker(event.latLng);
        });

        var placeMarker = function (location) {
            var options = { position: location, map: map };
            var marker = new google.maps.Marker(options);
        };