Home > Web Front-end > H5 Tutorial > Xiaoqiang's road to HTML5 mobile development (18) - HTML5 geolocation

Xiaoqiang's road to HTML5 mobile development (18) - HTML5 geolocation

黄舟
Release: 2017-01-22 13:56:20
Original
1459 people have browsed it

In the previous article "Xiaoqiang's HTML5 Mobile Development Road (2) - New Features of HTML5", we introduced the geolocation function of HTML5. In this article, we will learn more about how to use this function.

Html5 Geolocation API is used to obtain the user's geographical location.

In view of the fact that this feature may infringe on the user's privacy, the user's location information is not available unless the user agrees, and the browser will pop up a reminder box when using this feature.

1. Several methods of geolocation

IP address, GPS, Wifi, GSM/CDMA

2. Geographic location acquisition process


1. The user opens a web application that needs to obtain the geographical location.

2. The application requests the geographical location from the browser, and the browser pops up a query asking the user whether to share the geographical location.

3. Assuming the user allows it, the browser queries the relevant information from the device.

4. The browser sends relevant information to a trusted location server, and the server returns the specific geographical location.


3. Browser support

IE9.0+, FF3.5+, Safari5.0+, Chrome5.0+, Opera10.6 + Supports geolocation.

Note: For devices with GPS, such as iPhone (IPhone3.0+, Android2.0+), geographical positioning is more accurate.

4. Methods of geographical positioning in HTML5


##GeolocationAPI exists in the navigator object and only contains 3 methods:

1. getCurrentPosition //Current location

2.watchPosition //Monitoring position

3.clearWatch //Clear monitoring

5. Geolocation method getCurrentPosition()

<!DOCTYPE html>  
<html>  
<body>  
    <p id="demo">点击这个按钮,获得您的坐标:</p>  
    <button onclick="getLocation()">试一下</button>  
    <script>  
        var x=document.getElementById("demo");  
        function getLocation(){  
          if (navigator.geolocation){  //判断是否支持地理定位  
              //如果支持,则运行getCurrentPosition()方法。  
              navigator.geolocation.getCurrentPosition(showPosition);  
          }else{  
              //如果不支持,则向用户显示一段消息  
              x.innerHTML="Geolocation is not supported by this browser.";  
          }  
        }  
  
        //获取经纬度并显示  
        function showPosition(position){  
            x.innerHTML="Latitude: " + position.coords.latitude +   
            "<br />Longitude: " + position.coords.longitude;    
        }  
    </script>  
</body>  
</html>
Copy after login

Xiaoqiangs road to HTML5 mobile development (18) - HTML5 geolocation

The getCurrentPosition(success,error,option) method can have up to three parameters:

The first parameter of the getCurrentPosition() method calls back a showPosition() function And pass the location information to the function, obtain the location information from the function and display it,

The second parameter of the getCurrentPostion() method is used to handle error information, it is the callback function that fails to obtain the location information

The third parameter of the getCurrentPostion() method is the configuration item. This parameter is an object and affects the details of obtaining the position.

<!DOCTYPE html>  
<html>  
<body>  
    <p id="demo">点击这个按钮,获得您的坐标:</p>  
    <button onclick="getLocation()">试一下</button>  
    <script>  
        var x=document.getElementById("demo");  
        function getLocation(){  
          if (navigator.geolocation){  //判断是否支持地理定位  
              //如果支持,则运行getCurrentPosition()方法。  
              navigator.geolocation.getCurrentPosition(showPosition,showError);  
          }else{  
              //如果不支持,则向用户显示一段消息  
              x.innerHTML="Geolocation is not supported by this browser.";  
          }  
        }  
  
        //获取经纬度并显示  
        function showPosition(position){  
            x.innerHTML="Latitude: " + position.coords.latitude +   
            "<br />Longitude: " + position.coords.longitude;    
        }  
  
        //错误处理函数  
        function showError(error){  
          switch(error.code)  //错误码   
            {  
            case error.PERMISSION_DENIED:  //用户拒绝  
              x.innerHTML="User denied the request for Geolocation."  
              break;  
            case error.POSITION_UNAVAILABLE:  //无法提供定位服务  
              x.innerHTML="Location information is unavailable."  
              break;  
            case error.TIMEOUT:  //连接超时  
              x.innerHTML="The request to get user location timed out."  
              break;  
            case error.UNKNOWN_ERROR:  //未知错误  
              x.innerHTML="An unknown error occurred."  
              break;  
            }  
         }  
    </script>  
</body>  
</html>
Copy after login

6. Display the results in Google Maps

<!DOCTYPE html>  
<html>  
<body>  
    <p id="demo">点击这个按钮,获得您的位置:</p>  
    <button onclick="getLocation()">试一下</button>  
    <div id="mapholder"></div>  
        <script src="http://maps.google.com/maps/api/js?sensor=false"></script>  
        <script>  
            var x=document.getElementById("demo");  
                function getLocation(){  
                   if (navigator.geolocation){  
                     navigator.geolocation.getCurrentPosition(showPosition,showError);  
                    }else{  
                        x.innerHTML="Geolocation is not supported by this browser.";  
                    }  
                }  
  
                function showPosition(position){  
                      lat=position.coords.latitude;  
                      lon=position.coords.longitude;  
                      latlon=new google.maps.LatLng(lat, lon)  
                      mapholder=document.getElementById(&#39;mapholder&#39;)  
                      mapholder.style.height=&#39;250px&#39;;  
                      mapholder.style.width=&#39;500px&#39;;  
  
                      var myOptions={  
                          center:latlon,zoom:14,  
                          mapTypeId:google.maps.MapTypeId.ROADMAP,  
                          mapTypeControl:false,  
                          navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}  
                      };  
                      var map=new google.maps.Map(document.getElementById("mapholder"),myOptions);  
                      var marker=new google.maps.Marker({position:latlon,map:map,title:"You are here!"});  
                 }  
  
                function showError(error){  
                      switch(error.code){  
                        case error.PERMISSION_DENIED:  
                          x.innerHTML="User denied the request for Geolocation."  
                          break;  
                        case error.POSITION_UNAVAILABLE:  
                          x.innerHTML="Location information is unavailable."  
                          break;  
                        case error.TIMEOUT:  
                          x.innerHTML="The request to get user location timed out."  
                          break;  
                        case error.UNKNOWN_ERROR:  
                          x.innerHTML="An unknown error occurred."  
                          break;  
                        }  
                }  
        </script>  
</body>  
</html>
Copy after login

Xiaoqiangs road to HTML5 mobile development (18) - HTML5 geolocation## 7. Display the results in Baidu Maps

1. Go to Baidu Developer to get the map display key

http://developer.baidu.com/map/jshome.htm

<!DOCTYPE html>  
<html>  
<body>  
    <p id="demo">点击这个按钮,获得您的位置:</p>  
    <button onclick="getLocation()">试一下</button>  
    <div id="mapholder" style="width:600px;height:500px;"></div>  
        <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你自己的密钥"></script>  
        <script>  
            var x=document.getElementById("demo");  
                function getLocation(){  
                   if (navigator.geolocation){  
                     navigator.geolocation.getCurrentPosition(showPosition,showError);  
                    }else{  
                        x.innerHTML="Geolocation is not supported by this browser.";  
                    }  
                }  
  
                function showPosition(position){  
                    //alert(position.coords.longitude + " ___ " + position.coords.latitude);  
                       
                    // 百度地图API功能  
                    var map = new BMap.Map("mapholder");            // 创建Map实例  
                    var point = new BMap.Point(position.coords.longitude, position.coords.latitude);    // 创建点坐标  
                    map.centerAndZoom(point,15);                     // 初始化地图,设置中心点坐标和地图级别。  
                    map.enableScrollWheelZoom();   
                 }  
  
                function showError(error){  
                      switch(error.code){  
                        case error.PERMISSION_DENIED:  
                          x.innerHTML="User denied the request for Geolocation."  
                          break;  
                        case error.POSITION_UNAVAILABLE:  
                          x.innerHTML="Location information is unavailable."  
                          break;  
                        case error.TIMEOUT:  
                          x.innerHTML="The request to get user location timed out."  
                          break;  
                        case error.UNKNOWN_ERROR:  
                          x.innerHTML="An unknown error occurred."  
                          break;  
                        }  
                }  
        </script>  
</body>  
</html>
Copy after login
Xiaoqiangs road to HTML5 mobile development (18) - HTML5 geolocationNote : If you copy the above code, please replace "your own key" with the key applied for in Baidu Developer Center

Xiaoqiangs road to HTML5 mobile development (18) - HTML5 geolocation


You can see that the positioning references of Google Map and Baidu Map are different, so the positioning error using IP is very large. 8. getCurrentPosition() method - return data



If successful, the getCurrentPosition() method returns the object. The latitude, longitude, and accuracy properties are always returned. If available, the other following properties are returned.



Attribute

Description

coords.latitude Decimal number Latitude

coords.longitude Longitude as a decimal number

coords.accuracy Position accuracy

coords.altitude Altitude, in meters above sea level

coords. altitudeAccuracy Altitude accuracy of the location

coords.heading Direction, in degrees from true north

coords.speed Speed, in meters per second

timestamp Date of the response /Time



You can also get the geographical location (only supported by firefox)


p.address.country Country

p.address.region Province

p.address.city City

9. Monitoring location (in mobile device)



watchPosition() - Returns the user's current position and continues to return updated positions as the user moves (like a GPS in a car).

clearWatch() - Stopping the watchPosition() method

The following example shows the watchPosition() method

watchPosition acts like a tracker paired with clearWatch.

watchPosition and clearWatch work a bit like setInterval and clearInterval.

varwatchPositionId =navigator.geolocation.watchPosition(success_callback,error_callback,options);

navigator.geolocation.clearWatch(watchPositionId);

<!DOCTYPE html>  
<html>  
<body>  
<p id="demo">点击这个按钮,获得您的坐标:</p>  
<button onclick="getLocation()">试一下</button>  
<script>  
var x=document.getElementById("demo");  
function getLocation()  
  {  
  if (navigator.geolocation)  
    {  
    navigator.geolocation.watchPosition(showPosition);  
    }  
  else{x.innerHTML="Geolocation is not supported by this browser.";}  
  }  
function showPosition(position)  
  {  
  x.innerHTML="Latitude: " + position.coords.latitude +   
  "<br />Longitude: " + position.coords.longitude;      
  }  
</script>  
</body>  
</html>
Copy after login

以上就是 小强的HTML5移动开发之路(18)——HTML5地理定位的内容,更多相关内容请关注PHP中文网(www.php.cn)!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template