0
我試圖從外部json文件中提取名爲「locations.json」的位置列表併爲每個項目創建單獨的標記。使用ajax實際解析文件時遇到問題。使用谷歌地圖Api和外部Json文件
[
{
"latitude": 38.558961,
"longitude": -121.423011,
"name": "Library",
"title": "THIS IS WHERE STUFF GETS DONE!"
},
{
"latitude": 38.562605,
"longitude": -121.419683,
"name": "Bridge",
"title": "Water below"
},
{
"latitude": 38.556652,
"longitude": -121.423842,
"name": "GYM",
"title": "WORKOUT"
},
{
"latitude": 38.555465,
"longitude": -121.422551,
"name": "Stadium",
"title": "FOOTBALL!"
}
]
這是JavaScript文件中的代碼。
$.getJSON("csus_locations.txt", function(json1) { $.each(json1, function(key, data) {
var latLng = new google.maps.LatLng(data.latitude, data.longitude);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.name
});
});
});
另一種解決方案是嘗試以下,使用AJAX方法和用於循環:
$.ajax({
url: "/locations",
type: 'POST',
//force to handle it as text
dataType: "json",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
}
});
});
for (var i = 0; i < csus_locations.length; i++) {
var tourStop = locations[i];
var myLatLng = new google.maps.LatLng(tourStop[0], tourStop[1]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
shadow: shadow,
icon: image,
shape: shape,
name: tourStop[2],
});
這兩種解決方案似乎都是在一個循環內定義一個標記變量,然後在循環的每次迭代中用新信息覆蓋該標記變量。你只在地圖上看到一個標記嗎?我會建議審查這個,看起來就像你想要做的。 http://en.marnoto.com/2013/12/mapa-com-varios-marcadores-google-maps.html – user2263572