【发布时间】:2016-02-22 11:58:27
【问题描述】:
我正在尝试从名为“locations.json”的外部 json 文件中提取位置列表,并为每个项目创建单独的标记。实际使用 ajax 解析文件时遇到问题。
[
{
"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 方法和 for 循环:
$.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],
});
【问题讨论】:
-
两种解决方案似乎都是在循环中定义一个标记变量,然后在循环的每次迭代中用新信息覆盖该标记变量。您在地图上只看到一个标记吗?我建议对此进行审查,这似乎与您想要做的完全一样。 en.marnoto.com/2013/12/…
标签: javascript json ajax google-maps ionic