我有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數據結果。 –