How do I use HTML5 geolocation

  • 2020-06-01 08:18:16
  • OfStack

HTML5 provides geolocation (Geolocation API), which can determine the user's location. We can use this feature to develop applications based on geolocation information. This paper combined with an example to share with you how to use HTML5, with the help of baidu, Google map interface to obtain users' accurate geographical location information.

Location (Geolocation) is a new feature of HTML5, so it only works on modern browsers that support HTML5, especially handheld devices like iphone that are more geolocation accurate. First, we check whether the user's device browser supports geolocation, and if so, get the geographic information. Note that this feature may violate the user's privacy. Unless the user agrees, the user's location information is not available, so when we access the application, we will be prompted whether to allow geolocation or not. Of course, we will choose to allow.


 
function getLocation(){ 
  if (navigator.geolocation){ 
    navigator.geolocation.getCurrentPosition(showPosition,showError); 
  }else{ 
    alert(" The browser does not support geolocation. "); 
  } 
} 

As you can see from the code above, if the user device supports geolocation, then run the getCurrentPosition() method. If getCurrentPosition() runs successfully, one coordinates object is returned to the function specified in the showPosition parameter. The second parameter of the getCurrentPosition() method, showError, handles the error, which specifies the function to run when the user location acquisition fails.
Let's start with the function showError(), which specifies how to handle some error codes when getting the user's location fails:


function showError(error){ 
  switch(error.code) { 
    case error.PERMISSION_DENIED: 
      alert(" To locate failure , The user denied the request for geolocation "); 
      break; 
    case error.POSITION_UNAVAILABLE: 
      alert(" To locate failure , Location information is not available "); 
      break; 
    case error.TIMEOUT: 
      alert(" To locate failure , Request gets user location timeout "); 
      break; 
    case error.UNKNOWN_ERROR: 
      alert(" To locate failure , Location system failure "); 
      break; 
  } 
} 

Let's look at the function showPosition(), which calls coords's latitude and longitude to get the user's latitude and longitude.


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

Baidu map and Google map interface to obtain user address
Above, we learned that Geolocation of HTML5 can get the user's latitude and longitude, so what we need to do is turn the abstract latitude and longitude into readable and meaningful real user location information. Fortunately, baidu map and Google map provide this interface. We only need to pass the latitude and longitude information obtained by HTML5 to the map interface, and then the user's geographical location will be returned, including the provincial and urban information, and even the detailed geographical location information such as street and house number.
We first define div on the page to show the location, id#baidu_geo and id#google_geo, respectively. We just need to modify the key function showPosition(). First, let's look at the baidu map interface interaction. We will send the latitude and longitude information to the baidu map interface through Ajax, and the interface will return the corresponding provincial and urban street information. Baidu map interface returns a string of JSON data, and we can display the required information to div # baidu_geo according to the requirements. Notice that the jQuery library is used, and you need to load the jQuery library file 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(' Is located ...'); 
    }, 
    success: function (json) { 
      if(json.status==0){ 
        $("#baidu_geo").html(json.result.formatted_address); 
      } 
    }, 
    error: function (XMLHttpRequest, textStatus, errorThrown) { 
      $("#baidu_geo").html(latlon+" Failed to get address location "); 
    } 
  }); 
}); 

Let's look at the Google map interface interaction. Similarly, we send the latitude and longitude information to the Google map interface via Ajax, and the interface will return the corresponding provincial and urban street details. Google map interface also returns a string of JSON data, which is more detailed than that returned by baidu map interface. We can display the required information to div # google_geo according to the requirements.


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(' Is located ...'); 
    }, 
    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+" Failed to get address location "); 
    } 
  }); 
} 

The above code respectively integrates baidu map interface and Google map interface into the function showPosition (), which we can call according to the actual situation. Of course, this is only a simple application, we can develop many complex applications based on this simple example, it is recommended to use the mobile browser to access the DEMO demo.


Related articles: