我想在 Google map 中显示一些坐标,从文本文件中获取它可以很好地工作,但我不知道如何从数据库访问坐标。
这里是处理文本文件的代码:
<script type="text/javascript">
var map;
var markers = [];
var mon_fichier = fichier_txt("file.txt");
var elem = mon_fichier.split(',');
var tHandleMajActors; // Handle timer majActeurs()
function initialize() {
var haightAshbury = new google.maps.LatLng(elem[0], elem[1]);
var mapOptions = {
zoom: 6,
center: haightAshbury,
mapTypeId: google.maps.MapTypeId.TERRAIN
/*mapTypeId: google.maps.MapTypeId.SATELLITE*/
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
//run realtime view
RTrun();
}
//RT MENU MANAGEMENT
function RTrun(){
movePositionMarker();
}
//RT MARKER MANAGEMENT
function movePositionMarker(){ //XXX timer
var mon_fichier = fichier_txt("file.txt");
var elem = mon_fichier.split(',');
i=0;
while (i<elem.length) {
var myPosition = new google.maps.LatLng(elem[i], elem[i+1]);
i=i+2;
addMarker(myPosition);
}
//timer: every 10 s
tHandleMajActors = setTimeout( function(){
movePositionMarker();
}, 10000);
}
// Add a marker to the map and push to the array.
function addMarker(location) {
var image = 'images/flag.png';
var marker = new google.maps.Marker({
//animation: google.maps.Animation.DROP,
position: location,
map: map,
icon: image
});
markers.push(marker);
}
我想要从中获取坐标的表称为“坐标”,并具有:纬度、:经度、:日期、:时间、:tracker_id
感谢您的帮助!
最佳答案
您无法使用 JavaScript 直接访问数据库,因为它位于与浏览器不同的计算机(服务器)上。您需要在应用程序上调用一个操作,该操作将返回您想要的数据。
在本例中,您希望获取 json 格式的数据,以便 javascript 可以将其直接转换为实际的 javascript 对象。
您可以决定哪个操作应返回数据。在这种情况下,如果它是单个坐标对象的数据,那么使用 CoordinationsController#show 操作就有意义了。应该像这样设置:
def show
@coordinate = Coordinate.find(params[:id])
respond_to do |format|
format.html #defaults to rendering the /view/coordinates/show template
format.json { render json: @coordinate }
end
end
所以,这就是 rails 末端排序。
接下来是从 JavaScript 中调用上述操作。我将使用 jquery 来完成它,因为它更容易。
$.ajax({
url: "/coordinates/"+coordinate_id,
dataType: "json",
success: function(data){
//data is the data you got from the server, do something with it
}
});
在此示例中,您需要知道坐标对象的 id 才能传递它。
关于javascript - 如何在 Rails 应用程序中使用 javascript 调用数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24141894/