Home >Web Front-end >JS Tutorial >How to use HTML5 geolocation function_jquery
HTML5 provides a geolocation function (Geolocation API), which can determine the user's location. We can use this feature of HTML5 to develop applications based on geolocation information. This article uses examples to share with you how to use HTML5 and use Baidu and Google Maps interfaces to obtain users' accurate geographical location information.
Geolocation is a new feature of HTML5, so it can only run on modern browsers that support HTML5, especially handheld devices such as iPhones, where geolocation is more accurate. First we need to detect whether the user's device browser supports geolocation, and if so, obtain the geographic information. Note that this feature may infringe on the user's privacy. Unless the user agrees, the user's location information is not available. Therefore, when we access the application, we will be prompted whether to allow geolocation. Of course, we can choose to allow it.
function getLocation(){ if (navigator.geolocation){ navigator.geolocation.getCurrentPosition(showPosition,showError); }else{ alert("浏览器不支持地理定位。"); } }
The above code can know that if the user device supports geolocation, the getCurrentPosition() method is run. If getCurrentPosition() runs successfully, a coordinates object is returned to the function specified in the parameter showPosition. The second parameter showError of the getCurrentPosition() method is used to handle errors. It specifies the function to be run when obtaining the user's position fails.
Let’s first look at the function showError(), which stipulates some error code handling methods when failed to obtain the user’s geographical location:
function showError(error){ switch(error.code) { case error.PERMISSION_DENIED: alert("定位失败,用户拒绝请求地理定位"); break; case error.POSITION_UNAVAILABLE: alert("定位失败,位置信息是不可用"); break; case error.TIMEOUT: alert("定位失败,请求获取用户位置超时"); break; case error.UNKNOWN_ERROR: alert("定位失败,定位系统失效"); break; } }
Let’s look at the function showPosition() again, calling the latitude and longitude of coords to get the user’s latitude and longitude.
function showPosition(position){ var lat = position.coords.latitude; //纬度 var lag = position.coords.longitude; //经度 alert('纬度:'+lat+',经度:'+lag); }
Use Baidu Maps and Google Maps interfaces to obtain user addresses
Above we learned that HTML5's Geolocation can obtain the user's longitude and latitude, so what we need to do is to convert the abstract longitude and latitude into readable and meaningful real user geographical location information. Fortunately, Baidu Maps and Google Maps provide interfaces in this regard. We only need to pass the longitude and latitude information obtained by HTML5 to the map interface, and the user's geographical location will be returned, including province and city information, and even streets, House number and other detailed geographical location information.
We first define the div to display the geographical location on the page, defining id#baidu_geo and id#google_geo respectively. We only need to modify the key function showPosition(). Let's first look at the Baidu map interface interaction. We send the latitude and longitude information to the Baidu map interface through Ajax, and the interface will return the corresponding province, city, and street information. The Baidu map interface returns a string of JSON data. We can display the required information to div#baidu_geo according to our needs. Note that the jQuery library is used here, and the jQuery library file needs to be loaded first.
function showPosition(position){ var latlon = position.coords.latitude+','+position.coords.longitude; //baidu var url = "http://api.map.baidu.com/geocoder/v2/?ak=C93b5178d7a8ebdb830b9b557abce78b&callback=renderReverse&location="+latlon+"&output=json&pois=0"; $.ajax({ type: "GET", dataType: "jsonp", url: url, beforeSend: function(){ $("#baidu_geo").html('正在定位...'); }, success: function (json) { if(json.status==0){ $("#baidu_geo").html(json.result.formatted_address); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { $("#baidu_geo").html(latlon+"地址位置获取失败"); } }); });
Let’s look at Google Maps interface interaction. Similarly, we send the latitude and longitude information to the Google Maps interface through Ajax, and the interface will return the corresponding province, city, and street details. The Google map interface also returns a string of JSON data. These JSON data are more detailed than those returned by the Baidu map interface. We can display the required information to div#google_geo according to our needs.
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('正在定位...'); }, 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+"地址位置获取失败"); } }); }
The above code integrates the Baidu map interface and the Google map interface into the function showPosition() respectively, which we can call according to the actual situation. Of course, this is just a simple application. We can develop many complex applications based on this simple example. It is recommended to use a mobile browser to access the DEMO demonstration.