有没有办法将当前位置标记添加到gmaps4rails?

时间:2012-11-24 06:33:29

标签: javascript ruby-on-rails google-maps haml gmaps4rails

我正在尝试弄清楚如何使用map_points向后端添加当前位置标记到gmaps4rails地图以及一些@map_points = @user.places.to_gmaps4rails。我看到了以下帖子:

How do I display the user's location with a marker in gmaps4rails?

并尝试在那里实现javascript,但它似乎没有工作。我将此代码添加到我的javascript部分,但由于某种原因,回调似乎没有触发:

= gmaps("map_options" => {"detect_location" => true, "center_on_user" => true, "auto_zoom" => false, "zoom" => 12, "auto_adjust" => true, "markers" => {"data" => @map_points}})

:javascript
  Gmaps.map.callback = function() {
    Gmaps.map.addMarkers({Lat: Gmaps.map.userLocation.lat(), Lng: Gmaps.map.userLocation.lng(), rich_marker: null, marker_picture:""});
    }

编辑: 这是我现在拥有的,但由于某种原因,addListenerOnce没有解雇:

- content_for :scripts do
  :javascript
    Gmaps.map.callback = function() {
      google.maps.event.addListenerOnce(Gmaps.map.getMapObject(),'idle', function(){
        navigator.geolocation.getCurrentPosition(add_map_marker,displayError);
      });

    };

    function add_map_marker(position){
      var lat = position.coords.latitude;
      var lng = position.coords.longitude;
      Gmaps.map.addMarkers([{
        "lng": lng,
        "lat": lat,
        "picture": "http://googlemaps.googlermania.com/google_maps_api_v3/en/Google_Maps_Marker.png",
        "width": "37",
        "height": "34"
      }]);
    }

    function displayError(error){
      alert('There is an error displaying location');
    }

2 个答案:

答案 0 :(得分:2)

您应该使用addMarkers定义的here

你应该传递一个json数组标记作为参数,由to_gmaps4rails或相同格式产生。


编辑:

:javascript
  Gmaps.map.callback = function() {
    Gmaps.map.addMarkers([
      {"description": "", "title": "", "sidebar": "", "lng": "", "lat": "", "picture": "", "width": "", "height": ""}
    ]);
  }

如果地图尚不存在,请查看here

答案 1 :(得分:1)

您在哪里添加了该代码?因为我认为没有一些重载,例如:

Gmaps.loadMaps();

无论如何都无法解决...我想你必须描述整个路径。 你究竟是如何装载一切的?如果是标准方式,则需要重新加载地图。

我还建议您仔细研究(gmaps4rails source)

Gmaps4rails::JsBuilder.create_js 

方法,如果它是您的默认行为,请尝试使用此自定义注入开发自己的方法进行回调(第34行)。

其他方式是调用一些ajax并使用ujs执行:

  $('#map').html('<%= escape_javascript( gmaps({:last_map => false}) ) %>');
  Gmaps.map = new Gmaps4RailsGoogle();
  Gmaps.load_map = function() {
    Gmaps.map.map_options.maxZoom = 15;
    Gmaps.map.initialize();
    Gmaps.map.markers = <%=raw @json %>;
    Gmaps.map.create_markers();
    Gmaps.map.adjustMapToBounds();
    Gmaps.map.callback();
  };
  Gmaps.loadMaps();
相关问题