HTML5 and Mobile Web: the geographic positioning

一, Geolocation API

Check whether the browser supports geopositioning

function getLocation() {
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(showPosition, showError);
	} else {
		x.innerHTML = "该浏览器不支持获取地理位置。";
	}
}

Get the current location

navigator.geolocation.getCurrentPosition(showPosition, showError);
function showPosition(position) {
	x.innerHTML = "纬度: " + position.coords.latitude +"<br>经度: " + position.coords.longitude;
}
function showError(error) {
	switch (error.code) {
		case error.PERMISSION_DENIED:
			x.innerHTML = "用户拒绝对获取地理位置的请求。"
			break;
		case error.POSITION_UNAVAILABLE:
			x.innerHTML = "位置信息是不可用的。"
			break;
		case error.TIMEOUT:
			x.innerHTML = "请求用户地理位置超时。"
			break;
		case error.UNKNOWN_ERROR:
			x.innerHTML = "未知错误。"
			break;
	}
}

Continuous monitoring location information

navigator.geolocation.watchPosition(showPosition, showError);

Stop monitoring the location information 

navigator.geolocation.clearWatch(watchId);

Second, Baidu API

step

1 , registered Baidu account, in http://lbsyun.baidu.com/apiconsole/key?application=key  page application key (AK)

2, page introduction: <script type = "text / javascript" src = "http://api.map.baidu.com/api?v=2.0&ak= your key "> </ script>

 

3 , map requires a HTML element as a container, in order to show on the page. Here we create a div element.

<body><div id = "allmap"></div></body>

 

4 , instantiation map

<script type="text/javascript">

    // Baidu Maps API function

    var map = new BMap.Map("allmap");

    map.centerAndZoom (new BMap.Point (120.378386,30.309756), 15); // According to initialize the map coordinates

     map.enableScrollWheelZoom(true);

    map.addControl (new BMap.NavigationControl ()); // pan and zoom controls

    map.addControl (new BMap.ScaleControl ()); // Scale

    map.addControl (new BMap.OverviewMapControl ()); // thumbnail map

    map.addControl (new BMap.MapTypeControl ()); // map type

    map.setCurrentCity ( " Hangzhou "); // Only when setting the city information, MapTypeControl the switching function can be used

     // add callouts

    var marker = new BMap.Marker (new BMap.Point (120.378386,30.309756)); // Create Dimensions

    map.addOverlay (marker); // will mark added to the map

</script>

Map control

Control Abstract base class for controls, all controls are inherited class methods, properties. You can be achieved by such a custom control.
NavigationControl

Map pan and zoom controls, PC terminal located by default in the top left of the map that contains the control map panning and zooming capabilities. Mobile terminal providing zoom controls, located by default in the bottom right of the map.

OverviewMapControl

Thumbnail map control, the default is located in the bottom right of the map, it is a collapsible thumbnail map.

ScaleControl Scale control, the default is located in the bottom left of the map, showing the ratio between the map.
MapTypeControl Map type control, the default top right of the map (map, satellite, three-dimensional).
CopyrightControl Copyright control, the default is located in the bottom left of the map.
GeolocationControl Positioning controls for mobile terminal development, located by default in the bottom left of the map.

Maps covering

Overlay

Abstract base class covering material, covering all such methods are inherited.

Marker Mark represents the point on the map, marked customizable icons.
Label

Represents a text marked on the map, you can customize the text label.

Polyline He represents polyline on the map.
Polygon

He represents polygon on the map. Polygon similar to a closed polyline. Alternatively, you can also to add a fill color.

Circle Represent the circle on the map.
InfoWindow

Information window is also a special cover, it can show richer text and multimedia messages. Note: the same time, only one message window opens on your map.

Example

<!DOCTYPE html>
<html>   
<title>Geolocation和百度地图API进行地理定位实例</title>   
    <head>   
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
        <style>
            body, html,#container {
                width: 100%;
                height: 100%;
                overflow: hidden;
                margin:0;
                font-family:"微软雅黑";
            }
        </style>
        <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=134db1b9cf1f1f2b4427210932b34dcb"></script>   
    </head>   
    <body>   
        <div id="status" style="text-align: center"></div>   
        <div id="container"></div>   
    </body>   
</html>   
     
<script type="text/javascript">   
    //默认地理位置设置为上海市浦东新区 
    var x = 121.48789949,y = 31.24916171;
    var tip = document.getElementById("status");
    window.onload = function() {   
        if(navigator.geolocation) {
            // navigator有3个方法:clearWatch、getCurrentPosition、watchPosition
            navigator.geolocation.getCurrentPosition(showPosition);  
                // 百度地图API功能   
                var map = new BMap.Map("container", {enableMapClick:false}); // 创建Map实例
                var point = new BMap.Point(x,y); // 设置中心点坐标  
                map.centerAndZoom(point,12); // 初始化地图,设置中心点坐标和地图级别、
                map.addControl(new BMap.MapTypeControl()); // 添加地图类型
				map.addControl(new BMap.OverviewMapControl()); // 添加地图类型控件
				map.addControl(new BMap.ScaleControl()); // 地图添加比例尺
				map.addControl(new BMap.NavigationControl()); // 地图添加缩放比例
                map.setCurrentCity("上海"); // 设置地图显示的城市,此项是必须设置的
                map.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放
     
                var geolocation = new BMap.Geolocation(); // geolocation 有2个方法:getCurrentPosition、getStatus
                geolocation.getCurrentPosition(
                    function(r){ // 成功的回调
                        console.log("通过百度地图定位");
                        if(this.getStatus() == BMAP_STATUS_SUCCESS){   
                            var mk = new BMap.Marker(r.point);   
                            map.addOverlay(mk);   
                            map.panTo(r.point);   
                        }else {   
                            alert('failed'+this.getStatus()); // 此处的this指代 geolocation  
                        }
                    },
                    function(error){ // 失败的回调
                        switch(error.code) {
                            case error.TIMEOUT:
                                tip.innerHTML = "A timeout occured! Please try again!发生超时!请重试!";
                                break;
                            case error.POSITION_UNAVAILABLE:
                                tip.innerHTML = 'We can\'t detect your location. Sorry!我们无法探测到你的位置,对不起!';
                                break;
                            case error.PERMISSION_DENIED:
                                tip.innerHTML = 'Please allow geolocation access for this to work.请允许访问地理位置';
                                break;
                            case error.UNKNOWN_ERROR:
                                tip.innerHTML = 'An unknown error occured!发生未知错误!';
                                break;
                        }
                    },{
                    // 指示浏览器获取高精度的位置,默认为false
                    enableHighAccuracy: true,
                    // 指定获取地理位置的超时时间,默认不限时,单位为毫秒
                    timeout: 5000,
                    // 最长有效期,在重复获取地理位置时,此参数指定多久再次获取位置。
                    maximumAge: 3000
                })  
            return; 
        }   
        alert("你的浏览器不支持获取地理位置!");
    };   
    function showPosition(position){  // 成功的回调
        console.log("通过原生H5的geolocation定位");
        x = position.coords.latitude; // 维度 
        y = position.coords.longitude; // 经度
    };
</script>

 

 

 

 

 

 

 

 

 

Published 349 original articles · won praise 161 · views 190 000 +

Guess you like

Origin blog.csdn.net/qq_42192693/article/details/103442184