Comments: This article mainly introduces how to use html5 code to obtain geographical locations. The specific implementation code is as follows. For more information, see
The Code is as follows:
/**
* The following is the html5 code used to obtain the geographical location.
*/
Function getLocation (){
// Check whether the browser supports obtaining geographical locations
If (navigator. geolocation ){
// If the location can be obtained, showPosition () is successfully called, and showError is not called.
// Alert ("trying to get 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 ("locating failed, the user has disabled location obtaining permission ");
}
}
/**
* Address location retrieved
*/
Function showPosition (position ){
// Obtain the longitude and latitude
Var x = position. coords. latitude;
Var y = position. coords. longpolling;
// Configure the 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 + "] failed to get the address location. Please manually select the address ");
}
});
}
/**
* An error occurred while obtaining the address location.
*/
Function showError (error ){
Switch (error. code ){
Case error. PERMISSION_DENIED:
Alert ("location failed, user refused to request location ");
// X. innerHTML = "User denied the request for Geolocation. [the User rejects the request for geographic location]"
Break;
Case error. POSITION_UNAVAILABLE:
Alert ("positioning failed, location information is unavailable ");
// X. innerHTML = "Location information is unavailable. [Location information is unavailable]"
Break;
Case error. TIMEOUT:
Alert ("locating failed, request to get user location timeout ");
// X. innerHTML = "The request to get user location timed out. [request to get user location timeout]"
Break;
Case error. UNKNOWN_ERROR:
Alert ("locating failed, locating system failed ");
// X. innerHTML = "An unknown error occurred. [unknown error]"
Break;
}
}
/**
* Set the address
*/
Function setAddress (json ){
Var position = document. getElementById ("txtPosition ");
// Save
Var province = json. province;
// City
Var city = json. city;
// Zone
Var district = json. district;
Province = province. replace ('city ','');
Position. value = province + "," + city + "," + district;
Position. style. color = 'black ';
}