search
HomeWeb Front-endH5 TutorialXiaoqiang's road to HTML5 mobile development (18) - HTML5 geolocation

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>

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>

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>

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>
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>

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

Statement
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
H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment