正如您在下面的代码中看到的那样,我从MySQL数据库中获取数据,但是当我想使用获取的“位置”来设置谷歌地图上标记的“位置”时,我就陷入了困境。
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxxxxxxxxx&sensor=true"></script>
<script>
$.getJSON('http://www.wawhost.com/appProject/fetchmarker.php?callback=?', function(data) {
for (var i = 0; i < data.length; i++) {
localStorage.loc = data[i].location;
}
});
</script>
<script>
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882, 131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker({
position: 'new google.maps.LatLng(' + localStorage.loc + ')',
map: map,
title: 'Hello World!'
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
谢谢!
答案 0 :(得分:1)
在页面加载后发出请求,并从AJAX成功回调中调用initialize
函数。
$(function() {
$.getJSON('http://www.wawhost.com/appProject/fetchmarker.php?callback=?', function(data) {
for (var i = 0; i < data.length; i++) {
localStorage.loc = data[i].location;
}
initialize();
});
});
此外,这条线看起来有点粗略。 position
应该是新的google.maps.LatLng
。
position: 'new google.maps.LatLng(' + localStorage.loc + ')'.
LatLng
使用纬度和经度参数来构造对象。您从请求中存储的是字符串,其中包含逗号分隔的lat和long值。
// First split the string into lat and long.
var pos = localStorage.loc.split(",");
// Parse the strings into floats.
var lat = parseFloat(pos[0]);
var lng = parseFloat(pos[1]);
// Create a new marker with the values from the request.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
title: 'Hello World!'
});
试试here.