HTML地理位置定位

最近公司项目需要做一个类似微信朋友圈的互动交友功能,需要显示用户位置信息,因此在网上查了部分资料,记下demo供以后查看学习:(用到了百度api来实现定位功能)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>地理位置测试</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>

 

posted @ 2016-09-01 14:30  代码书生  阅读(6050)  评论(4编辑  收藏  举报