如何做一个Ajax GET请求从轨道获取数据并将其传递给JavaScript(谷歌地图)? [英] How to do an Ajax GET request to get data from rails and pass it to javascript(google maps)?
问题描述
我有一个模型位置有两列经纬度。我想找到一种方法可以获取位置列表,并使用Ajax和JavaScript将它们传递给Google地图。到目前为止,我的代码如下:
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',
});
$ / code>
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
$ b 显示地图的页面:
< div id = maponload =initialize();>
< / div>
现在我想找到一种方法从map.js发出一个AJAX请求,这样我就可以获得位置模型中的位置并将其传递给标记对象,以便在加载地图时,数据库中预先存在的所有位置都将传递给标记并显示这些标记。
谢谢。
哦,我能找到自己的方式获取位置列表。控制器和视图保持不变。
我在map.js中添加了以下ajax,它为我完成了工作。
$。ajax({
类型:GET,
dataType:json,
url:/ locations,
success:function(data){}
});
现在可以将数据传递给Google地图中的标记对象。
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:
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
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.
Thank you.
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.
$.ajax({
type: "GET",
dataType: "json",
url: "/locations",
success: function(data){}
});
Now data can be passed to the marker object in google maps.
这篇关于如何做一个Ajax GET请求从轨道获取数据并将其传递给JavaScript(谷歌地图)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!