HTML5 Achieve access to geographic information and positioning function

Preface

This article mainly introduces HTML5 Achieve access to geographic information and positioning function , This article explains the original HTML5、 Baidu Maps 、 Google maps and other three ways to get location information and locate , Friends in need can refer to .

HTML5 It provides the function of geographic location (Geolocation API), Able to locate users , We can use HTML5 Based on this feature, we develop applications based on geographic information . In this paper, we will share how to use HTML5, With Baidu 、 Google Maps interface to get the user's accurate geographic location information .

How to use HTML5 Location function

Positioning function (Geolocation) yes HTML5 New features , So only in support of HTML5 Running on a modern browser , Especially handheld devices like iphone, More accurate geographic positioning . First, we need to check whether the user's device browser supports geolocation , If so, get geographic information . Note that this feature may invade the user's privacy , Unless the user agrees , Otherwise, the user's location information is not available , So when we visit the app, we will ask if geolocation is allowed , Of course, we can choose to allow it .

function getLocation(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition,showError);
}else{
alert(" Browsers don't support geolocation .");
}
}

You can see from the code above , If the user device supports geolocation , Then run  getCurrentPosition()  Method . If getCurrentPosition() The successful running , Then the direction parameter showPosition The function specified in returns a coordinates object ,getCurrentPosition()  The second argument to the method showError Used to handle errors , It specifies the function to run when getting the user's location fails .

Let's start with functions showError(), It specifies how to handle some error codes in case of failure to obtain the user's geographical location :

function showError(error){
switch(error.code) {
case error.PERMISSION_DENIED:
alert(" seek failed , The user refused to request geolocation ");
break;
case error.POSITION_UNAVAILABLE:
alert(" seek failed , Location information is not available ");
break;
case error.TIMEOUT:
alert(" seek failed , Request to get user location timed out ");
break;
case error.UNKNOWN_ERROR:
alert(" seek failed , Positioning system failure ");
break;
}
}

Let's look at functions showPosition(), call coords Of latitude and longitude You can get the latitude and longitude of the user .

function showPosition(position){
var lat = position.coords.latitude; // latitude
var lag = position.coords.longitude; // longitude
alert(' latitude :'+lat+', longitude :'+lag);
}

Use Baidu map and Google map interface to get user address

Above we know HTML5 Of Geolocation You can get the longitude and latitude of the user , So what we need to do is turn the abstract latitude and longitude into readable and meaningful real user geographic information . Fortunately, baidu maps and Google maps provide this interface , We just need to put HTML5 The obtained longitude and latitude information is transmitted to the map interface , Will return the user's geographic location , Including information of provinces and cities , There are even streets 、 House number and other detailed geographic information .

Let's first define the elements to show the geographical location on the page , Defining the id#baidu_geo and id#google_geo. We just need to modify the key functions showPosition().

Let's look at Baidu map interface interaction first , We pass the latitude and longitude information through Ajax Send to Baidu map interface , The interface will return the street information of the corresponding province or city . Baidu map interface returns a string of JSON data , We can present the information we need to #baidu_geo. Notice the use of jQuery library , You need to load jQuery The library files .

 function showPosition(position){
var latlon = position.coords.latitude+','+position.coords.longitude;
//baidu
var url = "
<ahref="http://api.map.baidu.com/geocoder/v2/?ak=C93b5178d7a8ebdb830b9b557abce78b&callback=renderReverse&location="+latlon+"&output=json&pois=0</a>";
$.ajax({
type: "GET",
dataType: "jsonp",
url: url,
beforeSend: function(){
$("#baidu_geo").html(' Locating ...');
},
success: function (json) {
if(json.status==0){
$("#baidu_geo").html(json.result.formatted_address);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#baidu_geo").html(latlon+" Address location acquisition failed ");
}
});
});

Let's look at Google Maps interface interaction . Again, we'll pass the latitude and longitude information through Ajax Send it to Google Maps interface in different ways , The interface will return the street details of the corresponding province or city . The Google Maps interface also returns a string of JSON data , these JSON The data is more detailed than that returned by Baidu map interface , We can present the information we need to #google_geo.

function showPosition(position){
var latlon = position.coords.latitude+','+position.coords.longitude;
//google
var url = 'http://maps.google.cn/maps/api/geocode/json?latlng='+latlon+'&language=CN';
$.ajax({
type: "GET",
url: url,
beforeSend: function(){
$("#google_geo").html(' Locating ...');
},
success: function (json) {
if(json.status=='OK'){
var results = json.results;
$.each(results,function(index,array){
if(index==0){
$("#google_geo").html(array['formatted_address']);
}
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#google_geo").html(latlon+" Address location acquisition failed ");
}
});
}

The above code integrates Baidu map interface and Google map interface into functions respectively showPosition() in , We can call it according to the actual situation . Of course, it's just a simple application , We can develop many complex applications based on this simple example , It is recommended to use mobile browser to access DEMO demonstration .

Beautiful text, beautiful pictures




AngularJS Advanced ( twenty )HTML5 Achieve access to geographic information and positioning function of more related articles

  1. HTML5 Achieve access to geographic information and positioning function

    HTML5 It provides the function of geographic location (Geolocation API), Able to locate users , We can use HTML5 Based on this feature, we develop applications based on geographic information . In this paper, we will share how to use HTML5, With Baidu . Googleland ...

  2. html5 Achieve access to geographic information and positioning

    This is mainly about h5 Achieve access to geographic information and positioning function , This article explains the original h5, Baidu Maps , Google maps and other three ways to get geographic information and locate , Friends in need can refer to : h5 Provides geographic location capabilities (Geolocation API), can ...

  3. Html5 Geolocation Get geographic location information

    Html5 Provides geographic location information in API, Get the user's current location through the browser . Based on this feature, location-based service applications can be developed . Before getting geographic information , First, browsers ask users if they want to share their location information , It can only be used after the user agrees . ...

  4. Html5 Geolocation Get geographic location information ( turn )

    Html5 Provides geographic location information in API, Get the user's current location through the browser . Based on this feature, location-based service applications can be developed . Before getting geographic information , First, browsers ask users if they want to share their location information , It can only be used after the user agrees . ...

  5. AngularJS Advanced ( Twenty-nine )AngularJS Project development skills localStorage Storage

    AngularJS Project development skills localStorage Storage       notes : localStorage Deep learning Clue Project development is complete , In the test phase, we found that there was a problem in the generation of QR code in the background management side , The problem lies in localStora ...

  6. AngularJS Advanced ( twenty-five )requirejs + angular + angular-route Talking about HTML5 Single page Architecture

    requirejs + angular + angular-route  Talking about HTML5 Single page Architecture as everyone knows , Now move Webapp More and more , For example Tmall . JD.COM . Gome, these are good examples . And in the Webapp in , also ...

  7. AngularJS Advanced ( Twenty-two ) Implementation time selection plug-in

    JS Implementation time selection plug-in Guide language In the process of project development , You need to implement a date based filter , So we need to implement the time selection plug-in . For new things that are untouched , I always feel confused . Actually , Some implementations can be implemented in a very simple way . Take this as an example , accidentally ...

  8. AngularJS Advanced ( hexacosa- ) Realize paging operation

    JS Realize paging operation Preface Project development process , It is possible to retrieve a large number of query results that meet the conditions . Displaying all the query results on one page will reduce the user's experience , So we need to achieve pagination display effect . By the front "JS Implementation time selection plug-in ...

  9. AngularJS Advanced ( Twenty-four )AngularJS Two way dynamic binding with single and multiple selection boxes

    AngularJS Two way dynamic binding with single and multiple selection boxes      A gift of rose , Fragrance in hand . If you feel this blog is useful to you , Please spend 2 Like it in seconds , Your encouragement is the driving force of my continuous progress , Mutual encouragement ! AngularJS  stay  <in ...

Random recommendation

  1. Android Memory cleaning

    Go straight to the picture ! Get file size , Clean up file tool class public class DataCleanManager { public static String getTotalCacheSize(Contex ...

  2. HDU 3966 Aragorn&#39;s Story

    The question : Give a tree , And give the weight of each point , Then there is 3 Kind of operation :I C1 C2 K: hold C1 And C2 The weight of all points on the path plus KD C1 C2 K: hold C1 And C2 The weight of all points on the path minus KQ C: The query node number is C A weight ...

  3. Fragstats Software use and its landscape ecological significance

    [ turn ]Fragstats Software use and its landscape ecological significance     Original address :http://blog.163.com/shuailai@126/blog/static/13238040820104152513 ...

  4. C#.Net How to load and unload assemblies dynamically (.dll perhaps .exe)0------- Through the application domain AppDomain Loading and unloading assemblies

    In this blog “C#.Net How to load and unload assemblies dynamically (.dll perhaps .exe)” Don't ask where the slave is The door of Microsoft's assembly car seems to be only open for cargo loading , But turn off the unloading workers . There's only one key to the door , If you want to get it, you need ...

  5. Oracle Take the query statement of last Monday to weekend

    -- Oracle From Monday to weekend sql -- So what we take is On the day of the week , It starts on Sunday select to_char(to_date('20130906','yyyymmdd'),'d') f ...

  6. springMVC Our interceptor workflow

    First ,springmvc I won't say much about the interceptor configuration of . Mainly talk about the execution sequence of the three methods of interceptor . preHandle Methods must be the first to execute , If it returns as false None of the following methods are executed . postHandle ...

  7. 《Google The way of software testing 》【PDF】 download

    <Google The way of software testing >[PDF] Download link : https://u253469.pipipan.com/fs/253469-230382198 Content introduction Every day ,Google We have to test and release ...

  8. 20175324 《Java Programming 》 Week 7 learning summary

    Summary of the learning content of the textbook Common practical class String class - The program can be used directly String class , But it can't be extended , namely String A class cannot have subclasses - Common construction methods - String(char a[]) With an array of characters a gen ...

  9. node.js frame express About router The use of

    1.express Routing entry const express = require('express'); let server = express(); server.listen(8087); // user ...

  10. Android Development _ Talking about Fragment And ListFragment

    ListFragment, namely Fragment A subclass of , When we use a Fragment Just one listview View, use This class has several characteristics : 1.ListFragment There is only one in itself ListV ...