如何做一个Ajax GET请求来从轨道获取数据并把它传递给JavaScript(谷歌地图)?(How

2019-06-26 10:39发布

我有两列的模型位置纬度和经度。 我想找到一种方法,在那里我能得到的位置列表,并通过他们向谷歌使用Ajax和JavaScript地图。 到目前为止,我的代码如下:

map.js:

function initialize() 
{   
    var map;
    var latlng = new google.maps.LatLng(37.09, -95.71);
    var options = {
    zoom: 5, 
    center: latlng, 
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    disableDefaultUI: true,
    disableDoubleClickZoom: true,
    noClear: true,
    navigationControl: true,
    navigationControlOptions: {
        position: google.maps.ControlPosition.TOP_RIGHT
    }
    };
   map = new google.maps.Map(document.getElementById('map'), options);

   var marker = new google.maps.Marker({
    position: latlng, 
    map: map, 
    title: 'Click me', 
    });
}

locations_controller.rb

def show
    @location = Location.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @location }
    end
  end

页面显示的地图:

<div id="map" onload="initialize();">
</div>

所以现在我想找到一种方法,使从map.js AJAX请求,所以我可以从选址模型的位置,并把它传递给标记对象,这样,当一个地图加载所有位置数据库中的预先存在的传递给标记,这些标记出现。

谢谢。

Answer 1:

哦,我能找到我的方式来获得位置列表中。 控制器和视图中保持不变。

我在其中所做的工作对我来说map.js增加了以下AJAX。

$.ajax({
        type: "GET",
        dataType: "json",
        url: "/locations",
        success: function(data){}
    }); 

现在,数据可以被传递到在谷歌地图的标记对象。



文章来源: How to do an Ajax GET request to get data from rails and pass it to javascript(google maps)?