search
HomeWeb Front-endH5 TutorialApplication of HTML5 geolocation and third-party tool Baidu Map

Application of HTML5 geolocation and third-party tool Baidu Map

May 21, 2017 pm 03:02 PM
html5GeolocationBaidu mapThird party tools

This article mainly introduces the application of HTML5 geolocation and third-party tool Baidu Map in detail. It has certain reference value. Interested friends can refer to

Preface:
I have seen a lot of technical experts and related blogs, but there are very few descriptions of HTML5 geographical positioning. I don’t know if they are unwilling to mention it or because it is rarely used. I personally summarized the two based on a little experience. Reasons:
First, service provider reasons, because the positioning of HTML5 is provided by Google. Due to Google’s ban on mainland China, the positioning function is no longer supported. This is the main reason.
Second, HTML5 The built-in geo-positioning has poor performance. Compared with third-party tools---like Baidu Maps, etc., it is not on the same level. During real project development, the geo-positioning that comes with native HTML5 is rarely used. This is the first time Want a reason!

1. The new features of HTML5-geographic positioning
Since geo-positioning is a new feature of HTML5, we also need to learn and master the relevant APIs and learn how to use geography Positioning
First understand some common sense

A new termGeolocation:

is used to obtain the geography of the current browser coordinates to provide LBS (Location Based Service). Software such as Are You Hungry, Didi Taxi, and Amap all use LBS, including the following data:
Longitude: longitude
Latitude: latitude
Altitude: altitude
Speed: speed

The usage platform is divided into mobile and PC:
(1)Mobile browser:
First try to use the built-in GPS data— —The accuracy is in meters
Then use the mobile phone base station number to reversely deduce the corresponding geographical location-the positioning accuracy is in kilometers
(2)PC Browser:
Reverse query through the computer's IP address - The accuracy is in kilometers

The main topic:
So what are we doing? How to get positioning information from HTML5?
First, we press F12 in the browser to open the console, enter window.navigator.geolocation to see the positioning information!

We see that there are three main methods for positioning information, the meanings are:


getCurrentPosition:fn(succ,err) //获取当前定位数据,其中包含成功获取和获取失败的回调函数
watchPosition: fn   //监视定位数据
clearWatch: fn   //清除定位监视

Now that we know how to use geolocation in HTML5 files, we use development tools to create an HTML file and create a button. When the button is clicked, the location information is displayed in the background!


<!DOCTYPE html>  
<html>  
<head lang="en">  
    <meta charset="UTF-8">  
    <title></title>  
</head>  
<body>  
<button id="btn">获得我的定位数据</button>  
<script>  
    btn.onclick=function(){   //点击按钮时触发  
        navigator.geolocation.getCurrentPosition(succCB,errCB);  
  
        function succCB(pos){  //成功的获取回调函数!!  
            console.log(&#39;成功获取到定位数据&#39;);  
            console.log(&#39;纬度:&#39;+pos.coords.longitude);  
            console.log(&#39;经度:&#39;+pos.coords.latitude);  
            console.log(&#39;高度:&#39;+pos.coords.altitude);  
            console.log(&#39;速度:&#39;+pos.coords.speed);  
  
        }  
        function errCB(err){  //获取失败的回调函数!!  
            console.log(&#39;获取到定位数据失败&#39;);  
            console.log(err.message);  //输出失败的信息或原因!  
        }  
    }  
</script>  
</body>  
</html>

As shown in the figure, when the button is clicked, the positioning data is successfully obtained, but the height and speed are not correct due to PC issues. is Null, so we only need to remember one method to get geolocation in HTML5!


navigator.geolocation.getCurrentPosotion(
function(pos){
console.log(&#39;定位数据获取成功&#39;);
//pos.coords.longtitude ....
},
function(err){
console.log(&#39;定位数据获取失败&#39;);
//err.code   err.message
}
)

2. Use third-party tools--Baidu Map

As I mentioned in the preface, in Baidu Maps are used in projects and many mobile applications to provide users with location information. So how do we use Baidu Maps in our own projects?

First of all, we need to know that the source code of Baidu Maps will not be provided for everyone to download. This involves the interests of the company. People who understand do not need to say more, but Baidu is still a very conscientious company and allows us to register. Developer account to develop and use!

Usage steps:

First open the official website http://lbsyun.baidu.com/, and then scroll to the bottom:

##As you can see, Baidu Maps can be used for web development, Android development, and ios development. Here we use web development, click JavaScript API

Website: http://lbsyun.baidu.com/index.php? title=jspopular
We can go to many cases and function demonstrations in the API. To use Baidu Maps, you must first obtain the key!

I will explain what a key is later. Click to enter the page first. If the login interface pops up, log in. Log in and click to register a developer account (since I have already registered (so I can’t demonstrate it here, you need to do it yourself), enter the relevant mobile phone and email address, and then go to the email address to verify. After successful verification, click Create Application, and the following interface will appear:

应用名称随意填写一个
应用类型选择---浏览器端
Referer白名单:指的是谁可以访问你的应用,通过什么方式访问你的应用,这里填写一个星号' * ',意思是全部人都可以访问,因为只是做测试可以这样做,到以后项目如果使用到,会有相关的加密方式等等!!然后点击提交完成创建!!
完成应用的创建后,出现如下界面:

这里会显示刚才创建的应用编号,应用名称,以及最重要的访问应用码,就是前面提到的密钥!

然后得到密钥之后,我们回到主页http://lbsyun.baidu.com/index.php?title=jspopular
点击左侧的开发指南,可以看到相关API的用法以及案例!!,这个API是小编看到的所以API中最良心的,没有一句废话,
写的很详细,通俗易懂,因为实在太多了,就在这里介绍几个主要的用法!!!

我们创建一个新的HTML文件,将上面这段代码复制到HTML文件中


<!DOCTYPE html>  
<html>  
<head>  
    <meta charset="UTF-8"/>  
  
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=jrbPiu6jcbPsxGvdQXAc0C......">  
        //v2.0版本的引用方式:src="http://api.map.baidu.com/api?v=2.0&ak=您的密钥"  
        //v1.4版本及以前版本的引用方式:src="http://api.map.baidu.com/api?v=1.4&key=您的密钥&callback=initialize"  
    </script>  
  
    <style>  
        #container{  
            width: 800px;  
            height: 500px;  
        }  
    </style>  
</head>  
  
<body>  
<h1 id="使用百度地图">使用百度地图</h1>  
<p id="container"></p>  
<script type="text/javascript">  
    // 创建地图实例,避免与Map重名,所以使用BMap.Map  
    var map = new BMap.Map("container");  
    // 创建点坐标  
    var point = new BMap.Point(113.946317,22.549008);  
    // 初始化地图,设置中心点坐标和地图级别 1~18级  
    map.centerAndZoom(point, 18);  
  
    //鼠标滚动,地图缩放  
    map.enableScrollWheelZoom(true);  
  
    //添加地图控件  
    map.addControl(new BMap.NavigationControl());  
    map.addControl(new BMap.OverviewMapControl());  
    map.addControl(new BMap.ScaleControl());  
    map.addControl(new BMap.MapTypeControl());  
  
    //添加地图标注  
    var marker=map.addOverlay(new BMap.Marker(point));  
  
     
    
  
</script>  
</body>  
</html>

使用百度地图:

OK,我们成功的在HTML文件中使用了百度地图,现在可以像在http://map.baidu.com中一样使用百度地图了!!

相关函数说明:


 <script src="http://api.map.baidu.com/api?v=2.0&ak=您的网站在百度地图申请的访问秘钥 ">
  </script>

在ak中输入刚才得到那一长串密钥即可引用百度地图!!

创建地图实例 --必选。

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

创建一个指定的点 ,你的经纬度信息!!如果不知道可以使用前面的
navigator.geolocation.getCurrentPosotion方法来得到经纬度--必选。

var point = new BMap.Point(116.300982,39.915907); 

以指定点为中心显示地图  数字17指的是层级,层级可以分为1~18级,层级越小地图看的范围越大,层级越大看的范围越大,自己可以测试一下不同层级显示的地图效果!!---必选。

map.centerAndZoom(point, 17);

地图可以随着鼠标自由的缩放---可选。

map.enableScrollWheelZoom(true);

地图显示控件--效果自己测试,这里不是主要函数不再加以说明---可选。


map.addControl(new BMap.NavigationControl());
map.addControl(new BMap.OverviewMapControl());
map.addControl(new BMap.ScaleControl());
map.addControl(new BMap.MapTypeControl());

地图上显示一个标注(标注)--可选

var marker=map.addOverlay(new BMap.Marker(point));

OK,第三方百度地图就说到这里,还有许多好玩的函数可以自己使用,所以方法和参数都在API中可以找到!

The above is the detailed content of Application of HTML5 geolocation and third-party tool Baidu Map. For more information, please follow other related articles on the PHP Chinese website!

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: Exploring the Latest Version of HTMLH5: Exploring the Latest Version of HTMLMay 03, 2025 am 12:14 AM

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

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.

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function