我试图使用Geolocation查找计算机的位置,而且我很难搞清楚。我希望它连接到一个事件监听器,当单击该段落时,它会运行。
这是我的HTML:
<p id="para1">
Click to find location
</p>
这是我的剧本:
//Global variables
var elMap = document.getElementById("para1");
var msg = 'Sorry, we were unable to get your location';
if (Modernizr.geolocation) {
navigator.geolocation.getCurrentPosition(success, fail);
elMap.textContent = 'Checking location...';
} else {
elMap.textContent = msg;
}
//Event listeners
document.getElementById("para1").addEventListener("click", geoAPI);
function geoAPI() {
function success(position) {
msg = '<h3>Longitude:<br>';
msg += position.coords.longitude + '</h3>';
msg += '<h3>Latitude:<br>';
msg += position.coords.latitude + '</h3>';
elMap.innerHTML = msg;
}
function fail(msg) {
elMap.textContent = msg;
console.log(msg.code);
}
}
答案 0 :(得分:0)
我明白了!我很接近,应该是
//Global variables
var elMap = document.getElementById("para1");
var msg = 'Sorry, we were unable to get your location';
function success(position) {
msg = '<h3>Longitude:<br>';
msg += position.coords.longitude + '</h3>';
msg += '<h3>Latitude:<br>';
msg += position.coords.latitude + '</h3>';
elMap.innerHTML = msg;
}
function fail(msg) {
elMap.textContent = msg;
console.log(msg.code);
}
//Event listeners
function geoAPI() {
if (Modernizr.geolocation) {
navigator.geolocation.getCurrentPosition(success, fail);
elMap.textContent = 'Checking location...';
} else {
elMap.textContent = msg;
}
}
elMap.addEventListener('click', geoAPI);