我试图让这个地理位置脚本工作,但是对于我自己,我总是得到"无法找回你的位置"。这是指向网页的链接,其中包含我想要的实时结果。我尝试将jsfiddle复制到一个空白的,包含所有相同的HTML,JS和CSS。但是,我无法使其发挥作用。我需要API密钥或其他东西吗?如果你需要我详细说明,我很高兴,谢谢你的时间。
以下是实时结果的链接(点击后向下滚动) https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation
https://jsfiddle.net/yotzincastrejon/bwujL03d/
HTMl
<p><button onclick="geoFindMe()">Show my location</button></p>
<div id="out"></div>
JS
function geoFindMe() {
var output = document.getElementById("out");
if (!navigator.geolocation){
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
output.appendChild(img);
}
function error() {
output.innerHTML = "Unable to retrieve your location";
}
output.innerHTML = "<p>Locating…</p>";
navigator.geolocation.getCurrentPosition(success, error);
}
答案 0 :(得分:1)
立即工作https://jsfiddle.net/bwujL03d/1/
您需要将此代码放在头部(在页面加载之前)
function geoFindMe() {
var output = document.getElementById("out");
if (!navigator.geolocation){
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
output.appendChild(img);
}
function error() {
output.innerHTML = "Unable to retrieve your location";
}
output.innerHTML = "<p>Locating…</p>";
navigator.geolocation.getCurrentPosition(success, error);
}