js依据百度地图定位

2,025 阅读2分钟

目前了解的自动定位的方式有两种:

  1. PC通过IP地址定位。
  2. 移动端通过调百度地图接口定位。

今天来聊聊第二种的实现,会一步步带你写一个DEMO,超级简单,不要怕。

比较关键的技术点:

1. navigator中geolocation的getCurrentPosition方法:

getCurrentPosition使用方法:

navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options)

options:

option参数支持三个可选参数API,为:enableHighAccuracy, timeout, maximumAge.

1. enableHighAccuracy参数表示是否高精度可用,为Boolean类型,默认为false,如果开启,响应时间会变慢,同时,在手机设备上会用掉更多的流量,也就是money了。

2. timeout参数表示等待响应的最大时间,默认是0毫秒,表示无穷时间。

3. maximumAge表示应用程序的缓存时间。单位毫秒,默认是0,意味着每次请求都是立即去获取一个全新的对象内容。

2. 百度地图请求地址https://api.map.baidu.com/geocoder/v2/

需要的请求参数:

poi解释:

Point of interesting. 可以翻译为兴趣点,就是在地图上任何非地理意义的有意义的点:比如商店,酒吧,加油站,医院,车站等。不属于poi的是有地理意义的坐标:城市,河流,山峰 。

ak: 百度秘钥

location: 39.983424,116.322987 (维度,经度)

POI(0/1): 是否显示指定位置周边的poi,0为不显示,1为显示。当值为1时,显示周边100米内的poi。

下面是个小DEMO(最好传到服务器上验证):

<!DOCTYPE HTML>
<head>
    <script type="text/javascript">
        function showLocation(position) {
            var baiduGeoApi = {
                BAIDU_ACCESS_KEY: "o0LVi345SG0pu2IyhkEGTGw3dusTyFG7",
                API_PATH: "https://api.map.baidu.com/geocoder/v2/",
            };
            //**************************************************
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            alert("Latitude : " + latitude + " Longitude: " + longitude);
            var location = latitude + "," + longitude;
            var url = window.location.protocol + "//api.map.baidu.com/geocoder/v2/?ak=" + baiduGeoApi.BAIDU_ACCESS_KEY + "&callback=_sucCallback&location=" + location + "&output=json&pois=0";
            var script = document.createElement("script");
            script.setAttribute("src", url);
            var head = document.getElementsByTagName("head")[0];
            head.appendChild(script);
        }
 
        function _sucCallback (result){
            var cityInfo = result.result.addressComponent;
            <!--alert(cityInfo.city);省-->
            <!--alert(cityInfo.province);市-->
            <!--alert(cityInfo.district);区-->
    		if(result.status == 0){
    			var city = JSON.stringify(result.result.addressComponent.city),
    				province = JSON.stringify(result.result.addressComponent.province);
    		}else {
    			alert('err')
    		}
    		_sucCallback = null;
    	}

        function errorHandler(err) {
            if (err.code == 1) {
                alert("Error: Access is denied!");
            } else if (err.code == 2) {
                alert("Error: Position is unavailable!");
            }
        }

        function getLocation() {
            if (navigator.geolocation) {
                // timeout at 60000 milliseconds (60 seconds)
                var options = { timeout: 60000 };
                navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);
            } else {
                alert("Sorry, browser does not support geolocation!");
            }
        }
    </script>
</head>
<html>
    <body>
        <form>
            <input type="button" onclick="getLocation();" value="Get Location" />
        </form>
    </body>
</html>

参考链接: