【问题标题】:Why does geolocation not work on mobile browsers?为什么地理定位在移动浏览器上不起作用?
【发布时间】:2015-02-04 19:53:17
【问题描述】:

我正在尝试使用 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。

【问题讨论】:

  • 它适用于我在 Safari 和 Chrome 上运行 iOS 8.1 的 iPhone 5,以及在 Chrome 和 Android 股票浏览器中运行的 Galaxy Tab 4 Kit-Kat。此代码不是导致此问题的原因。

标签: javascript html geolocation


【解决方案1】:

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

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,错误回调);警报(“确定”); } else { alert('不支持地理位置');我得到了这个消息,它的意思是支持地理定位,但行:navigator.geolocation.getCurrentPosition(showPosition, errorCallback);什么都不做……
  • 我在调用 getCurrentPosition 的行之后添加了警报消息,我可以看到警报消息但看不到 getCurrentPosition 的结果
  • 然后呢?解决了还是没有? Geolocation安全上下文中可用。因此,如果您在没有 https 的情况下不提供应用程序,除非在几乎所有支持的浏览器中来源是 localhost,否则它将无法工作。
【解决方案2】:

Navigator 仅适用于 https 网站上的 Android。 这是一个使用 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>

【讨论】:

  • 感谢您的回复。是否可以使其在 android chrome 中的 localhost 上运行?
  • @RanjitKumar 您可以制作自签名证书。 Let's Encrypt 有一些关于如何自己做的说明:letsencrypt.org/docs/certificates-for-localhost
【解决方案3】:

嗨@jordan,我遇到的和我做的一样

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

  1. 开始第一台移动设备的定位服务

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

通过这样做,它询问了我的许可并且效果很好。

【讨论】:

  • 这实际上是简单而正确的答案,我尝试使用 window.onload = getLocation;我调用的 getLocation 函数不带括号,但带括号的它也适用于移动设备。谢谢。
【解决方案4】:

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

我和你的情况完全一样。很难找到答案...

【讨论】:

  • 如何在您的答案中添加一些解释性文本 - 以便更容易理解您的解决方案?
  • 嗯,我目前的情况是地理位置可以在电脑浏览器上调用,但在手机浏览器上不起作用。位置权限请求会弹出,但之后不会有任何响应...
猜你喜欢
  • 1970-01-01
  • 2021-08-16
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-15
相关资源
最近更新 更多