<script type="text/javascript" src="js/BMap.js" ></script>
<script type="text/javascript">
// 扩展API是否准备好,如果没有则监听“plusready"事件
if(window.plus){
plusReady();
}else{
document.addEventListener( "plusready", plusReady, false );
}
// 扩展API准备完成后要执行的操作
function plusReady(){
var map = new BMap.Map("allmap");
var longitude, latitude;
navigator.geolocation.getCurrentPosition(function (position) {
longitude = position.coords.longitude;
latitude = position.coords.latitude;
});
setTimeout(function () {
var gpsPoint = new BMap.Point(longitude, latitude);
BMap.Convertor.translate(gpsPoint, 0, function (point) {
var geoc = new BMap.Geocoder();
geoc.getLocation(point, function (rs) {
var addComp = rs.addressComponents;
alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
});
});
}, 3000);
}
</script>
BMap.js:
(function(){
window.BMap_loadScriptTime = (new Date).getTime();
document.write('<script type="text/javascript" src="http://api.map.baidu.com/getscript?v=1.3"></script>');
document.write('<link rel="stylesheet" type="text/css" href="http://api.map.baidu.com/res/13/bmap.css"/>');
//2011-7-25
function load_script(xyUrl, callback){
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = xyUrl;
//借鉴了jQuery的script跨域方法
script.onload = script.onreadystatechange = function(){
if((!this.readyState || this.readyState === "loaded" || this.readyState === "complete")){
callback && callback();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
if ( head && script.parentNode ) {
head.removeChild( script );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
head.insertBefore( script, head.firstChild );
}
function translate(point,type,callback){
var callbackName = 'cbk_' + Math.round(Math.random() * 10000); //随机函数名
var xyUrl = "http://api.map.baidu.com/ag/coord/convert?from="+ type + "&to=4&x=" + point.lng + "&y=" + point.lat + "&callback=BMap.Convertor." + callbackName;
//动态创建script标签
load_script(xyUrl);
BMap.Convertor[callbackName] = function(xyResult){
delete BMap.Convertor[callbackName]; //调用完需要删除改函数
var point = new BMap.Point(xyResult.x, xyResult.y);
callback && callback(point);
}
}
window.BMap = window.BMap || {};
BMap.Convertor = {};
BMap.Convertor.translate = translate;
})();