页面加载时获取位置

问题描述 投票:3回答:1

我正在使用HTML,CSS和Java脚本构建一个网站。我想在页面加载时获取用户的位置。所以他们不需要按一下按钮。我希望有人可以提供帮助。

!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your coordinates:</p>
<button onclick="getLocation()">Try It</button>
<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>
javascript html css html5 geolocation
1个回答
4
投票

只需致电getLocation()

<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;  
        }
        getLocation()
        </script>

小提琴:https://jsfiddle.net/ES4TF/

© www.soinside.com 2019 - 2024. All rights reserved.