[英]Trying to parse external json file to create markers in google maps api
[英]Using Google Maps Api and external Json file
我正在嘗試從名為“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],
});
您是否嘗試在 Google Chrome 瀏覽器中使用文件 URI 方案加載本地文件,例如file:///home/app/csus_locations.txt
? 由於安全原因(詳細信息),默認情況下不允許這樣做。
您可以在 Google Chrome 瀏覽器中使用 flag:
--allow-file-access-from-files
允許加載本地文件。
如果不是這種情況,那么既然是 JSON 文件類型,請嘗試明確指定dataType: "json"
,例如:
function loadMarkers(map)
{
$.ajax({
url: "csus_locations.txt",
cache: false,
dataType: "json",
success: function( data, textStatus, jqXHR ) {
$.each(data, function(key, item) {
var latLng = new google.maps.LatLng(item.latitude, item.longitude);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: item.name
});
});
}
});
}
或者為jQuery.getJSON()指定format: "json"
,例如:
function loadMarkers(map)
{
$.getJSON("csus_locations.txt",
{
format: "json"
})
.done(function(json) {
$.each(json, 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
});
console.log(data);
});
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.