动态显示谷歌地图上的标记-Rail 3.2 [英] Show markers on google maps dynamically -Rails 3.2

查看:163
本文介绍了动态显示谷歌地图上的标记-Rail 3.2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工作代码,使用 geocoder (例如
@nearbys = Place.near( #{params [:address]},5,:order =>distance,:units =>:km)
@ nearbys.first(5)

,并且我使用下面的代码显示标记

 函数initialize(){
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId:'roadmap'
};

//在地图上显示地图
map = new google.maps.Map(document.getElementById(map-canvas-guest),mapOptions);
map.setTilt(45);

//从ruby对象添加多个标记
var markers = [
['<%= @nearbys [0] .title%>','<% = @nearbys [0] .latitude%>','<%= @nearbys [0] .longitude%>'],
['<%= @nearbys [1] .title%> ;','<%= @nearbys [1] .latitude%>','<%= @nearbys [1] .longitude%>'],
['<%= @nearbys [2] .title%>','<%= @nearbys [2] .latitude%>','<%= @nearbys [2] .longitude%>'],
[ '<%= @nearbys [3] .title%>','<%= @nearbys [3] .latitude%>','<%= @nearbys [3] .longitude%>' ]

['<%= @nearbys [4] .title%>','<%= @nearbys [4] .latitude%>','<%= @nearbys [4] .longitude%>']
];

//添加信息窗口内容
var infoWindowContent = [
['< div class =info_content>'+
'< h3><< ;%= @nearbys [0] .title%>< / h3>'+'< / br>'+
'< p><%= @nearbys [0] .about%> ;< / p>'+
'< / div>'],
['< div class =info_content>'+
'< h3>< %= @nearbys [1] .title%>< / h3>'+
'< p><%= @nearbys [1] .about%>< / p>'+
'< / div>'],
['< div class =info_content>'+
'< h3><%= @nearbys [2] .title %>< / h3>'+'< / br>'+
'< p><%= @nearbys [2] .about%>< / p>'+
'< / div>'],
['< div class =info_content>'+
'< h3><%= @nearbys [3] >< / h3>'+'< / br>'+
'< p><%= @nearbys [2] .about%> / p>'+
'< / div>'],
['< div class =info_content >'+
'< h3><%= @nearbys [4] .title%>< / h3>'+'< / br>'+
'< p><%= @nearbys [4] .about%>< / p>'+
'< / div>']
];

//在地图上显示多个标记
var infoWindow = new google.maps.InfoWindow(),marker,i;

//通过我们的数组标记和(i = 0; i< markers.length; i ++){
var position = new google.maps.LatLng(markers [i] [1],markers [ I] [2]);
bounds.extend(position);
marker = new google.maps.Marker({
position:position,
map:map,
title:markers [i] [0]
});

//允许每个标记有一个信息窗口
google.maps.event.addListener(marker,'click',(function(marker,i){
return function (){
infoWindow.setContent(infoWindowContent [i] [0]);
infoWindow.open(map,marker);


}
})(marker,i));

//自动使地图适合屏幕上的所有标记
map.fitBounds(bounds);

}

//一旦我们的fitBounds函数运行,请覆盖我们的地图缩放级别(确保它只运行一次)
var boundsListener = google.maps.event。 addListener((map),'bounds_changed',function(event){
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});

} //初始化结束

但问题是: - 如果@nearbys的计数小于5,那么这段代码失败了。我一直试图使用jquery数组来动态化它,但它不工作,因为我认为我的代码缺少动态工作的代码。
它应该是这样的。

  var array =<%= @ nearbys%>; 
var markers = [];
var infowindows = [];
array.each(function(index){
markers.push('<%= @nearbys [0] .title%>','<%= @nearbys [0] .latitude %>','<%= @nearbys [0] .longitude%>');
infowindows.push('< div class =info_content>'+'< h3>< ;%= @nearbys [0] .title%>< / h3>'+'< / br>'+
'< p><%= @nearbys [0] .about%> ;< / p>'+'< / div>');

})

..所以我怎么做到这一点........使这种动态,使上面的工作代码不会违反新添加的代码。

解决方案

在与 jquery数组和 json ,i能够找到这个最好的解决方案......这是在所有情况下工作,我需要的是处理空的和空的条件,我已经做了,它的工作方式我需要。希望这有助于某人



我的管理员
$ b

  def显示_nearby_locations 

@nearbys = Place.near(#{params [:address]},5,:order => 距离,:单位=> :km)
@ nearbys.first(10)

end

在我的视图文件中

 <%= javascript_tag %GT; 
window.nearbys =<%= raw @ nearbys.to_json%>;

<%end%>

这是我查看的脚本

 函数初始化(){
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId:'roadmap'
};

//在地图上显示地图
map = new google.maps.Map(document.getElementById(map-canvas-guest),mapOptions);
map.setTilt(45);

var markers = [];
var infoWindowContent = [];
$ .each(nearbys,function(index){

console.log(data [0] [index] .latitude,data [0] [index] .longitude);
markers.push([nearbys [index] ['title'],nearbys [index] ['latitude'],nearbys [index] ['longitude']]);
infoWindowContent.push(['< ; div class =info_content>'+
'< h3 style =color:rgb(<%= rand(0..200)%>,<%= rand(0 .. 200)%>,<%= rand(0..200)%>);>'+ nearbys [index] ['title'] +'< / h3>'+'< / br> ;'+
'< p>'+ nearbys [index] ['about'] +'< / p>'+
'< / div>]];

});

//在地图上显示多个标记
var infoWindow = new google.maps.InfoWindow(),marker,i;
//循环遍历我们的标记阵列& (i = 0; i< markers.length; i ++){
var position = new google.maps.LatLng(markers [i] [1],markers [ I] [2]);
bounds.extend(position);
marker = new google.maps.Marker({
position:position,
map:map,
title:markers [i] [0]
});

//允许每个标记有一个信息窗口
google.maps.event.addListener(marker,'click',(function(marker,i){
return function (){
infoWindow.setContent(infoWindowContent [i] [0]);
infoWindow.open(map,marker);


}
})(marker,i));

//自动使地图适合屏幕上的所有标记
map.fitBounds(bounds);

}

//一旦我们的fitBounds函数运行,请覆盖我们的地图缩放级别(确保它只运行一次)
var boundsListener = google.maps.event。 addListener((map),'bounds_changed',function(event){
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});

} //初始化结束


i have a working code that shows multiple markers on google map using geocoder such as @nearbys = Place.near("#{params[:address]}", 5,:order => "distance",:units => :km) @nearbys.first(5) and i display the markers using the below code

function initialize() {
    var map;
    var bounds = new google.maps.LatLngBounds();
    var mapOptions = {
        mapTypeId: 'roadmap'
    };

    // Display a map on the page
    map = new google.maps.Map(document.getElementById("map-canvas-guest"), mapOptions);
    map.setTilt(45);

    // adding Multiple Markers from ruby object
    var markers = [
        ['<%= @nearbys[0].title %>', '<%= @nearbys[0].latitude %>','<%= @nearbys[0].longitude %>'],
        ['<%= @nearbys[1].title %>', '<%= @nearbys[1].latitude %>','<%= @nearbys[1].longitude %>'],
        ['<%= @nearbys[2].title %>', '<%= @nearbys[2].latitude %>','<%= @nearbys[2].longitude %>'],
        ['<%= @nearbys[3].title %>', '<%= @nearbys[3].latitude %>','<%= @nearbys[3].longitude %>']
        ,
        ['<%= @nearbys[4].title %>', '<%= @nearbys[4].latitude %>','<%= @nearbys[4].longitude %>']
      ];

    // adding Info Window Content 
    var infoWindowContent = [
        ['<div class="info_content" >' +
        '<h3><%= @nearbys[0].title %></h3>' +'</br>'+
        '<p><%= @nearbys[0].about %></p>' +       
         '</div>'],
        ['<div class="info_content">' +
        '<h3><%= @nearbys[1].title %></h3>' +
        '<p><%= @nearbys[1].about %></p>' +
        '</div>'],
                ['<div class="info_content">' +
        '<h3><%= @nearbys[2].title %></h3>' +'</br>'+
        '<p><%= @nearbys[2].about %></p>' +
        '</div>'],
                ['<div class="info_content">' +
        '<h3><%= @nearbys[3].title %></h3>' +'</br>'+
        '<p><%= @nearbys[2].about %>/p>' +
        '</div>'],
                ['<div class="info_content">' +
        '<h3><%= @nearbys[4].title %></h3>' +'</br>'+
        '<p><%= @nearbys[4].about %></p>' +
        '</div>']
    ];

    // Display multiple markers on a map
    var infoWindow = new google.maps.InfoWindow(), marker, i;

    // Loop through our array of markers & place each one on the map  
    for( i = 0; i < markers.length; i++ ) {
        var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
        bounds.extend(position);
        marker = new google.maps.Marker({
            position: position,
            map: map,
            title: markers[i][0]
        });

        // Allow each marker to have an info window    
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infoWindow.setContent(infoWindowContent[i][0]);
                infoWindow.open(map, marker);


            }
        })(marker, i));

        // Automatically center the map fitting all markers on the screen
        map.fitBounds(bounds);

    }

    // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
    var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
        this.setZoom(14);
        google.maps.event.removeListener(boundsListener);
    });

}//initialize ends

BUT the problem is:-what if @nearbys has less than 5 count,then this code fails.SO i have been trying to make it dynamic using jquery arrays but its not working because i think my code is missing something to work it dynamically. it should be something like this..

var array=<%= @nearbys%>;
var markers=[];
var infowindows=[];
array.each(function(index){
markers.push('<%= @nearbys[0].title %>', '<%= @nearbys[0].latitude %>','<%= @nearbys[0].longitude %>');
infowindows.push('<div class="info_content" >'+'<h3><%= @nearbys[0].title %></h3>' +'</br>'+
        '<p><%= @nearbys[0].about %></p>'+'</div>');

})

..SO how i can achieve this........to make this dynamic so that above working code doesnt breaks with the newly added code.

解决方案

well after struggling with jquery arrays and json ,i was able to find this best solution...this is working in all scenarios and all i need is to handle empty and null conditions,which i already did and its working the way i needed.HOPE THIS HELPS SOMEONE

my controller

def show_nearby_locations

  @nearbys = Place.near("#{params[:address]}", 5,:order => "distance",:units => :km)
  @nearbys.first(10)

end

in my view file

<%= javascript_tag do%>
 window.nearbys= <%=raw @nearbys.to_json %>;

<%end%>

this is my script inside view

function initialize() {
    var map;
    var bounds = new google.maps.LatLngBounds();
    var mapOptions = {
        mapTypeId: 'roadmap'
    };

    // Display a map on the page
    map = new google.maps.Map(document.getElementById("map-canvas-guest"), mapOptions);
    map.setTilt(45);            

    var markers=[];
    var infoWindowContent=[];
    $.each(nearbys, function(index) { 

        console.log( data[0][index].latitude,data[0][index].longitude );
        markers.push([nearbys[index]['title'], nearbys[index]['latitude'],nearbys[index]['longitude']]);
        infoWindowContent.push(['<div class="info_content" >' +
        '<h3 style="color: rgb(<%= rand(0..200)%>,<%= rand(0..200)%> ,<%= rand(0..200)%>);">'+nearbys[index]['title']+'</h3>' +'</br>'+
        '<p>'+nearbys[index]['about']+'</p>' +       
         '</div>']);

        });   

       // Display multiple markers on a map
       var infoWindow = new google.maps.InfoWindow(), marker, i;        
      // Loop through our array of markers & place each one on the map  
      for( i = 0; i < markers.length; i++ ) {
          var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
          bounds.extend(position);
          marker = new google.maps.Marker({
            position: position,
            map: map,
            title: markers[i][0]
        });

        // Allow each marker to have an info window    
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infoWindow.setContent(infoWindowContent[i][0]);
                infoWindow.open(map, marker);


            }
        })(marker, i));

        // Automatically center the map fitting all markers on the screen
        map.fitBounds(bounds);

    }

    // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
    var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
        this.setZoom(14);
        google.maps.event.removeListener(boundsListener);
    });

}//initialize ends

这篇关于动态显示谷歌地图上的标记-Rail 3.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆