【问题标题】:Google Maps API - click event not workingGoogle Maps API - 点击事件不起作用
【发布时间】:2013-07-30 11:40:06
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    看起来像是一个范围界定问题。 placeMarker 位于 initialize 之外,其中定义了 map。尝试在 initialize 函数内移动 placeMarker。或者将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);
            };
    

    【讨论】:

    • 我更新了代码,并将地图作为参数传递给 placeMarker,但在我点击的地方仍然看不到任何标记。
    • 更新了答案。如您所见,我没有使用 CoffeeScript。也许移动方法是要走的路。
    • 我更新了代码并把它放在初始化里面,还是不行:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多