首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用于显示地图模式Rails 5的Link_to标记

用于显示地图模式Rails 5的Link_to标记
EN

Stack Overflow用户
提问于 2017-12-10 10:06:31
回答 4查看 797关注 0票数 4

当我点击地图标记时,会弹出一个模式,如下所示:

我刚刚实现了一个搜索功能,当我点击一个结果时,会弹出一个包含所有信息的模式,就像照片中一样。

下面是我为该页面编写的代码:

MapsController:

代码语言:javascript
运行
复制
class MapsController < ApplicationController
  def index

      @maps = Map.all
      @hash = Gmaps4rails.build_markers(@maps) do |map, marker|
      marker.lat map.latitude
      marker.lng map.longitude
       marker.json({:id => map.id,
            :number => map.number,
            :name => map.name,
            :tabid => map.tabid,
            :zipcode => map.zipcode,
            :latitude => map.latitude,
            :longitude => map.longitude
                  })     

    end
  end

  def favorite 
    @map = Map.new(:number => 'Favorite Site')
    @map.save
    redirect_to :back
    flash[:success] = "favorited"
  end



  def show
   @maps = Map.find(params[:id])

end
end

SearchController:

代码语言:javascript
运行
复制
class SearchController < ApplicationController
  def index
    if params[:query].present?
     @maps = Map.search(params[:query]).with_pg_search_highlight
     @count = @maps.pluck(:id).count


     @hash = Gmaps4rails.build_markers(@maps) do |map, marker|
      marker.lat map.latitude
      marker.lng map.longitude
       marker.json({:id => map.id,
            :number => map.number,
            :name => map.name,
            :tabid => map.tabid,
            :zipcode => map.zipcode,
            :latitude => map.latitude,
            :longitude => map.longitude
                  })         



      # marker.infowindow render_to_string(:partial => "/maps/info", :locals => { :object => map})
       end
    else 
      @maps = Map.all
  end
end
end

下面是我的搜索结果页面代码:

代码语言:javascript
运行
复制
<% provide(:page_title, 'Search Results') %>

<script src="//maps.google.com/maps/api/js?key=AIzaSyAxwNVY12NVNEbrnPorhkHRe7V0_xU8xHM&libraries=places"></script>

<% content_for :scripts %>
<%= javascript_include_tag 'creative/marker_cluster.js', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'creative/infobox_packed.js', 'data-turbolinks-track': 'reload' %>

<div class="main">

<div id="sideBar" class="pre-scrollable">
      <h2><%= @count%> results found </h2>
      <br>
  <% @maps.each do |map| %>
      <div>
        <div class="" id="map_<%= map.id %>">

        <h4>
          <%= link_to map.number, controller: "maps", action: "show", id: map.id %>
        </h4>


        <hr>

        </div>
      </div>
    <% end %>
    <%= link_to 'Return to Main Map', maps_path %>
 </div> 
 <div id="map_wrapper">
    <div id="map" style='width: 100%; height: 100%;'></div>
   </div>

</div>



<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" >
  <div class="modal-dialog">

          <!--Basic Table-->
          <div class="panel panel-green margin-bottom-40">
            <div class="panel-heading">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
              <div class = "name"></div>
            </div>
            <div class="panel-body">

                  <div id="map2" style='width: 568px; height: 365px;'>

                  </div>

                <div class="row">
    <div class="col-sm-12 text-center">



              </div>
              </div>
            </div>
            <table class="table paneltb">


            </table>

          </div>
          <!--End Basic Table-->
  </div>
</div>

 <script type = "text/javascript">
var handler = Gmaps.build('Google', {
         markers:
            {clusterer: {
              gridSize: 60,
              maxZoom: 20,
              styles: [ {
                textSize: 10,
                textColor: '#ff0000',
                url: 'assets/creative/m1.png',
                height: 60,
                width: 60 }
              , {
                textSize: 14, 
                textColor: '#ffff00',
                url:'assets/creative/m2.png',
                height: 60,
                width: 60 }
              , {
               textSize: 18, 
               textColor: '#0000ff',
               url: 'assets/creative/m3.png',
               width: 60,
               height: 60}
              ]}}
      });

var current;
function initialize(){
  handler.buildMap({ internal: {id: 'map'} }, function() {

    markers_json = <%=raw @hash.to_json %>;
    markers = _.map(markers_json, function(marker_json){
      marker = handler.addMarker(marker_json);
      handler.fitMapToBounds();
      _.extend(marker, marker_json);
      return marker;
    });

    getLocation();



    markers.map(function(elem, index) {

      google.maps.event.addListener(elem.getServiceObject(), "click", function(evt) {
        var id = elem.id,
            number = elem.number,
            name = elem.name,
            zipcode = elem.zipcode,
            tabid = elem.tabid,
            latitude = elem.latitude,
            longitude = elem.longitude



         $(".name").html("<h3 class='panel-title'><i class='fa fa-id-card'></i>"+number+"</h3>")
         $(".paneltb").html("<thead><tr><th>Panel</th><th>Location</th><th>Tab ID</th><th>Zip Code</th><th>Latitude</th><th>Longitude</th></tr></thead><tbody><tr><td>"+number+"</td><td>"+ name + "</td><td>"+tabid+"</td><td>"+zipcode+"</td><td>"+latitude+"</td><td>"+longitude+"</td></tr></tbody>")


        pos = new google.maps.LatLng( latitude, longitude );
        var div = document.getElementById('map2');
        var sv = new google.maps.StreetViewPanorama(div);



        sv.setPosition( pos );
        sv.setVisible( true );

        // find the heading by looking from the google car pos to the venue pos
        var service = new google.maps.StreetViewService();
        service.getPanoramaByLocation( pos, 50, function(result, status) {
            if (status == google.maps.StreetViewStatus.OK) 
            {   
                carPos = result.location.latLng;
                heading = google.maps.geometry.spherical.computeHeading( carPos, pos );
                sv.setPov( { heading: heading, pitch: 0, zoom: 0 } );
            }
        })

        $('#myModal').modal('show')

          current = elem;

      $("#myModal").on("shown.bs.modal", function () {
    google.maps.event.trigger(sv, "resize");
});  

        });









    })
  });
    // Create the search box and link it to the UI element.


}
function getLocation(){
  if(navigator.geolocation){
    navigator.geolocation.getCurrentPosition(displayOnMap);
  }
  else{
    navigator.geolocation.getCurrentPosition(displayOnMapError);
  }
};
function displayOnMap(position){

  marker2 = handler.addMarker({
    lat: position.coords.latitude,
    lng: position.coords.longitude,
    picture: {
        url: "<%= asset_path 'creative/1499326997_Untitled-2-01.png' %>",
        width:  48,
        height: 48
        },
    infowindow:  "You are Here!"
  });
  handler.map.centerOn(marker2);
  handler.getMap().setZoom(10);
};

function displayOnMapError(position){

  marker2 = handler.addMarker({
    lat: 34.0522,
    lng: -118.2437,
    picture: {
        url: "<%= asset_path 'creative/1499326997_Untitled-2-01.png' %>",
        width:  48,
        height: 48
        }
  });
  handler.map.centerOn(marker2);
  handler.getMap().setZoom(10);
};




initialize();


</script>

现在,当我点击一个链接时,我会被重定向到一个地图id为nothing的链接(参见地址),例如:

如果有人能指导我,我将不胜感激。

更新1

当我使用给出的建议答案时,我确实得到了一个模式弹出窗口。我们的目标是让模式给我提供相同的信息,就像我点击了地图标记一样(见第一张图)。当我最初点击搜索结果编号时,我得到的结果如下:

然而,当我点击地图标记时,当我点击结果链接时,它的模式就会弹出来,弹出的每个模式都会显示弹出的最后一个地图标记模式的信息,这意味着模式看起来是正确的,因为在第一张图片中,它只是搜索结果中每个链接的模式是相同的。

更新2

我认为我的问题是,这些链接不是地图标记,因此编写的javascript不适用于它们。我怎样才能让链接和地图标记一样,这样信息就会转移到模式上。

更新3

我正在试着像建议的那样把函数拉出来,然后点击调用它,到目前为止,我只有这个,它不工作,或者我。

代码语言:javascript
运行
复制
<%= link_to map.number, "#", data: {toggle: "modal", target: "#myModal"}, :html => {:onclick => 'initialize()' } %>
EN

回答 4

Stack Overflow用户

发布于 2017-12-10 10:28:50

目前您的链接如下所示:

<%= link_to map.number, controller: "maps", action: "show", id: map.id %>

这将创建转到/map/{id} url的基本链接。

要打开带有链接的引导模式,请执行以下操作:

<%= link_to map.number, "#", data: {toggle: "modal", target: "#myModal"} %>

更新:

首先,您的initialize函数已经使用$('#myModal').modal('show')显示了模式,所以您可以从链接中去掉data: {toggle: "modal", target: "#myModal"}

接下来,您的initialize函数需要传入特定的地图标记元素,因此我建议这样做:

<%= link_to map.number, "#", class: "map-marker-link", data: {elem: map} %>

然后在你的javascript中:

代码语言:javascript
运行
复制
$(".map-marker-link").click(function (event) {
    initialize($(this).data('elem'));
    event.preventDefault();
});
票数 2
EN

Stack Overflow用户

发布于 2017-12-26 01:00:29

如果我明白你的问题,那么重点是,你需要在点击链接后显示地图模式,对吗?

如果是,请按照以下步骤操作

更好的做法是在布局文件夹中创建地图文件夹创建部分模型地图文件夹创建部分_show.html.erb

  • Inside地图文件夹创建部分

$modal = $('.modal'),$modalBody = $('.modal .mode-body‘),$modalHeading = $('.modal .mode-$modalBody’);$modalHeading.html("Map");$modalBody.html('<%= escape_javascript(“escape_javascript”) %>');在下面的结果页上呈现模式部分

<%= render partial:"../path/modal“%>

  • 使用remote true创建链接

<%= link_to map.number,map_path(map_parameter1,map_parameter2),remote: true,id: map.id %> #=>将地图参数与指向显示模式的链接一起传递

说明: JS脚本可以使用_show.html.erbshow.js.erb

非常小心地实现这个

希望能帮上忙!

票数 1
EN

Stack Overflow用户

发布于 2017-12-24 08:53:53

我通常使用服务器端Javascript来处理这些问题。试试这个:

  1. 向您的链接添加data-remote="true“:

远程控制器,map.number:"maps",<%=:“link_to”,id: map.id,data:{ remote: true }在您的控制器上添加JS响应

def show @maps = Map.find(params:id) respond_to :js end

  • 创建一个要渲染的新视图文件。应称为'show.js.erb‘,并位于'app/views/maps/’目录中

// Javascript代码。//无论您在此处写什么,都将被执行警告(“您刚刚点击了地图<%= @maps.id %>");

您在视图文件上编写的javascript应该被写出来,以填充模式并显示它。您将能够复制您在原始问题中发布的大部分JS代码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47735172

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档