2011-05-24 80 views
0

我试图使用Google Maps for Rails gem来使用基于使用当前位置的自定义gmaps4rails_callback标记填充地图,但我似乎无法取代代码用户地理位置确定后触发的标记。基于地理位置填充Google Maps for Rails标记

application.js定义自定义映射的回调函数,有一个回调沿着getCurrentPosition

function nearby_locations(position) { 
    $.getJSON('locations/nearby.json', 
      { lat: "33.7012", long: "-117.8683" }, 
      function(data) { 
        Gmaps4Rails.replace_markers(data); 
      }); 
} 

function gmaps4rails_callback() { 
    navigator.geolocation.getCurrentPosition(nearby_locations); 
} 

现在,我使用硬编码纬度/经度数据,但最终我要去键关机真实数据中的position对象传递给我。手动运行getJSON调用可以正常工作,并且我的locations/nearby.json以正确的格式返回位置数据,并按预期更新标记。

我的视图模板只是使用

<%= gmaps("map_options" => {"auto_adjust" => true, "detect_location" => true}) %> 

现在我意识到,我可能做了地理查询两次,同时使用detect_location,然后调用getCurrentPosition,但在早期的尝试,在gmaps4rails_callback代码是被在浏览器(Safari)的地理定位许可甚至完成之前执行,所以我认为这会延迟执行,直到确定位置。

我以前显示的地图没有自定义gmaps4rails_callback,它工作正常,所以我知道我的jQuery和JavaScript文件被包括在内。

Google Maps for Rails有可能以某种方式设置了自己的getCurrentPosition回调函数,而我的函数被忽略了吗?在添加了一些调试日志记录之后,它看起来不像nearby_locations被调用。

回答

1

基本上,当你设置"detect_location" => true,这触发以下功能:

findUserLocation: function() { 
    if(navigator.geolocation) { 
    //try to retrieve user's position 
    navigator.geolocation.getCurrentPosition(function(position) { 
     //saves the position in the userLocation variable 
     Gmaps4Rails.userLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); 
      //change map's center to focus on user's geoloc if asked 
      if(Gmaps4Rails.map_options.center_on_user === true) { 
       Gmaps4Rails.map.setCenter(Gmaps4Rails.userLocation); 
      } 
    }, 
    function() { 
      //if failure, triggers the function if defined 
      if(this.fnSet("gmaps4rails_geolocation_failure")) { gmaps4rails_geolocation_failure(true); } 
     }); 
    } 
    else { 
     //if failure, triggers the function if defined 
     if(this.fnSet("gmaps4rails_geolocation_failure")) { gmaps4rails_geolocation_failure(false); } 
    } 
} 

所以,是的地理位置已经取得...或正在进行中。此功能在gmaps4rails_callback之前触发,但它是浏览器地理位置的难题:需要一个未定义的时间。

我想过提议在失败时回调,但并不认为有必要在成功中包含回调(我还没有确信)。

不幸的是,我不明白你的gmpas4rails_callback的问题:我有detection_location和回调,它按预期工作。

+0

感谢您确认幕后发生了什么。当我昨晚发布我的问题时,我没有深入了解代码。你能否确认gmaps4rails_callback的执行是否被阻止,直到用户权限被授予并且位置已经确定(或者触发失败动作)为止?从我自己的测试来看,似乎并非如此。我会看到发布一个快速项目,展示如果您想仔细观察可以克隆的问题。 – 2011-05-24 21:22:26

+0

回调未被阻止。我只是在其中添加了一个警报,并没有回答chrome希望对我的电脑进行地理定位。我在回答chrome之前显示警报消息。 – apneadiving 2011-05-24 21:35:11

+0

不是回答吗? – apneadiving 2011-05-30 05:22:27

相关问题