我有index.php和ajax.php。当页面加载ajax函数从ajax.php返回json数据时。 Ajax.php正在工作。我可以得到json数据。地图加载首先比ajax函数,所以我得到的变量json没有定义的错误。我直接使用json数据结果。例如var json = [{{“id”:48,“title”:“a”,“lng”:“28.6643180847168”,“lat”:“41.0327529907227”}]我的代码正在工作。首先地图正在加载,所以它会给出错误。我应该使用不同的方法?我希望我能够解释得很清楚。打印json结果到谷歌地图
这是我的JSON数据导致:
[{ “ID”:48, “标题”: “一”, “LNG”: “28.6643180847168”, “LAT”: “41.0327529907227”}, {“id”:46,“title”:“b”,“lng”:“28.6722145080566”,“lat”:“41.0330085754395”},{“id”:44,“title”:“c” :“28.6628570556641”,“lat”:“41.032169342041”},{“id”:43,“title”:“d”,“lng”:“28.6649876832962”,“lat”:“41.0323740058176”}]
这是index.php文件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<style>
html, body, #map-canvas {height: 100%;margin: 0;padding: 0;}
</style>
</head>
<body>
<div id="one"></div>
<div id="map-canvas"></div>
<script>
$(window).load(function() {
$.ajax({
dataType: "json",
url: 'ajax.php',
success:function(data){
var result = JSON.stringify(data);
$("#one").html(result);
}
});
});
var map;
var json=$("#one").text();
function initialize() {
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(json[0]['lat'],json[0]['lng'])
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Looping through all the entries from the JSON data
for(var i = 0; i < json.length; i++) {
var obj = json[i];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(obj.lat,obj.lng),
map: map
});
var clicker = addClicker(marker, obj.title);
}
function addClicker(marker, content) {
google.maps.event.addListener(marker, 'click', function() {
if (infowindow) {infowindow.close();}
infowindow = new google.maps.InfoWindow({content: content});
infowindow.open(map, marker);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html>
你说得对,我按照你的说法试过了。但标记不会在地图上创建。例如,我写了一个例子json = [{“id”:48,“title”:“a”,“lng”:“28.6643180847168”,“lat”:“41.0327529907227”}, {“id”:46,标题“:”b“,”lng“:”28.6722145080566“,”lat“:”41.0330085754395“}, {”id“:44,”title“:”c“,”lng“:”28.6628570556641“ “:”41.032169342041“}, {”id“:43,”title“:”d“,”lng“:”28.6649876832962“,”lat“:”41.0323740058176“}]数据标记被创建。否则标记不创建。 –
你是否从php中检查obj.lat && obj.lng的内容?如果你提醒()内容,是吗? –
我只想学习如何将json数据结果用于Google地图。我的代码现在不能工作。当页面加载在地图和Ajax加载,所以我不能在地图上使用json数据结果。 –