2015-11-20 99 views
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], 
}); 
+0

这两种解决方案似乎都是在一个循环内定义一个标记变量,然后在循环的每次迭代中用新信息覆盖该标记变量。你只在地图上看到一个标记吗?我会建议审查这个,看起来就像你想要做的。 http://en.marnoto.com/2013/12/mapa-com-varios-marcadores-google-maps.html – user2263572

回答

0

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

你可以在谷歌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