为什么移动浏览器上的地理定位不起作用?

6

我正在尝试使用HTML5的geolocation获取用户位置。在桌面端,它运作良好,但在所有移动设备上(Samsung Note、Samsung Galaxy S4和iPhone 6)都无法运作,并且没有显示error对象。

这是我的代码:

function showPosition(position) {
    var coor = position.coords.longitude+", "+position.coords.latitude;
    alert(coor);
}
function errorPosition(error) {
    alert(error);
}
function toggleGeolocation() {
    navigator.geolocation.watchPosition(showPosition,errorPosition);
}

当它要求获取地理位置权限时,我点击允许(GPS正在工作)。可能出了什么问题?

我在所有设备上使用的是Google Chrome浏览器。


1
这段代码在我的iPhone 5上运行iOS 8.1的Safari和Chrome,以及在我的Galaxy Tab 4 Kit-Kat上在Chrome和Android原生浏览器中也能正常工作。这段代码不是导致问题的原因。 - blex
4个回答

6

试试用这段代码,应该可以工作。

var successHandler = function(position) { 
alert(position.coords.latitude); 
alert(position.coords.longitude); 
}; 

var errorHandler = function (errorObj) { 
alert(errorObj.code + ": " + errorObj.message); 

alert("something wrong take this lat " + 26.0546106 ); 
alert("something wrong take this lng " +-98.3939791); 

}; 

navigator.geolocation.getCurrentPosition( 
successHandler, errorHandler, 
{enableHighAccuracy: true, maximumAge: 10000});

感谢您的回答,但我仍然无法获得错误消息,我添加了像这样的警报消息: function initializeGeo() { if (navigator && navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition, errorCallback); alert("OK"); } else { alert('不支持地理定位'); } } 而我收到了这条消息,这意味着地理定位被支持,但是这一行: navigator.geolocation.getCurrentPosition(showPosition, errorCallback); 没有起作用... - Jordan
我已经在调用getCurrentPosition的行后添加了警报消息,我可以看到警报消息,但无法看到getCurrentPosition的结果。 - Jordan
然后呢?问题解决了吗?Geolocation 只在安全上下文中可用。因此,如果您没有使用 https 提供应用程序,则在几乎所有支持的浏览器中,除非来源是 localhost,否则它将无法工作。 - sçuçu

4

在Android上,Navigator仅适用于https网站。以下是一个示例,如果使用http将不会显示错误,但在https上可以正常工作 (来自https://www.w3schools.com/HTML/tryit.asp?filename=tryhtml5_geolocation)

<!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>

谢谢您的回复。在安卓Chrome上能否使其在本地主机上运行? - Ranjit Kumar
@RanjitKumar 你可以创建自签名证书。Let's Encrypt 的官网上有一些关于如何自行创建证书的说明:https://letsencrypt.org/docs/certificates-for-localhost/ - Schwarz Software

1

嗨@jordan,我遇到了同样的问题,我做的是:

首先确保您的设备上已更新Chrome浏览器。

  1. 首先启动移动设备的位置服务

  2. 在加载时调用getLocation()函数

这样做会询问我是否允许权限,并且可以正常工作。


这实际上是简单而正确的答案,我尝试使用window.onload = getLocation;和getLocation函数,我调用它时没有括号,但是加上括号后,在我的移动设备上也可以正常工作。谢谢。 - saadeez

0

    // google geolocation
    googleMap: function(func){
        if (navigator.geolocation) {

            //get location
            navigator.geolocation.getCurrentPosition(function(position) {
                var coords = position.coords;
                lat = coords.latitude;
                lng = coords.longitude;

                var latlng = new google.maps.LatLng(lat, lng);
                var geocoder = new google.maps.Geocoder();
                geocoder.geocode( {'location': latlng}, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {

                        var time = Date.parse(new Date());
                        var resultArr = results[0].address_components, address = "" ,LocationName = "",province = "",city = "",district = "";

                        for (var i = 0; i < resultArr.length; i++) {
                            var type = resultArr[i].types[0] ? resultArr[i].types[0] : 0;
                            if (type && type == "street_number") {
                                LocationName = resultArr[i].short_name;
                            }
                            if (type && type == "route") {
                                address = address + resultArr[i].short_name;
                            }
                            if (type && type == "political") {
                                district = resultArr[i].short_name;
                            }
                            if (type && type == "locality") {
                                city = resultArr[i].short_name;
                            }
                            if (type && type == "administrative_area_level_1") {
                                province = resultArr[i].short_name;
                            }
                        }

                        var data = {'name': LocationName + ' ' + address, 'address': address, 'lng': lng, 'lat': lat, 'province': province, 'city': city, 'district': district};
                        func(data);

                    } else {
                        func();
                        alert('Geocode was not successful for the following reason: ' + status);
                    }
                });

            }, function getError(error){
                func();
                switch(error.code){
                    case error.TIMEOUT:
                        alert(langData['siteConfig'][22][100]);
                        break;
                    case error.PERMISSION_DENIED:
                        alert(langData['siteConfig'][22][101]);
                        break;
                    case error.POSITION_UNAVAILABLE:
                        alert(langData['siteConfig'][22][102]);
                        break;
                    default:
                        break;
                }
            })
        }else {
            func();
            alert(langData['waimai'][3][72])
        }
    },
h5: function(func){
        if (navigator.geolocation) {
            if ("function" == typeof func) {
                h5LocationInit.fn = func
            }
            window.touchH5LocationCallback = function(f, g) {
                if(f == null){
                    HN_Location.getLocationByGeocoding(g);
                }else{
                    // getLocationError(f);
                    HN_Location.init(func, true);
                }
                $("#touchH5LocationIframe").remove();
            },
                $('<iframe src="javascript:(function(){ window.navigator.geolocation.getCurrentPosition(function(position){parent && parent.touchH5LocationCallback && parent.touchH5LocationCallback(null,position);}, function(err){parent && parent.touchH5LocationCallback && parent.touchH5LocationCallback(err);}, {enableHighAccuracy: 1, maximumAge: 10000, timeout: 5000});})()" style="display:none;" id="touchH5LocationIframe" ></iframe>').appendTo("body")
        } else {
            // var r = {
            //   tips: "broswer not supported"
            // };
            // "function" == typeof func ? func(r) : "[object Object]" === Object.prototype.toString.call(func) && func.fn && func.fn(r)
            HN_Location.init(func, true);
        }
    },
    
    

我完全理解你的情况。找到答案真的很难...


2
你觉得在回答中加入一些解释性的文字怎么样?这样可以让你的解决方案更易于理解。 - PowerStat
哦,我的当前情况是地理位置可以在电脑浏览器中调用,但在手机浏览器上无法工作。位置权限请求将弹出,但此后不会有任何响应... - Ken Too

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接