【发布时间】:2014-08-23 07:47:56
【问题描述】:
我正在从 mysql 数据库中获取数据,并通过通过 $.get 访问的 laravel/php 将其 JSON 化,使用 jquery,它返回如下:
[{"id":45,"name":"Aberdeen","latitude":"-2.09410800","longitude":"57.15502200"},
{"id":46,"name":"Bangor","latitude":"-4.18029020","longitude":"53.20660020"},
{"id":47,"name":"Bath","latitude":"-2.36205010","longitude":"51.38600160"}]
//list goes on
然后我想在我的地图上添加标记,当我在 js 文件中手动定义上述数组并且未使用 $.get 时,单击侦听器起作用。使用$.get,我的代码如下所示:
$(document).ready(function () {
function initialize(clubs) {
var mapOptions = {
center: new google.maps.LatLng(54.206845, -2.422000),
zoom: 6
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var infowindow = new google.maps.InfoWindow(),
marker, i;
for (i = 0; i < clubs.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(clubs[i]['latitude'], clubs[i]['longitude']),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(clubs[i]['name']);
infowindow.open(map, marker);
console.log('clicked on marker');
$('#club-info').html('club: ' + clubs[i]['name']);
}
})(marker, i));
} // end for
} // end function initialize
$.get(
'api/clubdata',
function (data) {
google.maps.event.addDomListener(window, 'load', initialize(data));
});
});
HTML 是这样的(使用 bootstrap 作为样式):
<div class="row">
<div class="col-md-6" id="map-canvas"></div>
<div class="col-md-6" id="club-info"></div>
</div>
我似乎无法弄清楚为什么标记不显示,非常感谢任何帮助!
编辑: 我只是补充一点,数据很好,我已经通过 console.log 进行了检查。我觉得这是我编程方式的问题。
【问题讨论】:
-
如果您在
for循环中记录clubs[i]['latitude']会怎样? -
另外
marker = ...应该是var marker = ... -
当我粘贴它时,我实际上从代码中的 for 循环开头删除了该行 - 哈哈。是的,它显示了所有 lats 的列表
-
我建议你试试。
-
好吧,我想通了,我搞砸了 - 很抱歉我浪费了你的时间
标签: javascript jquery ajax google-maps-api-3