最近公司項目需要做一個類似微信朋友圈的互動交友功能,需要顯示用戶位置信息,因此在網上查了部分資料,記下demo供以後查看學習:(用到了百度api來實現定位功能)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>地理位置測試www.linuxidc.com</title>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.3"></script>
<script type="text/javascript" src="http://developer.baidu.com/map/jsdemo/demo/convertor.js"></script>
<script type="text/javascript" src="jquery.1.10.1.min.js"></script>
<script type="text/javascript">
var gpsPoint;
var baiduPoint;
var baiduAddress;
function getLocation() {
//獲取GPS坐標
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showMap, handleError, { enableHighAccuracy: true, maximumAge: 1000 });
} else {
alert("您的浏覽器不支持使用HTML 5來獲取地理位置服務");
}
}
function showMap(value) {
var longitude = value.coords.longitude;
var latitude = value.coords.latitude;
gpsPoint = new BMap.Point(longitude, latitude);
BMap.Convertor.translate(gpsPoint, 0, translateCallback);
}
translateCallback = function (point) {
baiduPoint = point;
var geoc = new BMap.Geocoder();
geoc.getLocation(baiduPoint, getCityByBaiduCoordinate);
}
function getCityByBaiduCoordinate(rs) {
baiduAddress = rs.addressComponents;
var address = baiduAddress.city + baiduAddress.district + baiduAddress.street + baiduAddress.streetNumber;
$("#showdiv").html(address);
}
function handleError(value) {
switch (value.code) {
case 1:
alert("位置服務被拒絕");
break;
case 2:
alert("暫時獲取不到位置信息");
break;
case 3:
alert("獲取信息超時");
break;
case 4:
alert("未知錯誤");
break;
}
}
function init() {
getLocation();
}
window.onload = init;
</script>
</head>
<body>
<div id="showdiv"></div>
</body>
</html>