从外部源调用json文件

时间:2016-10-15 20:06:56

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

我使用此JavaScript从外部源调用我的JSON数据。 json数据将从服务器加载。那么,我可以使用外部JSON数据从谷歌地图获取标记的脚本。

 var map, infowindow; ////

// The JSON data
var json = "http://www.tripleclickstudio.com/json/file.json"
$.getJSON(json,{
    tags:"location",
    tagmode:"any",
    format:"json"
    
})

function initialize() {
  
  // Giving the map som options
  var mapOptions = {
    ////
  };
  
  // Creating the map
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  
  var bounds = new google.maps.LatLngBounds(); ////
  
  // Looping through all the entries from the JSON data
  var responses = json[0].ResponseData; ////
  for(var i = 0; i < responses.length; i++) { ////
    
    // Current object
    var obj = responses[i]; ////

    // Adding a new marker for the object
    var position =
      new google.maps.LatLng( obj.CoordinateY, obj.CoordinateX ); ////
    bounds.extend( position ); ////
    var marker = new google.maps.Marker({
      position: position, ////
      map: map,
      draggable: true,
      animation: google.maps.Animation.DROP,
      title: obj.BuildingName
    });
    
    // Adding a new info window for the object
    var clicker = addClicker(marker, obj.BuildingName); ////

  } // end loop
  
  map.fitBounds( bounds ); ////
  
  // Adding a new click event listener for the object
  function addClicker(marker, content) {
    google.maps.event.addListener(marker, 'click', function() {
      
      if (infowindow) {infowindow.close();}
      infowindow = new google.maps.InfoWindow({content: content});
      infowindow.open(map, marker);
      
    });
  }
  
}

// Initialize the map
google.maps.event.addDomListener(window, 'load', initialize);
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
   <script src="https:////cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <div id="map-canvas"></div>

但输出结果却是空白页面。但如果我将JSON数据用于文件,这将完美无缺。

1 个答案:

答案 0 :(得分:1)

我的代码段中出现两个javascript错误:

  1. XMLHttpRequest cannot load http://www.tripleclickstudio.com/json/file.json?tags=location&tagmode=any&format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

  2. Uncaught TypeError: Cannot read property 'length' of undefined就行:

  3. for(var i = 0; i < responses.length; i++) {  
    

    因为在运行循环时不存在响应。 $ .getJSON是异步的,在运行回调函数(您尚未定义)之前,不会填充数据。但是,您的第一个问题是存在一个安全策略阻止您使用$ .getJSON下载它。您需要获得为您的域下载它的权限(标题中相应的Access-Control-Allow-Origin)或通过JSONP下载它。

    但是,当我这样做时,我的JSON中会出现语法错误。