查找当前位置的纬度和经度

时间:2013-07-09 05:18:13

标签: javascript jquery html5 firefox mozilla

我正在使用此代码查找当前位置纬度和经度。

$(document).ready(function() {
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
    }
    else 
    {
        alert('It seems like Geolocation, which is required for this page, is not enabled in your browser.');
    }       
});

function successFunction(position) 
{
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    alert('Your latitude is :'+lat+' and longitude is '+long);
}

function errorFunction(position) 
{
    alert('Error!');
}

它在Chrome中运行良好但在Mozilla中运行不正常。也没有警报错误消息。

3 个答案:

答案 0 :(得分:5)

试试这个我希望这会对你有所帮助:

<!DOCTYPE html>
<html>
  <head>
   <script type="text/javascript">
     function initGeolocation()
     {
        if( navigator.geolocation )
        {
           // Call getCurrentPosition with success and failure callbacks
           navigator.geolocation.getCurrentPosition( success, fail );
        }
        else
        {
           alert("Sorry, your browser does not support geolocation services.");
        }
     }

     function success(position)
     {

         document.getElementById('long').value = position.coords.longitude;
         document.getElementById('lat').value = position.coords.latitude
     }

     function fail()
     {
        // Could not obtain location
     }

   </script>    
 </head>

 <body onLoad="initGeolocation();">
   <FORM NAME="rd" METHOD="POST" ACTION="index.html">
     <INPUT TYPE="text" NAME="long" ID="long" VALUE="">
     <INPUT TYPE="text" NAME="lat" ID="lat" VALUE="">
 </body>
</html>

答案 1 :(得分:1)

您可以尝试以下代码:-

<!DOCTYPE html>
<html>
<body>

<p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

<script>
var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;
}
</script>

</body>
</html>

Reference

答案 2 :(得分:0)

通过使用下面的jQuery代码,您可以找到当前位置的纬度和经度而无需任何API密钥。让我们尝试

 $(document).ready(function(){
     
        // get users lat/long
        
        var getPosition = {
          enableHighAccuracy: false,
          timeout: 9000,
          maximumAge: 0
        };
        
        function success(gotPosition) {
          var uLat = gotPosition.coords.latitude;
          var uLon = gotPosition.coords.longitude;
          console.log(`${uLat}`, `${uLon}`);
        
        };
        
        function error(err) {
          console.warn(`ERROR(${err.code}): ${err.message}`);
        };
        
        navigator.geolocation.getCurrentPosition(success, error, getPosition);
        });
相关问题