HTML5 Base Extension-geo-location, local storage, cache

Source: Internet
Author: User
Tags web database

HTML5 extension, following two blog posts, let's take a look at some of the extended features of HTML5, since HTML5 is more compatible with computer browsers, Android browsers, Apple browser more browsers, or provide a uniform standard for these browsers. So the current web development on mobile phones, HTML5 is relatively fire. Therefore, these extended functions, feel more from the mobile phone, tablet and other points of view.

One, geo-positioning: First look at the geographical location of several forms: IP address, GPS (Global Positioning System), WIFI,GSM (Global system for Mobile communication)/ CDMA (Code Division multiple Access). General mobile phones are located by GPs, relatively accurate. Look at that. HTML5 how to achieve geographic location:

1. Enable browser-based (no backend support) to obtain the user's geo-location technology

2. Accurate positioning of the user's geographical location (accuracy up to 10m, dependent on the device)

3. Keep track of the user's location (live location)

4. Interact with Google map, or Baidu map to render location information.

HTML5 provides the geolocation API for sharing the user's current geo-location information to a trusted site, which involves a user's privacy security issue, so when a site needs to get the user's current location, the browser prompts the user to "allow" or "deny." The method it provides:

1, getcurrentposition//Current position

2, watchposition//monitoring location

3, Clearwatch//clear monitoring

Take a look at the parameters:

The GetCurrentPosition (success,error,option) method can have a maximum of three parameters:

The first parameter is a callback function that successfully obtains the location information, which is the only parameter required by the method;

The second parameter is used to capture the situation where the location information is getting wrong.

The third parameter is a configuration item.

Let's look at an example:

?
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 <p id="demo">点击这个按钮,获得您的位置:</p><button onclick="getLocation()">试一下</button><div id="mapholder"></div><script>    //获取id为demo的标签    var x=document.getElementById("demo");    //getLocation获取位置的函数,单击是调用    function getLocation()      {        //如果浏览器支持      if (navigator.geolocation)        {        //获取当前位置,分别传入了成功和失败的两个函数        navigator.geolocation.getCurrentPosition(showPosition,showError);        }        //如果不支持,则进行提示      else{x.innerHTML="Geolocation is not supported by this browser.";}      }    //获取成功,调用的函数showPosition    function showPosition(position)      {        //获取经度和维度      var latlon=position.coords.latitude+","+position.coords.longitude;       //利用谷歌地图进行显示,当然了也可以通过百度地图      var img_url="http://maps.googleapis.com/maps/api/staticmap?center="      +latlon+"&zoom=14&size=400x300&sensor=false";      document.getElementById("mapholder").innerHTML=""+img_url+"" style="display: none;">加载中..." title="图片加载中..." src="http://www.2cto.com/statics/images/s_nopic.gif">";      }    //错误调用的函数    function showError(error)      {      switch(error.code)         {            //错误1        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>

For the simple geographical positioning of the understanding, because just learning, understand the relatively superficial. More information can be network search, very much, it is easy to help us to achieve the mobile phone positioning function development.

Second, independent data storage: The meaning is to store data locally, due to the problem of mobile phone traffic, this feature in the mobile phone client is very popular. Here's a look at web local storage and Web SQLDatabase.

1,web Local Storage is a Windows property, including Localstorage and Sessionstorage, from which the name should easily differentiate between the two, the former is stored locally, the latter can only accompany the session, and the window will disappear. The usage is basically the same, see localstorage here:

First look at the method of access:

Well, look at an example:

?
12345678910111213141516 <script type="text/javascript">    if (localStorage.pagecount) {        localStorage.pagecount = Number(localStorage.pagecount) + 1;    } else {        localStorage.pagecount = 1;    }    document.write("Visits: " + localStorage.pagecount + " time(s).");</script><p>刷新页面会看到计数器在增长。</p><p>请关闭浏览器窗口,然后再试一次,计数器会继续计数。</p>

The 2,web SQL Database:web SQL database API is not actually part of the HTML5 specification, but rather a separate specification. It manipulates the client's database through a set of APIs. The meaning is to install a database to the browser, can be like mysql,oracle, and so on data deletion and modification, just more powerful than localstorage. Opening the browser's development tool, we can see:

See an example:

?
1234567891011121314151617181920212223242526272829303132333435363738394041424344 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>html5-dataBase</title><script type="text/javascript">    //创建数据库    var db = window.openDatabase("mydata", "1.0", "数据库描述", 20000);     //window.openDatabase("数据库名字", "版本","数据库描述",数据库大小);    if (db)        alert("新建数据库成功!");    db.transaction(function(tx) {        //执行sql语句,创建表        tx.executeSql("CREATE TABLE test (id int UNIQUE, mytitle TEXT, timestamp REAL)");    });    db.transaction(function(tx) {        //插入数据        tx.executeSql("INSERT INTO test (mytitle, timestamp) values(?, ?)", ["WEB Database", new Date().getTime()], null, null);    });     //db.transaction(function(tx) {     // tx.executeSql("DROP TABLE qqs");     //})     //db.transaction(function(tx) {     // tx.executeSql("update test set mytitle=? where mytitle = "fsafdsaf"",[‘xp‘],null,null);     //});    //查询数据库    db.transaction(function(tx) {        tx.executeSql("SELECT * FROM test", [],            function(tx, result) {                for (var i = 0; i < result.rows.length; i++) {                    document.write(‘<b>‘ + result.rows.item(i)[‘mytitle‘] + ‘</b><br>‘);                }            }, function() {                alert("error");            });    });</script>

The basic knowledge of local storage for HTML5.

Third, new network connection cache: HTML5 You can easily create an offline version of your Web app by creating a cache manifest file. In addition to IE, other browsers are already supported. For the mobile phone has a very big advantage, such as we download a good game, can play offline, and so on the network and then data synchronization. Advantage:

Offline Browsing-users can use them when the app is offline

Speed-cached resources are loaded faster

Reduce server load-The browser will download only updated or changed resources from the server.

The procedure is also relatively simple, specifically did not experiment, you can try, in the manifest file to add we want to cache the filename can be.

Well, for a simple extension, we can deepen the data through the network. Of course, this is just a part of the expansion, and there's a lot of HTML5 to learn from it. Need to accumulate slowly in the continuous.

HTML5 Base Extension-geo-location, local storage, cache

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.