分享

Ajax支持的Google地图Mashup教程(4)

 guoxi022 2007-06-14

Ajax支持的Google地图Mashup教程

作者: ,  出处:Dev2Dev, 责任编辑: 叶江, 
2007-06-13 14:59
  本文中将使用工具轻松构建终极的Hello World mashup:Google地图mashup……
 

  客户端将使用XMLHttpRequest 从REST服务检索JSON 对象。一旦检索到该对象,JavaScript 代码将需要反序列化对象,然后遍历整个数组。看一下mapper.js,就可以看到 getLocationsAndMap 和 getLocationsAndMapCallback 函数完成了这一功能:

// Gets the current locations from the REST service
// on the server and writes out the HTML that
// contains links for the map

function getLocationsAndMap() {
 if (receiveReq.readyState == 4 ||
     receiveReq.readyState == 0)
 {     
   // getD2DSites.html is a REST service
   // that returns the list of locations
   // as JSON
 
   receiveReq.open("GET", ‘getD2DSites.html‘,
                   true);              
   receiveReq.onreadystatechange =
               getLocationsAndMapCallback;     
   receiveReq.send(null);      
 } // end  if  
} // end  function

function getLocationsAndMapCallback() {
 // state == 4 is when the response is complete
 if (receiveReq.readyState == 4) {             
  // Deserialize the JSON response (eval() command)
  // This creates an array of location objects.
  var response = eval("("+request.responseText+")");
  // generate HTML listing the locations and update 
  //   the page DOM so the user will see the HTML
  var div = document.getElementById(‘loc_div‘);        
  div.innerHTML = ‘<p>Received ‘ +
   response.locations.location.length+‘ results.‘;
 
  for(i=0;i < response.locations.location.length; i++) {
        var city = response.locations.location[i].city;
        var anchor = ‘‘; // TODO: we will fix this later
        div.innerHTML += ‘<p><b>‘+ city + ‘</b> ‘ +
          anchor + loc + ‘</a><br/>‘ + addr + ‘</p>‘;
  } // end  for loop
 } // end   if (state == 4)
} // end   function

  请注意, eval 调用将接收JSON 并对它进行计算,有效地构建一个可以导航的JavaScript数组。For 循环显示了如何在数组内遍历地理位置:

  至此,您已经完成了这些工作:

  •   创建一个静态的 REST 服务 HTML 文件
  •   向HTML文件添加一个JSON 有效负载
  •   编写代码通过eval()将JSON 重构为一个JavaScript 对象
  •   编写代码来循环遍历地址数组,使用新的HTML操纵DOM

  现在,让我们来看如何在Google 地图中显示这些位置。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多