我从mysql数据库获取数据并通过laravel / php通过$.get
访问jSONifying,使用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进行了检查。我觉得这是我编程的方式的问题。
答案 0 :(得分:0)
有一个愚蠢的时刻 - 经度和纬度混淆了。应该是这样写的:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(clubs[i]['longitude'], clubs[i]['latitude']),
map: map
});
答案 1 :(得分:0)
您不能使用指向addDomListener调用的函数指针传递参数:
google.maps.event.addDomListener(window, 'load', initialize(data));
请改为:
google.maps.event.addDomListener(window, 'load', function() {initialize(data)});
但是......你真的应该在回调$ .get调用时(当数据可用时)这样做。
$.get(
'api/clubdata',
function(data){
initialize(data);
}
);
您的经度和纬度属性在您的JSON中也有错误名称。应该是:
var data = [{
"id": 45,
"name": "Aberdeen",
"longitude": "-2.09410800",
"latitude": "57.15502200"
}, {
"id": 46,
"name": "Bangor",
"longitude": "-4.18029020",
"latitude": "53.20660020"
}, {
"id": 47,
"name": "Bath",
"longitude": "-2.36205010",
"latitude": "51.38600160"
}];