Using relatively simple JavaScript code, you can create web applications that can determine the details of the user's geographical location, including latitude and longitude and altitude. Some web applications can even provide navigation functions by monitoring the movement of user locations over time, which also integrates map systems such as the GoogleMaps API.
HTML5 provides geolocation API to determine user location. We can use this feature of HTML5 to develop applications based on geolocation information. This article combines examples to share with you how to use HTML5 and use Baidu and Google map interfaces to obtain users' accurate geographical location information.
Geolocation is a new feature of HTML5, so it is only possible to 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 browser of the user device supports geolocation, and if so, obtain geographic information. Note that this feature may infringe on the user's privacy. Unless the user's consent is, the user's location information is unavailable, so when we access the application, we will prompt whether to allow geolocation, and of course we can choose to allow.
- functiongetLocation(){
- if(navigator.geolocation){
- navigator.geolocation.getCurrentPosition(showPosition,showError);
- }else{
- alert (The browser does not support geolocation.);
- }
- }
The above code shows that if the user device supports geolocation, run the getCurrentPosition() method. If getCurrentPosition() runs successfully, a coordinates object is returned to the function specified in the parameter showPosition. The second parameter of the getCurrentPosition() method is used to handle the error, which specifies the function that runs when the user location fails to get.
Let's first look at the function showError(), which specifies the handling of some error codes when obtaining the user's geographical location:
- functionshowError(error){
- switch(error.code){
- caseerror.PERMISSION_DENIED:
- alert (localization failed, user refuses to request geolocation);
- break;
- caseerror.POSITION_UNAVAILABLE:
- alert (localization failed, location information is unavailable);
- break;
- caseerror.TIMEOUT:
- alert (locating failed, requesting to obtain user location timeout);
- break;
- caseerror.UNKNOWN_ERROR:
- alert (localization failed, positioning system failed);
- break;
- }
- }
Let's look at the function showPosition(), and call the latitude and longitude of coords to get the user's latitude and longitude.
- functionshowPosition(position){
- varlat=position.coords.latitude;//latitude
- varlag=position.coords.longitude;//Longitude
- alert('lat:'+lat+', longitude:'+lag);
- }
Use Baidu Maps and Google Maps interfaces to obtain user addresses
As we understand that HTML5's Geolocation can obtain the user's latitude and longitude, what we need to do is to convert abstract latitude and longitude into readable meaningful real user geographic location information. Fortunately, Baidu Maps and Google Maps provide interfaces in this regard. We only need to pass the latitude and longitude information obtained by HTML5 to the map interface, and it will return the user's geographical location, including provincial, municipal and regional information, and even detailed geographical location information such as streets and house numbers.
We first define the div to display the geographical location on the page, and define id#baidu_geo and id#google_geo respectively. We just 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 provincial, municipal and street information. Baidu map interface returns a string of JSON data, and 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.
- functionshowPosition(position){
- varlatlon=position.coords.latitude+','+position.coords.longitude;
- //baidu
- varurl=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('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 failed);
- }
- });
- });
Let’s look at Google Maps Interface Interaction. Similarly, we send 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 Maps interface also returns a string of JSON data. These JSON data are more detailed than those returned by Baidu Maps interface. We can display the required information to div#google_geo according to our needs.
- functionshowPosition(position){
- varlatlon=position.coords.latitude+','+position.coords.longitude;
- varurl='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'){
- varresults=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 failed);
- }
- });
- }
The above code integrates the Baidu map interface and the Google map interface into the function showPosition() respectively, and we can call it 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.