【问题标题】:Reading in XML or JSON from file on local server从本地服务器上的文件中读取 XML 或 JSON
【发布时间】:2015-10-18 08:27:11
【问题描述】:

我正在尝试从 XML 文件或 JSON 文件(我都托管在本地测试服务器上的同一目录中)加载用于谷歌地图的坐标列表。到目前为止,我已经使用硬编码的 JSON 对象来加载地图坐标以进行测试。我的问题是,如何用我服务器上的 XML/JSON 文件替换那个假的/硬编码的 JSON?这是我的代码:

  (function() {

  // Creating an array that will contain all of our product icons
  var productIcons = [];

  productIcons['bulletin'] = new google.maps.MarkerImage(
    'icons/Bulletin-sm.png', 
    new google.maps.Size(48, 48), 
    null, 
    new google.maps.Point(24, 24)
  );

  productIcons['bus'] = new google.maps.MarkerImage(
    'icons/busicon.png', 
    new google.maps.Size(48, 48), 
    null, 
    new google.maps.Point(24, 24)
  );

  productIcons['bench'] = new google.maps.MarkerImage(
    'icons/BusBench-sm.png', 
    new google.maps.Size(48, 48), 
    null, 
    new google.maps.Point(24, 24)
  );

  productIcons['junior'] = new google.maps.MarkerImage(
    'icons/JuniorPoster-sm.png', 
    new google.maps.Size(48, 48), 
    null, 
    new google.maps.Point(24, 24)
  );

  productIcons['poster'] = new google.maps.MarkerImage(
    'icons/Poster-sm.png', 
    new google.maps.Size(48, 48), 
    null, 
    new google.maps.Point(24, 24)
  );


  productIcons['shelter'] = new google.maps.MarkerImage(
    'icons/TransitShelter-sm.png', 
    new google.maps.Size(48, 48), 
    null, 
    new google.maps.Point(24, 24)
  );

  window.onload = function() {

    // Creating a map
    var options = {  
      zoom: 3,  
      center: new google.maps.LatLng(37.09, -95.71),  
      mapTypeId: google.maps.MapTypeId.ROADMAP  
    };  
    var map = new google.maps.Map(document.getElementById('map'), options);  


// Creating a JSON object with fake product data (to be replaced by XML or JSON)
var productData = {'product': [
{
'lat': 40.756054,
'lng': -119.986951,
'productType': 'junior'
},
{
'lat': 35.620973,
'lng': -121.347276,
'productType': 'shelter'
},
{
'lat': 40.620973,
'lng': -121.347276,
'productType': 'bus'
},
{
'lat': 39.120973,
'lng': -122.847276,
'productType': 'bench'
},
{
'lat': 35.920973,
'lng': -122.347276,
'productType': 'bulletin'
},
{
'lat': 37.775206,
'lng': -122.419209,
'productType': 'poster'
}
]};
// Looping through the product array in productData
for (var i = 0; i < productData.product.length; i++) {
// creating a variable that will hold the current product object
var product = productData.product[i];
// Creating marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(product.lat, product.lng),
map: map,
icon: productIcons[product.productType]
});

}
}
})();

【问题讨论】:

  • 您必须使用服务器端代码加载 JSON 文件,因为浏览器无权访问您的服务器端文件。您可能会将 JSON 注入您的页面以供 Javascript 使用。

标签: javascript json xml google-maps-api-3


【解决方案1】:

我认为您可以在服务器上设置一个 RESTFUL Web 服务,然后使用 jquery 的 ajax 功能从中获取 JSON 内容。

ajax 教程: Ajax tutorial for post and get

至于 RESTFUL web 服务端,有很多技术可以探索。只需搜索“java restful web service tutorial”或“.NET WCF RESTFUL”

【讨论】:

  • 太好了,感谢您的帮助-这正是我所需要的。
最近更新 更多