Javascript全局变量的使用方法

1.demo例子说明

<script type="text/javascript">
    var gDivId;  //js全局变量

function geocoder(lastLon,lastLat,result) {
    alert("lastLon:"+lastLon);
    alert("lastLat:"+lastLat);
    alert("result:"+result);
    gDivId = result;  //赋值给全局变量
    
}

function testff(){
    alert("gDivId: " + gDivId);  //读取全局变量
}
</script>
<input type="button" value="逆地理编码" onclick="geocoder(1212,3434,'test')"/>

<input type="button" value="全局变量" onclick="testff()"/>

 

2.应用在高德地图中,根据经纬度来查询地址信息

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=d94035ac264f0cc5b293199360ca0e1e"></script>


</head>

<body>
<div id="iCenter" style="display:none;"></div>
            121.432921, 31.196159
              <div id="result"> </div>
              <input type="button" value="逆地理编码" onclick="geocoder('121.432921', '31.196159','result')"/>

<script language="javascript">

var mapObj;
var gDivId;

function geocoder(lastLon,lastLat,result) {    
    gDivId = result;  //赋值给全局变量
    
    //已知点坐标
    var lnglatXY = new AMap.LngLat(lastLon,lastLat);
    
    mapObj = new AMap.Map("iCenter", {
        view: new AMap.View2D({
        center:new AMap.LngLat(lastLon,lastLat),//地图中心点
        zoom:13 //地图显示的缩放级别
        })
    });
    
    var MGeocoder;
    //加载地理编码插件
    mapObj.plugin(["AMap.Geocoder"], function() {       
        MGeocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
        });
        //返回地理编码结果
        AMap.event.addListener(MGeocoder, "complete", geocoder_CallBack);
        //逆地理编码
        MGeocoder.getAddress(lnglatXY);
    });
    
    //mapObj.setFitView();
}

//回调函数
function geocoder_CallBack(data) {
    //返回地址描述
    address = data.regeocode.formattedAddress;

    //返回结果拼接输出,需要Jquery的支持。
    //$("#"+gDivId).html(address);
    document.getElementById(gDivId).innerHTML = address;
} 
</script>
            
</body>
</html>
posted @ 2014-07-17 15:40  全新时代-小小程序员大梦想  阅读(1262)  评论(0编辑  收藏  举报