是否可以使用JavaScript和/或HTML代码而不提示用户?
我希望以文本格式打印其位置(城市或国家/地区)。
答案 0 :(得分:1)
查看此链接:https://www.w3schools.com/Html/html5_geolocation.asp
使用GEOLocation,HTML5可以获取您的当前位置。
下面的代码将不起作用,因为:
要在您的网站上使用此代码,请从Google获得免费的API密钥。要了解更多信息,请访问:https://www.w3schools.com/graphics/google_maps_basic.asp
获得API密钥后,此代码即可在您的网站上运行。如果您想查看有效的版本,请访问:https://www.w3schools.com/Html/tryit.asp?filename=tryhtml5_geolocation_map
该代码基本上会获取您的纬度和经度,并将其绘制在Google地图中。
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
var img_url = "https://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&zoom=14&size=400x300&key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}
//To use this code on your website, get a free API key from Google.
//Read more at: https://www.w3schools.com/graphics/google_maps_basic.asp
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your position.</p>
<button onclick="getLocation()">Try It</button>
<div id="mapholder"></div>
</body>
</html>
还有一件事情,如果您想让国家和城市在这里查看第一个答案:How to get client's IP address using JavaScript?。那应该可以帮到你。
希望这对您有帮助!