2017-11-04 146 views
0

我正在嘗試使用地理位置查找我的計算機的位置,並且我很難找出它。我希望它連接到一個事件監聽器,當該段落被點擊時,它會運行。如何使用地理位置查找位置?

這裏是我的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

我知道了!我很接近,應該是

//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);