我正在尝试将addListeners分配给有多个标记且不起作用的单个标记。发生的事情是,即使我没有点击,所有窗口都会立即打开。当我点击时,没有任何反应。有什么问题?
这是我的代码:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDUE08r9kD1p5QsqOzmI6_EcoUNCJntf5I&sensor=false"></script>
<script type="text/javascript">
//start the map. code from google maps tutorial.
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(37.7750, -122.4183),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//return a map for later use
return new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
function request() {
$.ajax ({
type: "GET",
dataType: "json",
url: "stations.php",
data: {
route: $("#route").val()
},
success: function(data) {
var routePathCoords = [];
var pathColor = data.color;
$.each(data.stations, function(i,j) {
routePathCoords.push(new google.maps.LatLng(data.lat[i], data.longit[i]));
});
//create new map
var map = initialize();
//generating the polyline
var routePath = new google.maps.Polyline({
path: routePathCoords,
strokeColor: pathColor,
strokeOpacity: 1.0,
strokeWeight: 5
});
routePath.setMap(map);
//creating each marker, display on screen
$.each(routePathCoords, function(i,c) {
var marker = new google.maps.Marker({
//obtaining from coordinates array
position: c,
map: map,
//obtaining from stations array
title: data.stations[i]
});
var name = marker.title;
//listen for click, then activate window
google.maps.event.addListener(marker, 'click', stnWindow(name, marker, map));
});
},
error:function (xhr, ajaxOptions, thrownError){
console.log(ajaxOptions);
alert(xhr.status);
alert(thrownError);
}
});
return false;
}
function stnWindow(name, marker, map) {
$.ajax({
type: "GET",
dataType: "json",
url: "window.php",
data: {
name: name
},
success: function(data) {
//initializing variables for window+content
var station = data.fullname;
var infoWindow = new google.maps.InfoWindow;
//adding station title
var content = "<h1>" + station + "</h1>";
//get names and times, put into var content
$.each(data.destns, function(i,n) {
content = content + "<h2> Destination: </h2>" + n;
content = content + "<h3> Arrival: </h3>" + data.arrivals[i] + "minutes" ;
});
infoWindow.setContent(content);
infoWindow.open(map, marker);
}
})
}
</script>
<script type="text/javascript">
</script>
答案 0 :(得分:1)
您正在执行stnWindow
功能而不是分配它。
你可以通过返回一个只包含ajax调用的函数来解决它,如下所示:
function stnWindow (name, marker, map) {
return function () {
$.ajax() //...
}
}
在触发点击之前,不会触发返回的功能。
答案 1 :(得分:0)
Try to replace :
google.maps.event.addListener(marker, 'click', stnWindow(name, marker, map));
by :
google.maps.event.addListener(marker, 'click', function(){
$.ajax({
type: "GET",
dataType: "json",
url: "window.php",
data: {
name: name
},
success: function(data) {
//initializing variables for window+content
var station = data.fullname;
....
infoWindow.open(map, marker);
}
})
});