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