我差不多了,但它不太合适。我正在尝试通过ajax加载内容,它确实加载了正确的内容,我可以看到它在firebug中加载但是,它给了我一个错误:infowindow没有定义。我load_content
在load_content工作之前,两个注释掉的行用一些文本加载一个小窗口。
function initialize() {
var myLatlng = new google.maps.LatLng(<%= @location_for_map.average(:lat) %>, <%= @location_for_map.average(:lng) %>);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeControl: false,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//var infowindow = new google.maps.InfoWindow();
setMarkers(map, places);
}
function setMarkers(map, locations) {
// Add markers to the map
for (var i = 0; i < locations.length; i++) {
var place = locations[i];
var myLatLng = new google.maps.LatLng(place.lat, place.lng);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: '/images/google_maps/numbers/'+(i+1)+'.png',
html: place.name,
id: place.id,
title: place.name
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function() {
//infowindow.setContent(this.html);
//infowindow.open(map,this);
load_content(marker, this.id);
});
}
}
function load_content(marker, id){
$.ajax({
url: '/places/' + id + '.js',
success: function(data){
infowindow.setContent(data);
infowindow.open(map, marker);
}
});
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
答案 0 :(得分:3)
这有效:
function setMarkers(map, locations) {
// Add markers to the map
for (var i = 0; i < locations.length; i++) {
var place = locations[i];
var myLatLng = new google.maps.LatLng(place.lat, place.lng);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: '/images/google_maps/numbers/'+(i+1)+'.png',
html: place.name,
id: place.id,
title: place.name
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function() {
load_content(map,this,infowindow);
});
}
}
function load_content(map,marker,infowindow){
$.ajax({
url: '/places/' + marker.id + '.js',
success: function(data){
infowindow.setContent(data);
infowindow.open(map, marker);
}
});
}
答案 1 :(得分:0)
您的infowindow声明仅在函数内部具有范围。尝试使用全局范围声明infowindow变量。我相信这就是造成'infowindow not defined'问题的原因。
答案 2 :(得分:0)
移动此行:
var infowindow = new google.maps.InfoWindow();
在任何函数之外,例如在函数initialize(){}
之后