如何执行 Ajax GET 请求以从 Rails 获取数据并将其传递给 javascript(谷歌地图)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11589508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:45:56  来源:igfitidea点击:

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

javascriptruby-on-railsajaxgoogle-maps-api-3ruby-on-rails-3.2

提问by Maddy

I have a model Locations with two columns latitude and longitude. I want to find a way where I can get the list of locations and pass them to google maps using Ajax and javascript. So far my code is as follows:

我有一个带有两列纬度和经度的模型位置。我想找到一种方法来获取位置列表并使用 Ajax 和 javascript 将它们传递给谷歌地图。到目前为止,我的代码如下:

map.js:

地图.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

location_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

Page displaying the map:

显示地图的页面:

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

SO now I want to find a way to make an AJAX request from map.js so I can get the locations from the Location model and pass it to the marker object so that when a map is loading all the locations pre-existing in the database are passed to marker and those markers appear.

所以现在我想找到一种从 map.js 发出 AJAX 请求的方法,这样我就可以从 Location 模型中获取位置并将其传递给标记对象,以便在地图加载数据库中预先存在的所有位置时传递给标记并出现这些标记。

Thank you.

谢谢你。

回答by Maddy

Oh I was able to find my way to get the list of locations. The controller and view are left untouched.

哦,我找到了获取位置列表的方法。控制器和视图保持不变。

I added the following ajax in map.js which did the work for me.

我在 map.js 中添加了以下 ajax,它为我完成了工作。

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

Now data can be passed to the marker object in google maps.

现在可以将数据传递给谷歌地图中的标记对象。