使用Google Maps Api和外部Json文件

时间:2015-11-20 04:49:19

标签: javascript json ajax google-maps ionic

我试图从外部json文件中提取位置列表,标题为" locations.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],
});

1 个答案:

答案 0 :(得分:1)

您是否尝试使用文件URI方案加载本地文件,例如{Chrome}浏览器中的file:///home/app/csus_locations.txt?由于安全原因(details),默认情况下不允许这样做。

您可以在Google Chrome浏览器中使用旗帜:

--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
                });
            });
        }
    });
}

Plunker

或为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);
        });
    });
}

Plunker