HTML5中通過js獲取地理位置信息

前言

HTML5通過MUI框架做的定位打卡功能,怎樣獲得地理位置呢?參考了好多博客大部分使用的是百度或者高德的地圖接口。我也仿照着寫了一個。

正文

先上張圖看可能界面吧
在這裏插入圖片描述
這個界面是HBuilder通過運行到手機的界面,瀏覽器中的界面是這個樣子的
在這裏插入圖片描述
HTML的主要代碼

<div class="mui-input-row" style="height: 55px;">
					<div style="width: 80px;">
						<label style="width: 75px;padding: 13px 1px 11px 15px;"> <span class="mui-icon mui-icon-location-filled" style="font-size: medium;"></span>地點:</label>
					</div>
					<div style="width: 80%;padding: 10px 1px 11px 20px;position: relative;margin-left: 60px;" id="addr">
						位置獲取中...
					</div>
				</div>

js中的主要代碼


function Location() {};

Location.prototype.getLocation = function(callback) {
	var options = {
		enableHighAccuracy: true,
		maximumAge: 1000
	};
	this.callback = Object.prototype.toString.call(callback) == "[object Function]" ?
		callback :
		function(address) {
			alert(address.province + address.city);
			console.log("getocation(callbackFunction) 可獲得定位信息對象");
		};
	var self = this;
	if (navigator.geolocation) {
		//瀏覽器支持geolocation
		navigator.geolocation.getCurrentPosition(function(position) {
			//經度
			var longitude = position.coords.longitude;
			//緯度
			var latitude = position.coords.latitude;
			self.loadMapApi(longitude, latitude);
		}, self.onError, options);
	} else {
		//瀏覽器不支持geolocation
	}
};

Location.prototype.loadMapApi = function(longitude, latitude) {
	var self = this;
	var oHead = document.getElementsByTagName('HEAD').item(0);
	var oScript = document.createElement("script");
	oScript.type = "text/javascript";
	oScript.src =
		"http://api.map.baidu.com/getscript?v=2.0&ak=A396783ee700cfdb9ba1df281ce36862&services=&t=20140930184510";
	oHead.appendChild(oScript);
	oScript.onload = function(date) {
		var point = new BMap.Point(longitude, latitude);
		var gc = new BMap.Geocoder();
		gc.getLocation(point, function(rs) {
			var addComp = rs.addressComponents;
			self.callback(addComp);
		});
	}
};

Location.prototype.onError = function(error) {
	switch (error.code) {
		case 1:
			alert("位置服務被拒絕");
			break;
		case 2:
			alert("暫時獲取不到位置信息");
			break;
		case 3:
			alert("獲取信息超時");
			break;
		case 4:
			alert("未知錯誤");
			break;
	}
};

//調用
var local = new Location();
local.getLocation(function(res) {
	//此處就是返回的地理位置信息
	console.log(res);
	//JSON.stringify(res),把返回的對象轉爲字符串了,自己根據需求截取下就好
	var resstr = JSON.stringify(res);
	// alert(res.province+res.city+res.district+res.street+res.streetNumber);
	document.getElementById("addr").innerText = res.province+res.city+res.district+res.street+res.streetNumber;
});

然後就開始調試就好了配合蜂鳥助手更好用。

結束

PS:蜂鳥助手是一款模擬軟件,有興趣的朋友可以下載玩一玩。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章