【问题标题】:Free alternatives to getCurrentPosition() for websites without SSL?没有 SSL 的网站的 getCurrentPosition() 的免费替代品?
【发布时间】:2016-12-18 23:00:32
【问题描述】:

首先,我知道这个post 存在。我需要一个免费(或非常便宜)的解决方案,所以我再次问这个问题。

getCurrentPosition() 和 watchPosition() 在不安全的来源上被弃用。要使用此功能,您应该考虑将您的应用程序切换到安全来源,例如 HTTPS。

Chrome 已禁止在没有 SSL 的网站上使用 getCurrentPosition()。

Google Maps API 可以解决这个问题,但它的usage limits 太低了。 (我们正在管理一个每天浏览量超过 400,000 次的新闻门户)。

有没有人知道 getCurrentPosition() 的任何免费(或非常便宜)的替代方法?

【问题讨论】:

    标签: javascript browser geolocation location


    【解决方案1】:

    您可以为此使用https://ipinfo.io API(这是我的服务)。每天最多 1,000 个请求是免费的(有或没有 SSL 支持)。它为您提供坐标、名称等。这是一个例子:

    curl ipinfo.io
    {
      "ip": "172.56.39.47",
      "hostname": "No Hostname",
      "city": "Oakland",
      "region": "California",
      "country": "US",
      "loc": "37.7350,-122.2088",
      "org": "AS21928 T-Mobile USA, Inc.",
      "postal": "94621"
    }
    

    这是一个示例,它使用与您从getCurrentPosition() 获得的内容相匹配的 API 响应构造一个 coords 对象:

    $.getJSON('https://ipinfo.io/geo', function(response) { 
        var loc = response.loc.split(',');
        var coords = {
            latitude: loc[0],
            longitude: loc[1]
        };
    });
    

    这里有一个详细的示例,展示了如何将其用作getCurrentPosition() 的后备:

    function do_something(coords) {
        // Do something with the coords here
    }
    
    navigator.geolocation.getCurrentPosition(function(position) { 
        do_something(position.coords);
        },
        function(failure) {
            $.getJSON('https://ipinfo.io/geo', function(response) { 
            var loc = response.loc.split(',');
            var coords = {
                latitude: loc[0],
                longitude: loc[1]
            };
            do_something(coords);
            });  
        };
    });
    

    【讨论】:

    • 谢谢,但这并不能回答我的问题。还是谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 2010-11-08
    • 2022-12-04
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    相关资源
    最近更新 更多