5

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

$(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 中却不行。也没有警报错误消息。

4

3 回答 3

10

试试这个,我希望这会帮助你:

<!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>
于 2013-07-09T06:08:02.693 回答
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>

参考

于 2018-11-18T12:35:59.837 回答
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);
        });
于 2020-11-04T10:38:50.867 回答