JavaScript一个google地图获取

<script type="text/javascript">
/**
 * 返回一个新创建的<img>元素,该元素用于在获取到地理位置信息后,显示一张Google地图
 * 该地图上显示了当前的位置,要注意的是,次函数的调用者必须要将返回的元素
 * 插入到文档中,以使它可见
 * 如果当前浏览器不支持地理位置API,则抛出一个错误
 */
function getmap(){
	//检查是否支持地理位置API
	if(!navigator.geolocation)
		throw "Geolocation not supported"

	//创建一个行的<img>元素,并开始请求地理位置信息
	//<img>元素显示包含当前位置的地图,然后再将返回该图片
	var image = document.createElement("img");
	image.width = 640;
	image.height = 640;
	navigator.geolocation.getCurrentPosition(setMapURL);
	return image;

	//当(如果)成功获取到地理位置信息后,会在返回image对象后调用此方法
	function setMapURL(pos){
		//从参数对象pos中获取地理位置信息
		var latitude = pos.coords.latitude;		//经度
		var longitude = pos.coords.longitude;		//纬度
		var accuracy = pos.coords.accuracy;		//米

		//构造 一个URL,用于请求一张显示当前位置的静态Google地图
		var url = "http://map.google.com/maps/api/staticmap"+"?conter="+
			latitude+","+longitude+"&size=640x640&sensor=true";
		console.log(url);

		//设置一个大致的缩放级别
		var zoomlevel = 20;	//以各种方式开始缩放
		if(accuracy > 80)		//在低精度的情况下放大
			zoomlevel -= Math.round(Math.log(accuracy/50)/Math.LN2);
		url += "&zoom="+zoomlevel;		//将缩放级别添加到URL中
		//现在在image对象中显示该地图,
		image.src = url;
	}
}
var a = getmap();
document.body.appendChild(a);
</script>

  

posted @ 2017-06-02 17:36  newAdmin  阅读(1321)  评论(0编辑  收藏  举报