Comment: This article mainly introduces the use of html5 code to obtain geographical location. The specific implementation code is as follows and screenshots are attached. Friends who need it can refer to it.
/**
* The following is html5 code to get the geographical location
*/
function getLocation() {
//Check whether the browser supports geographic location acquisition
if (navigator.geolocation) {
//If you support geographic location acquisition, you will call showPosition() successfully, and call showError if you fail.
// alert("Strive to obtain location...");
var config = { enableHighAccuracy: true, timeout: 5000, maximumAge: 30000 };
navigator.geolocation.getCurrentPosition(showPosition, showError, config);
} else {
//alert("Geolocation is not supported by this browser.");
alert("Location failed, the user has disabled location access");
}
}
/**
* Get the address location successfully
*/
function showPosition(position) {
//Get the latitude and longitude
var x = position.coords.latitude;
var y = position.coords.longitude;
//Configure Baidu Geocoding API
var url = "http://api.map.baidu.com/geocoder/v2/?ak=C93b5178d7a8ebdb830b9b557abce78b" +
"&callback=renderReverse" +
"&location=" + x + "," + y +
"&output=json" +
"&pois=0";
$.ajax({
type: "GET",
dataType: "jsonp",
url: url,
success: function (json) {
if (json == null || typeof (json) == "undefined") {
return;
}
if (json.status != "0") {
return;
}
setAddress(json.result.addressComponent);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("[x:" + x + ",y:" + y + "]The address location failed to be retrieved, please manually select the address");
}
});
}
/**
* Failed to obtain the address location [Not processed yet]
*/
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("Location failed, user refuses to request geolocation");
//x.innerHTML = "User denied the request for Geolocation.[User denied request geolocation]"
break;
case error.POSITION_UNAVAILABLE:
alert("Location failed, location information is unavailable");
//x.innerHTML = "Location information is unavailable.[Location information is unavailable]"
break;
case error.TIMEOUT:
alert("Location failed, request to obtain user location timed out");
//x.innerHTML = "The request to get user location timed out.[Request to get user location timed out]"
break;
case error.UNKNOWN_ERROR:
alert("Location failed, positioning system failed");
//x.innerHTML = "An unknown error occurred.[Unknown error]"
break;
}
}
/**
* Set the address
*/
function setAddress(json) {
var position = document.getElementById("txtPosition");
//Province
var province = json.province;
//city
var city = json.city;
//district
var district = json.district;
province = province.replace('City', '');
position.value = province + "," + city + "," + district;
position.style.color = 'black';
}